http://stackoverflow.com/q/51515638
has comment: http://stackoverflow.com/comment/90000532
has comment: http://stackoverflow.com/comment/90000388
has comment: http://stackoverflow.com/comment/90000444
tagged with: python
has body: How would I be able to use a while loop in the background process of my django project? I want my project to run a while loop even when the web app is not on. How would I be able to do that? Command Line management? or Celery? or Cron job? Thanks in advance.
has comment: http://stackoverflow.com/comment/89999682
has comment: http://stackoverflow.com/comment/90000022
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90001777
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/89999657
has comment: http://stackoverflow.com/comment/90000184
has title: Django: how to have a while loop that runs in the background process?
score: 1
has comment: http://stackoverflow.com/comment/89999680
type: Question
has comment: http://stackoverflow.com/comment/90000412
downvote count: 0
has comment: http://stackoverflow.com/comment/90000548
favorite count: 0

http://stackoverflow.com/q/51505925
tagged with: python
type: Question
has body: #Collecting Data from these columns X = dataframe['Primary Type'].value_counts().loc['THEFT'] y = dataframe['Year'].value_counts() #Dividing Data into Test and Train X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) #Trainng the Algorithm regressor = LinearRegression() regressor.fit(X_train, y_train) #Making the Predictions y_pred = regressor.predict(X_test) #In the form of table df= pd.DataFrame({'Actual': y_test, 'Predict': y_pred}) print (df) I am getting an type error while training a model. I am not getting this how can I overcome on this problem. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) on this statement I am getting problem. Please help me out.
has comment: http://stackoverflow.com/comment/89980873
has answer: http://stackoverflow.com/a/51506275
score: 0
tagged with: typeerror
answer count: 1
type: UnansweredQuestion
has title: TypeError: Singleton array 236724 cannot be considered a valid collection

http://stackoverflow.com/comment/90078143
type: AnswerComment
comment on: http://stackoverflow.com/a/51548779
score: 0
has text: thanks I try. Parallel processing is simple if you have one task per file but there is two tasks per file and I have no idea how to do it. I don't know how to explain in first place :-D
type: Comment

api
tags question: http://stackoverflow.com/q/51502634
tags question: http://stackoverflow.com/q/51636747
tags question: http://stackoverflow.com/q/51587494
tags question: http://stackoverflow.com/q/51606377
tags question: http://stackoverflow.com/q/51638867
tags question: http://stackoverflow.com/q/51613315
tags question: http://stackoverflow.com/q/51619151
tags question: http://stackoverflow.com/q/51488152
type: Tag
tags question: http://stackoverflow.com/q/51509720
tags question: http://stackoverflow.com/q/51560515
tag name: api
tags question: http://stackoverflow.com/q/51548211
tags question: http://stackoverflow.com/q/51523618
tags question: http://stackoverflow.com/q/51500420
tags question: http://stackoverflow.com/q/51489584
tags question: http://stackoverflow.com/q/51617924
tags question: http://stackoverflow.com/q/51618547
tags question: http://stackoverflow.com/q/51607819
tags question: http://stackoverflow.com/q/51565762
tags question: http://stackoverflow.com/q/51610143
tags question: http://stackoverflow.com/q/51512601
tags question: http://stackoverflow.com/q/51507843

http://stackoverflow.com/a/51604451
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Based on the doc:AAD V2.0 end pointRestrictions on protocols ,The OAuth 2.0 Resource Owner Password Credentials Grant is not supported by the v2.0 endpoint. In python ADAL sdk , client secret is not accepted by acquire_token_with_username_password method, so you need to register native app. Sample code: import adal import requests tenant = "" client_id = "app id" # client_secret = "" username = "" password = "” authority = "https://login.microsoftonline.com/" + tenant RESOURCE = "https://graph.microsoft.com" context = adal.AuthenticationContext(authority) # Use this for Client Credentials #token = context.acquire_token_with_client_credentials( # RESOURCE, # client_id, # client_secret # ) # Use this for Resource Owner Password Credentials (ROPC) token = context.acquire_token_with_username_password(RESOURCE, username, password, client_id) graph_api_endpoint = 'https://graph.microsoft.com/v1.0{0}' # /me only works with ROPC, for Client Credentials you'll need /<UsersObjectId/ request_url = graph_api_endpoint.format('/me') headers = { 'User-Agent' : 'python_test', 'Authorization' : 'Bearer {0}'.format(token["accessToken"]), 'Accept' : 'application/json', 'Content-Type' : 'application/json' } response = requests.get(url = request_url, headers = headers) print (response.content) In addition, native app is not necessary if you use REST API, but client secret need to be set. Hope it helps you.
score: 2
accepted answer of: http://stackoverflow.com/q/51566175
upvote count: 2
has comment: http://stackoverflow.com/comment/90203972
has comment: http://stackoverflow.com/comment/90478574
answers question: http://stackoverflow.com/q/51566175

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

http://stackoverflow.com/a/61464583
upvote count: 7
type: Answer
score: 6
has body: Most short way, i think: with ThreadPoolExecutor(max_workers=20) as executor: results = list(tqdm(executor.map(myfunc, range(len(my_array))), total=len(my_array)))
downvote count: 1
answers question: http://stackoverflow.com/q/51601756

http://stackoverflow.com/comment/92767150
type: Comment
type: AnswerComment
has text: Cool, it works if I remove _all_ the new lines, i.e. everything in a single string: display(Markdown("""# Third test \n Here, I also use the display function. \n\n It kind of helps but won't show as I expect""")
comment on: http://stackoverflow.com/a/52825137
score: 0

http://stackoverflow.com/q/51549799
has comment: http://stackoverflow.com/comment/90067841
has comment: http://stackoverflow.com/comment/90067700
has title: input shape of dataset in cnn
score: 0
tagged with: deep-learning
tagged with: keras
has body: My dataset is a simple table of 20 columns and 100,000 rows.It is not a image data as commonly used in CNN. What input shape should I provide in this case? Right now I did- input_shape = (21,109713,1) model.add(Conv2D(32, kernel_size=(5, 5), strides=(1, 1), activation='relu', input_shape=input_shape)) which gives the error- ValueError: rng_mrg cpu-implementation does not support more than (2**31 -1) samples full code- model = Sequential() model.add(Conv2D(32, kernel_size=(5, 5), strides=(1, 1), activation='relu', input_shape=input_shape)) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2))) model.add(Conv2D(64, (5, 5), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(1000, activation='relu')) model.add(Dense(num_classes, activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adam(), metrics=['accuracy']) class AccuracyHistory(keras.callbacks.Callback): def on_train_begin(self, logs={}): self.acc = [] def on_epoch_end(self, batch, logs={}): self.acc.append(logs.get('acc')) history = AccuracyHistory() model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test), callbacks=[history])
has comment: http://stackoverflow.com/comment/90067574
has comment: http://stackoverflow.com/comment/90067616
has comment: http://stackoverflow.com/comment/90067304
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90076368
type: UnansweredQuestion
type: Question
tagged with: theano
has comment: http://stackoverflow.com/comment/90067592
has comment: http://stackoverflow.com/comment/90067066

http://stackoverflow.com/comment/90124478
type: AnswerComment
score: 0
type: Comment
has text: That gives me an error: AssertionError: 3 columns passed, passed data had 1 columns
comment on: http://stackoverflow.com/a/51560753

edit-distance
type: Tag
tags question: http://stackoverflow.com/q/51638807
tag name: edit-distance

http://stackoverflow.com/a/51628058
accepted answer of: http://stackoverflow.com/q/51627530
type: Answer
score: 1
has body: You could just recreate a dataset manually, or use a vtkArrayCalculator Filter for this task, with the following parameters : Coordinate Results : ON Function : "coords" Result Array Type : Float If you used ParaView, it would look like this :
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90228536
answers question: http://stackoverflow.com/q/51627530

http://stackoverflow.com/a/51613269
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51613004
has body: I am pretty sure it overwrites any existing information from before. Scikit Learn docs specify that. Unless you use warm_start = True, fit() calls will overwrite existing data.

http://stackoverflow.com/a/51484790
has body: You can use .copy() with broadcasting, with df being your existing dataframe: df1 = df.copy() df1['country_id'] = 123 df2 = df.copy() df2['country_id'] = 456
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51484601

concatenation
tags question: http://stackoverflow.com/q/51571680
tags question: http://stackoverflow.com/q/51625861
tags question: http://stackoverflow.com/q/51578389
tags question: http://stackoverflow.com/q/51570405
type: Tag
tag name: concatenation
tags question: http://stackoverflow.com/q/51623226
tags question: http://stackoverflow.com/q/51592871
tags question: http://stackoverflow.com/q/51571981
tags question: http://stackoverflow.com/q/51591589
tags question: http://stackoverflow.com/q/51573267
tags question: http://stackoverflow.com/q/51528065
tags question: http://stackoverflow.com/q/51485013
tags question: http://stackoverflow.com/q/51550895

http://stackoverflow.com/comment/90162634
comment on: http://stackoverflow.com/q/51598340
score: 0
type: Comment
type: QuestionComment
has text: Because `count` method doesn't take overlapping substrings into account.

http://stackoverflow.com/a/51590889
has body: You would need to do something like this: from multiprocessing.pool import Pool def all_url(): #Here I append elements to urllist return urllist def new_file(): with Pool() as pool: pool.map(new_file_process_url, all_url()) def new_file_process_url(each): # Creates html file. if __name__ == '__main__': new_file()
answers question: http://stackoverflow.com/q/51590766
type: Answer
has comment: http://stackoverflow.com/comment/90148235
accepted answer of: http://stackoverflow.com/q/51590766
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90147999
has comment: http://stackoverflow.com/comment/90148312
has comment: http://stackoverflow.com/comment/90147847
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/90069259
has text: import cv2 import numpy list_pixel=[] list_label=[] for i in range(0,10): for j in range(0,10): list_pixel.append(cv2.imread("C:\\Users\\kimcho\\Desktop\\testdata\\testdata_"+str(i)+"_0"+str(j)+".png",0)) list_label.append(i) j=0 list_pixel.pop(0) list_label.pop(0) numpy.array(list_pixel) print(list_pixel) print(list_pixel.shape) print(list_pixel[0].shape)
comment on: http://stackoverflow.com/q/51550181
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51503233
answers question: http://stackoverflow.com/q/51502959
has comment: http://stackoverflow.com/comment/89976247
score: 0
has body: You can using IndexSlice df.query('ilevel_0&gt;2') Out[327]: ColInd1 1 2 ColInd2 A B A B 3 0.652576 0.639522 0.52087 0.446931 df.loc[:,pd.IndexSlice[:,'A']] Out[328]: ColInd1 1 2 ColInd2 A A 0 0.092394 0.427668 1 0.326748 0.383632 2 0.717328 0.354294 3 0.652576 0.520870
type: Answer

http://stackoverflow.com/comment/90117569
score: 0
type: Comment
has text: @Rods2292 If the answer does not solve your problem, then please ask your question in such a way that a solution would naturally need to overcome it to be acceptable. Sound good? Or otherwise, please be fair and test out all the solutions before deciding what to settle on.
type: AnswerComment
comment on: http://stackoverflow.com/a/51575137

http://stackoverflow.com/q/51574778
has comment: http://stackoverflow.com/comment/90115356
has title: Python3 - Problems identifying object type
favorite count: 0
has answer: http://stackoverflow.com/a/51574838
score: 0
tagged with: python
linked to: http://stackoverflow.com/q/2225038
has answer: http://stackoverflow.com/a/51574865
type: UnansweredQuestion
upvote count: 1
has body: I should preface my question by saying I'm very new to Python (3 days), with no prior experience at programming, so if I don't understand the answers immediately, please bear with me. I'm using Python 3.5.3, and trying to do the following exercise found here (https://www.practicepython.org): Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. Keep the game going until the user types “exit” So far I got this: import random import sys value=random.randint(0, 10) x=value y=input("I thought of a number between 0 and 100. Try to guess what it was! ") z=type(y) if z==int: if y&lt;x: print("too low!") elif y&gt;x: print("too high!") elif y==x: print("right!") elif y==z: print("thank you for playing!") sys.exit(0) elif z==str: if y=="exit": print("thank you for playing!") sys.exit(0) elif y !="exit": print("Please write only numbers from 1 to 10 or 'exit'. Thank you.") else: print("Please write only numbers from 1 to 10 or 'exit'. Thank you.") I created the "z" variable to store information about the input type, so as to have do it different things if it's an integer or a string. I felt that is was necessary because I was having a lot of error messages regarding mixing str to ints. I was expecting the program to identify if the user wrote a string, which would trigger the following code: elif z==str: if y=="exit": print("thank you for playing!") sys.exit(0) elif y !="exit": print("Please write only numbers from 1 to 10 or 'exit'. Thank you.") or a integer, where it would do this: if z==int: if y&lt;x: print("too low!") elif y&gt;x: print("too high!") elif y==x: print("right!") elif y==z: print("thank you for playing!") sys.exit(0) In reality what is happening is, whenever I write an input, be it a number or a word, I only get this message:"Please write only numbers from 1 to 10 or 'exit'. Thank you". I commented out the code regarding strings and still I got …
downvote count: 1
linked to: http://stackoverflow.com/q/5424716
has comment: http://stackoverflow.com/comment/90115383
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90115335

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

pandas
tags question: http://stackoverflow.com/q/51548970
tags question: http://stackoverflow.com/q/51547269
tags question: http://stackoverflow.com/q/51623901
tags question: http://stackoverflow.com/q/51636617
tags question: http://stackoverflow.com/q/51486235
tags question: http://stackoverflow.com/q/51608495
tags question: http://stackoverflow.com/q/51599191
tags question: http://stackoverflow.com/q/51536599
tags question: http://stackoverflow.com/q/51609156
tags question: http://stackoverflow.com/q/51572354
tags question: http://stackoverflow.com/q/51618025
tags question: http://stackoverflow.com/q/51562221
tags question: http://stackoverflow.com/q/51520033
tags question: http://stackoverflow.com/q/51529840
tags question: http://stackoverflow.com/q/51596793
tags question: http://stackoverflow.com/q/51553634
tags question: http://stackoverflow.com/q/51577884
tags question: http://stackoverflow.com/q/51597773
tags question: http://stackoverflow.com/q/51532581
tags question: http://stackoverflow.com/q/51573525
tags question: http://stackoverflow.com/q/51554148
tags question: http://stackoverflow.com/q/51582786
tags question: http://stackoverflow.com/q/51569043
tags question: http://stackoverflow.com/q/51619160
tags question: http://stackoverflow.com/q/51620014
tags question: http://stackoverflow.com/q/51594501
tags question: http://stackoverflow.com/q/51571507
tags question: http://stackoverflow.com/q/51586350
tags question: http://stackoverflow.com/q/51631063
tags question: http://stackoverflow.com/q/51509939
tags question: http://stackoverflow.com/q/51601932
tags question: http://stackoverflow.com/q/51586751
tags question: http://stackoverflow.com/q/51624320
tags question: http://stackoverflow.com/q/51584049
tags question: http://stackoverflow.com/q/51600164
tags question: http://stackoverflow.com/q/51558647
tags question: http://stackoverflow.com/q/51551031
tags question: http://stackoverflow.com/q/51522291
tags question: http://stackoverflow.com/q/51530311
tags question: http://stackoverflow.com/q/51630870
tags question: http://stackoverflow.com/q/51542222
tags question: http://stackoverflow.com/q/51537834
tags question: http://stackoverflow.com/q/51514212
tags question: http://stackoverflow.com/q/51630874
tags question: http://stackoverflow.com/q/51484371
tags question: http://stackoverflow.com/q/51602670
tags question: http://stackoverflow.com/q/51604819
tags question: http://stackoverflow.com/q/51617578
tags question: http://stackoverflow.com/q/51632860
tags question: http://stackoverflow.com/q/51567859
tags question: http://stackoverflow.com/q/51572131
tags question: http://stackoverflow.com/q/51513259
tags question: http://stackoverflow.com/q/51504535
tags question: http://stackoverflow.com/q/51621082
tags question: http://stackoverflow.com/q/51630106
tags question: http://stackoverflow.com/q/51551267
tags question: http://stackoverflow.com/q/51488708
tags question: http://stackoverflow.com/q/51624870
tags question: http://stackoverflow.com/q/51541377
tags question: http://stackoverflow.com/q/51608387
tags question: http://stackoverflow.com/q/51618724
tags question: http://stackoverflow.com/q/51509259
tags question: http://stackoverflow.com/q/51581888
tags question: http://stackoverflow.com/q/51524421
tags question: http://stackoverflow.com/q/51515677
tags question: http://stackoverflow.com/q/51516709
tags question: http://stackoverflow.com/q/51617098
tags question: http://stackoverflow.com/q/51637028
tags question: http://stackoverflow.com/q/51505187
tags question: http://stackoverflow.com/q/51558911
tags question: http://stackoverflow.com/q/51618509
tags question: http://stackoverflow.com/q/51637757
tags question: http://stackoverflow.com/q/51559201
tags question: http://stackoverflow.com/q/51558378
tags question: http://stackoverflow.com/q/51627716
tags question: http://stackoverflow.com/q/51500621
tags question: http://stackoverflow.com/q/51617367
tags question: http://stackoverflow.com/q/51600414
tags question: http://stackoverflow.com/q/51502602
tags question: http://stackoverflow.com/q/51485721

matplotlib
tags question: http://stackoverflow.com/q/51540384
tags question: http://stackoverflow.com/q/51527331
tags question: http://stackoverflow.com/q/51494124
tags question: http://stackoverflow.com/q/51546356
tags question: http://stackoverflow.com/q/51502927
tags question: http://stackoverflow.com/q/51506354
tags question: http://stackoverflow.com/q/51602052
tags question: http://stackoverflow.com/q/51571540
tags question: http://stackoverflow.com/q/51495982
tags question: http://stackoverflow.com/q/51545523
tags question: http://stackoverflow.com/q/51508506
tags question: http://stackoverflow.com/q/51621365
tags question: http://stackoverflow.com/q/51535425
tags question: http://stackoverflow.com/q/51549534
tags question: http://stackoverflow.com/q/51548794
tags question: http://stackoverflow.com/q/51603959
tags question: http://stackoverflow.com/q/51527766
tags question: http://stackoverflow.com/q/51487391
tags question: http://stackoverflow.com/q/51504082
tags question: http://stackoverflow.com/q/51571507
tags question: http://stackoverflow.com/q/51580820
tags question: http://stackoverflow.com/q/51559482
tags question: http://stackoverflow.com/q/51611163
tags question: http://stackoverflow.com/q/51598004
tags question: http://stackoverflow.com/q/51620286
tags question: http://stackoverflow.com/q/51632072
tags question: http://stackoverflow.com/q/51611051
tags question: http://stackoverflow.com/q/51544141
tags question: http://stackoverflow.com/q/51526677
tags question: http://stackoverflow.com/q/51544930
tags question: http://stackoverflow.com/q/51637028
tags question: http://stackoverflow.com/q/51502360
tags question: http://stackoverflow.com/q/51584866
tags question: http://stackoverflow.com/q/51553465
tags question: http://stackoverflow.com/q/51576635
tag name: matplotlib
tags question: http://stackoverflow.com/q/51503539
tags question: http://stackoverflow.com/q/51574035
tags question: http://stackoverflow.com/q/51602012
tags question: http://stackoverflow.com/q/51508811
tags question: http://stackoverflow.com/q/51575927
tags question: http://stackoverflow.com/q/51628902
tags question: http://stackoverflow.com/q/51491248
tags question: http://stackoverflow.com/q/51589678
tags question: http://stackoverflow.com/q/51617781
tags question: http://stackoverflow.com/q/51599282
tags question: http://stackoverflow.com/q/51509999
tags question: http://stackoverflow.com/q/51627885
tags question: http://stackoverflow.com/q/51590602
tags question: http://stackoverflow.com/q/51576450
tags question: http://stackoverflow.com/q/51587923
tags question: http://stackoverflow.com/q/51623135
tags question: http://stackoverflow.com/q/51568030
tags question: http://stackoverflow.com/q/51534220
tags question: http://stackoverflow.com/q/51637621
tags question: http://stackoverflow.com/q/51627233
tags question: http://stackoverflow.com/q/51587656
tags question: http://stackoverflow.com/q/51571047
tags question: http://stackoverflow.com/q/51570291
tags question: http://stackoverflow.com/q/51494218
tags question: http://stackoverflow.com/q/51527495
tags question: http://stackoverflow.com/q/51487259
tags question: http://stackoverflow.com/q/51573606
tags question: http://stackoverflow.com/q/51609513
tags question: http://stackoverflow.com/q/51635689
tags question: http://stackoverflow.com/q/51543507
tags question: http://stackoverflow.com/q/51519178
tags question: http://stackoverflow.com/q/51516790
tags question: http://stackoverflow.com/q/51509259
tags question: http://stackoverflow.com/q/51588514
tags question: http://stackoverflow.com/q/51559830
tags question: http://stackoverflow.com/q/51486099
tags question: http://stackoverflow.com/q/51521733
tags question: http://stackoverflow.com/q/51554995
tags question: http://stackoverflow.com/q/51612755
tags question: http://stackoverflow.com/q/51504323
tags question: http://stackoverflow.com/q/51490358
tags question: http://stackoverflow.com/q/51595337
tags question: http://stackoverflow.com/q/51626527
tags question: http://stackoverflow.com/q/51571196

http://stackoverflow.com/q/51631694
tagged with: dask-distributed
tagged with: dask-kubernetes
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51633456
favorite count: 0
accepted answer: http://stackoverflow.com/a/51633456
tagged with: dask
tagged with: python
has title: How do I get adaptive dask workers to run some code on startup?
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
has body: I'm creating a dask scheduler using dask-kubernetes and putting it into adaptive mode. from dask-kubernetes import KubeCluster cluster = KubeCluster() cluster.adapt(minimum=0, maximum=40) I need each worker to run some setup code when they are created (setting some environment variables with os.environ) in order for the tasks to execute correctly. I see in the docs there is a --preload flag for workers that you start from the command line. I'm guessing I need to set that directly into the adaptive scheduler somewhere. How to I pass code to my workers to be executed when they start?

http://stackoverflow.com/comment/90239135
type: QuestionComment
has text: What data structure is `ccxt`?
comment on: http://stackoverflow.com/q/51637374
score: 0
type: Comment

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

http://stackoverflow.com/q/51488111
has comment: http://stackoverflow.com/comment/89945251
has comment: http://stackoverflow.com/comment/89945504
downvote count: 0
has comment: http://stackoverflow.com/comment/89945235
possible better answer: http://stackoverflow.com/a/51488182
favorite count: 0
has comment: http://stackoverflow.com/comment/89945317
has answer: http://stackoverflow.com/a/51488182
has title: Plotting scale for area chart when all values are positive
tagged with: python
has comment: http://stackoverflow.com/comment/89945463
accepted answer: http://stackoverflow.com/a/51488358
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89945592
score: 1
tagged with: matplotlib
upvote count: 1
has comment: http://stackoverflow.com/comment/89945686
type: Question
has comment: http://stackoverflow.com/comment/89945664
has body: I'm trying to produce a chart that is mixed area and line chart. Consider my dataframe df df = pd.DataFrame([range(1, 4)] * 5, columns=list('ABC')).assign(B=lambda d: -d.B).cumsum() And my chart df.C.plot.area(stacked=False) df.A.plot() df.B.plot() Notice that the negative series does not show up. Now suppose I make one entry of series C a negative value df.loc[3, 'C'] = -1 And plot again df.C.plot.area(stacked=False) df.A.plot() df.B.plot() This is what I expected. However, I do have data for series C that is all one sign. How do I plot it such that the scale isn't ruined for my other series? MCVE # messed up import pandas as pd df = pd.DataFrame([range(1, 4)] * 5, columns=list('ABC')).assign(B=lambda d: -d.B).cumsum() df.C.plot.area(stacked=False) df.A.plot() df.B.plot() # correct but I have to put false data import pandas as pd df = pd.DataFrame([range(1, 4)] * 5, columns=list('ABC')).assign(B=lambda d: -d.B).cumsum() df.loc[3, 'C'] = -1 df.C.plot.area(stacked=False) df.A.plot() df.B.plot()
has comment: http://stackoverflow.com/comment/89945632
has comment: http://stackoverflow.com/comment/89945607
has answer: http://stackoverflow.com/a/51488358
answer count: 2
tagged with: pandas

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/51580691
tags question: http://stackoverflow.com/q/51504634
tags question: http://stackoverflow.com/q/51594414
tags question: http://stackoverflow.com/q/51630858
tags question: http://stackoverflow.com/q/51558719
tags question: http://stackoverflow.com/q/51519138
tags question: http://stackoverflow.com/q/51608623
tags question: http://stackoverflow.com/q/51514556
tags question: http://stackoverflow.com/q/51511467
tags question: http://stackoverflow.com/q/51509710
tags question: http://stackoverflow.com/q/51540598
tags question: http://stackoverflow.com/q/51516510
tags question: http://stackoverflow.com/q/51535997
tags question: http://stackoverflow.com/q/51534109
tags question: http://stackoverflow.com/q/51489990
tags question: http://stackoverflow.com/q/51586393
tags question: http://stackoverflow.com/q/51522826
tags question: http://stackoverflow.com/q/51531399
tags question: http://stackoverflow.com/q/51492206
tags question: http://stackoverflow.com/q/51488313
type: Tag
tags question: http://stackoverflow.com/q/51510617
tags question: http://stackoverflow.com/q/51522702
tags question: http://stackoverflow.com/q/51509141
tags question: http://stackoverflow.com/q/51615227
tags question: http://stackoverflow.com/q/51563999
tags question: http://stackoverflow.com/q/51549124
tags question: http://stackoverflow.com/q/51570254
tags question: http://stackoverflow.com/q/51524441
tags question: http://stackoverflow.com/q/51582620
tags question: http://stackoverflow.com/q/51598599
tags question: http://stackoverflow.com/q/51584401
tags question: http://stackoverflow.com/q/51514315
tags question: http://stackoverflow.com/q/51548069
tags question: http://stackoverflow.com/q/51610002
tags question: http://stackoverflow.com/q/51554030
tags question: http://stackoverflow.com/q/51551570
tags question: http://stackoverflow.com/q/51562284
tags question: http://stackoverflow.com/q/51581516

http://stackoverflow.com/a/51528116
answers question: http://stackoverflow.com/q/51527841
type: Answer
downvote count: 0
score: 1
has body: You can find the indices of all duplicates in an array in O(n) time and O(1) extra space with something like the following: def get_duplicate_indices(arr): inds = [] for i, val in enumerate(arr): val = abs(val) if arr[val] &gt;= 0: arr[val] = -arr[val] else: inds.append(i) return inds get_duplicate_indices(a) [4, 5] Note that this will modify the array in place! If you want to keep your input array un-modified, replace the first few lines in the above with: def get_duplicate_indices(a): arr = a.copy() # so we don't modify in place. Drawback is it's not O(n) extra space inds = [] for i, val in enumerate(a): # ... Essentially this uses the sign of each element in the array as an indicator of whether a number has been seen before. If we come across a negative value, it means the number we reached has been seen before, so we append the number's index to our list of already-seen indices. Note that this can run into trouble if the values in the array are larger than the length of the array, but in this case we just extend the working array to be the same length as whatever the maximum value is in the input. Easy peasy.
has comment: http://stackoverflow.com/comment/90025303
has comment: http://stackoverflow.com/comment/90025240
upvote count: 1
has comment: http://stackoverflow.com/comment/90024975
has comment: http://stackoverflow.com/comment/90025069

http://stackoverflow.com/comment/90072991
comment on: http://stackoverflow.com/a/51552345
type: AnswerComment
type: Comment
score: 1
has text: Thanks a ton. Exactly what I wanted.

http://stackoverflow.com/a/56475956
has body: That is a limitation of JVM, you can use only once start_vm(). See this link for more information https://github.com/LeeKamentsky/python-javabridge/issues/88
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51554355
downvote count: 0

http://stackoverflow.com/q/51579117
has body: I am trying to implement the Luhn's algorithm to check for credit card number validity. To do this every second digit needs to be multiplied by 2 and if the result is >9 it then is replaced by the sum of the digits. def luhn_check(creditcardnr): """ check if credit card number is valid using the Luhn's algorithm """ som = 0 for i, digit in enumerate([int(x) for x in str(creditcardnr)]): if i in range(1, len(str(creditcardnr))-1,2): digit *= 2 if digit &gt; 9: digit -= digitsum(digit) som += digit print('digit :',digit,' sum :',som) return som % 10 == 0 When I run this code I get as result digit : 5 sum : 5 digit : 2 sum : 7 digit : 2 sum : 9 digit : 9 sum : 18 digit : 7 sum : 25 digit : 2 sum : 27 digit : 0 sum : 27 digit : 9 sum : 36 digit : 3 sum : 39 digit : 9 sum : 48 digit : 6 sum : 54 False the second sum should be 9 not 7 digitsum() is a function that replaces an integer by the sum of it's digits
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/51753772
has comment: http://stackoverflow.com/comment/90123633
tagged with: algorithm
tagged with: if-statement
has comment: http://stackoverflow.com/comment/90123594
tagged with: luhn
has title: Python: Luhn's algorithm / if statement never executes
score: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/90092996
score: 0
type: Comment
type: QuestionComment
has text: Are those long-running `ExtractComments` and `ExtractKeywords` tasks CPU-bound (and Python code, as opposed to GIL-releasing C extension code)? If so, doing them as coroutines will block your whole pipeline; doing them as threads will not, but it will still mean they can't run in parallel; doing them as child processes may be a better solution. However, you can still integrate them pretty easily with either asyncio or threads (e.g., via run_on_executor type methods).
comment on: http://stackoverflow.com/q/51563040

http://stackoverflow.com/a/51594341
type: Answer
accepted answer of: http://stackoverflow.com/q/51594270
has body: You need create helper column from DatetimeIndex with same missing values like price columns and then aggregate both columns: df['idx'] = df.index.where(df['price'].notnull(), np.nan) first_last = df.groupby(['stock', pd.Grouper(freq='D')])['price', 'idx'].agg(['first','last']) first_last.columns = first_last.columns.map('_'.join) print (first_last) price_first price_last idx_first \ stock Index 85 2016-10-21 150 100 2016-10-21 17:00:00 88 2016-10-21 50 50 2016-10-21 17:00:00 idx_last stock Index 85 2016-10-21 2016-10-21 17:30:00 88 2016-10-21 2016-10-21 17:00:00
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/51594270

http://stackoverflow.com/q/51491372
has answer: http://stackoverflow.com/a/51492085
answer count: 1
tagged with: python
tagged with: qt-signals
upvote count: 1
has body: I was trying to analyse the sample code cited here: PyQt - QMessageBox Here's the snippet: from PyQt4.QtGui import * from PyQt4.QtCore import * class Window(QMainWindow): def __init__(self): super().__init__() w = QWidget() b = QPushButton(self) b.setText("Show message!") b.clicked.connect(self.showdialog) w.setWindowTitle("PyQt Dialog demo") def showdialog(self): msg = QMessageBox() msg.setIcon(QMessageBox.Question) # self.connect(msg, SIGNAL('clicked()'), self.msgbtn) msg.buttonClicked.connect(self.msgbtn) msg.exec_() def msgbtn(self, i): print("Button pressed is:", i.text()) if __name__ == '__main__': app = QApplication([]) w = Window() w.show() app.exec_() There are two ways of connecting signals to slots in PyQt. For buttons, it's: QtCore.QObject.connect(button, QtCore.SIGNAL(“clicked()”), slot_function) or widget.clicked.connect(slot_function) Using it the second way works fine: the msgbtn slot method is called as intended. However, if I try to change it to the more usual, 'PyQt-onic' way of connecting (i.e. the first one - I commented it out in the snippet), the slot method is never called. Could anyone please help me out with this?
type: AnsweredQuestion
score: 1
tagged with: qmessagebox
type: Question
accepted answer: http://stackoverflow.com/a/51492085
tagged with: pyqt
tagged with: pyqt4
downvote count: 0
has title: Connecting in PyQt4 QMessageBox fails to call the slot method
favorite count: 0

http://stackoverflow.com/q/51506676
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51506714
upvote count: 2
has comment: http://stackoverflow.com/comment/89982553
has body: How can I convert each element at index 1 in the inner list to upper() using only list comprehension. ed_sheeran = [ [j.upper() for j[1] in i ] for i in ed_sheeran ] # My code but not working. ed_sheeran = [[' ', 'w', 'h', 'i', 't', 'e', ' ', 'l', 'i', 'p', 's', ',', ' ', 'p', 'a', 'l', 'e', ' ', 'f', 'a', 'c', 'e', ' '], [' ', 'b', 'r', 'e', 'a', 't', 'h', 'i', 'n', 'g', ' ', 'i', 'n', ' ', 's', 'n', 'o', 'w', 'f', 'l', 'a', 'k', 'e', 's', ' '], [' ', 'b', 'u', 'r', 'n', 't', ' ', 'l', 'u', 'n', 'g', 's', ' ', 's', 'o', 'u', 'r', ' ', 't', 'a', 's', 't', 'e', ' ']] for i in ed_sheeran: i[1] = i[1].upper() print(ed_sheeran) Output: [[' ', 'W', 'h', 'i', 't', 'e', ' ', 'l', 'i', 'p', 's', ',', ' ', 'p', 'a', 'l', 'e', ' ', 'f', 'a', 'c', 'e', ' '], [' ', 'B', 'r', 'e', 'a', 't', 'h', 'i', 'n', 'g', ' ', 'i', 'n', ' ', 's', 'n', 'o', 'w', 'f', 'l', 'a', 'k', 'e', 's', ' '], [' ', 'B', 'u', 'r', 'n', 't', ' ', 'l', 'u', 'n', 'g', 's', ' ', 's', 'o', 'u', 'r', ' ', 't', 'a', 's', 't', 'e', ' ']]
tagged with: python
has answer: http://stackoverflow.com/a/51506793
has answer: http://stackoverflow.com/a/51506900
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89982686
score: 1
possible better answer: http://stackoverflow.com/a/51506793
downvote count: 1
has comment: http://stackoverflow.com/comment/89982509
type: Question
has answer: http://stackoverflow.com/a/51506714
has comment: http://stackoverflow.com/comment/89982511
has title: how to convert element at index 1 to upper() in a nested list?
answer count: 3

http://stackoverflow.com/comment/90023665
type: Comment
comment on: http://stackoverflow.com/q/51527379
score: 0
type: QuestionComment
has text: Just providing you a solution that will work outside of your extremely specific example.

http://stackoverflow.com/comment/90110151
type: Comment
score: 2
has text: You wrote an `f` as prefix, so Python aims to find a variable named `0`. What are you trying to do here (probably `settings.py` file)?
comment on: http://stackoverflow.com/q/51572088
type: QuestionComment

http://stackoverflow.com/comment/90165708
type: QuestionComment
has text: @timgeb mylist contains arrays of different sizes, exactly as PM2Ring says. You can add anything in it.
score: 0
comment on: http://stackoverflow.com/q/51599428
type: Comment

http://stackoverflow.com/a/51499890
accepted answer of: http://stackoverflow.com/q/51499605
answers question: http://stackoverflow.com/q/51499605
downvote count: 1
upvote count: 4
has body: The plot function returns a list of Line2D objects which represent the plotted data. These objects have a remove method which will remove them from the figure they've been plotted on (note that Line2D inherits from Artist which you can check via Line2D.__mro__): remove() method of matplotlib.lines.Line2D instance Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with :meth:`matplotlib.axes.Axes.draw_idle`. Call :meth:`matplotlib.axes.Axes.relim` to update the axes limits if desired. [...] So you can do the following (I combined plotting the single points in one go): points = plt.plot(*zip(*points_list), 'o', color='k')[0] # Remove the points (requires redrawing). points.remove() Keeping your for loop this would be: points = [] for point in points_list: points.extend( plt.plot(point[0], point[1], marker='o', color='k') ) for p in points: p.remove() Or more concise using a list comprehension: points = [plt.plot(*p, marker='o', color='k')[0] for p in points_list]
score: 3
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/51546603
has comment: http://stackoverflow.com/comment/90061380
downvote count: 0
type: AcceptedAnswer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51546543
type: Answer
answers question: http://stackoverflow.com/q/51546543
has body: Generate two tuples and compare them: def __eq__(self, building2): return (self._item1, self._item2, self._item3, self._item4) == ( building2._item1, building2._item2, building3._item1, building4._item1)
score: 2

http://stackoverflow.com/comment/90208679
has text: @runaway57 Nice. Would you select this as an answer?
comment on: http://stackoverflow.com/a/51621363
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89983743
type: Comment
has text: Hello, I understand this is your first question on Stackoverflow so please first https://stackoverflow.com/help/how-to-ask then edit the above question and provide more context and the concrete technical issue you're running into. Thanks
comment on: http://stackoverflow.com/q/51507122
score: 0
type: QuestionComment

http://stackoverflow.com/a/51522538
answers question: http://stackoverflow.com/q/51522457
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90015119
upvote count: 1
has body: Including -qq in the tox command should reduce the output to just 0.2.0.
downvote count: 1

http://stackoverflow.com/comment/90243903
comment on: http://stackoverflow.com/a/51639653
has text: I did see your edit and I still think you do not need the `update()` loop. It will be handled with the `mainloop()` if you are having issues with it not updating with the main loop then there might be some other cause as it should work fine.
type: Comment
score: 0
type: AnswerComment

pyqt
type: Tag
tags question: http://stackoverflow.com/q/51487893
tags question: http://stackoverflow.com/q/51490917
tags question: http://stackoverflow.com/q/51495091
tags question: http://stackoverflow.com/q/51526677
tags question: http://stackoverflow.com/q/51598792
tags question: http://stackoverflow.com/q/51510968
tags question: http://stackoverflow.com/q/51505464
tags question: http://stackoverflow.com/q/51553836
tags question: http://stackoverflow.com/q/51603424
tags question: http://stackoverflow.com/q/51559628
tags question: http://stackoverflow.com/q/51509798
tags question: http://stackoverflow.com/q/51576848
tags question: http://stackoverflow.com/q/51554290
tags question: http://stackoverflow.com/q/51534731
tags question: http://stackoverflow.com/q/51626161
tags question: http://stackoverflow.com/q/51489933
tags question: http://stackoverflow.com/q/51557663
tags question: http://stackoverflow.com/q/51620130
tags question: http://stackoverflow.com/q/51549271
tags question: http://stackoverflow.com/q/51635438
tags question: http://stackoverflow.com/q/51529556
tags question: http://stackoverflow.com/q/51542722
tags question: http://stackoverflow.com/q/51530112
tags question: http://stackoverflow.com/q/51491372
tags question: http://stackoverflow.com/q/51607038
tags question: http://stackoverflow.com/q/51613638
tags question: http://stackoverflow.com/q/51527635
tags question: http://stackoverflow.com/q/51507237
tags question: http://stackoverflow.com/q/51487226
tag name: pyqt
tags question: http://stackoverflow.com/q/51545428
tags question: http://stackoverflow.com/q/51560196
tags question: http://stackoverflow.com/q/51487971
tags question: http://stackoverflow.com/q/51586200

http://stackoverflow.com/a/51493936
accepted answer of: http://stackoverflow.com/q/51490635
has body: An outgoing request, even if is from one project you own to another, is an outgoing request, so yes, it would count towards your quota. If possible, as a piece of advice, try to convert what you have in those projects into services of only one project.
has comment: http://stackoverflow.com/comment/90009296
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51490635
score: 0
type: Answer

http://stackoverflow.com/q/51597893
has answer: http://stackoverflow.com/a/51597986
accepted answer: http://stackoverflow.com/a/51597986
has answer: http://stackoverflow.com/a/51598228
has title: how to slice between two elements in a pandas series
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51598064
type: Question
has body: I have a Series containing a column with names and their nationalities in parenthesis. I want this column to contain just the individuals nationality and without parenthesis, with the same index. 0 LOMBARDI Domingo (URU) 1 MACIAS Jose (ARG) 2 TEJADA Anibal (URU) 3 WARNKEN Alberto (CHI) 4 REGO Gilberto (BRA) 5 CRISTOPHE Henry (BEL) 6 MATEUCCI Francisco (URU) 7 MACIAS Jose (ARG) 8 LANGENUS Jean (BEL) 9 TEJADA Anibal (URU) 10 SAUCEDO Ulises (BOL) I have tried using .split(' ')[2] to the series. But found out "'Series' object has no attribute 'split'."
score: 0
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51598064

http://stackoverflow.com/q/51614117
has answer: http://stackoverflow.com/a/51614399
downvote count: 0
tagged with: raise
favorite count: 0
possible better answer: http://stackoverflow.com/a/51614399
tagged with: exception
has body: I have a python file in which i have two functions that each of them raise an exception. def f(): raise e1 def g(): raise e2 My question, is it possible to store these exceptions in a variable, like list for example--[e1, e2]--, in order to control the order of exceptions execution in another function, say h ?
tagged with: python
has answer: http://stackoverflow.com/a/51614174
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90209509
has title: How to report an exception for later
type: Question
has comment: http://stackoverflow.com/comment/90193621
score: 5
upvote count: 5
accepted answer: http://stackoverflow.com/a/51614174
answer count: 2

http://stackoverflow.com/comment/89948157
comment on: http://stackoverflow.com/q/51489746
type: Comment
type: QuestionComment
score: 7
has text: `from selenium.webdriver.remote.webelement import WebElement` ?

http://stackoverflow.com/comment/90293816
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51660174
has text: My mistake, make it serializeddata.data and let me know the result!
score: 0

http://stackoverflow.com/q/51490166
tagged with: pytest
has body: How can I display the amount of time taken for each test executed by pytest? I've investigated pytest-timeout, pytest-timeit, and pytest-benchmark. pytest-benchmark is closest, but requires wrapping every test manually. The most pressing need is to figure out why testing under Py 3.x takes almost twice as long as Py 2.7. There are 231 top-level tests in the package I want to test (as identified by pytest), so wrapping all of these is not trivial.
upvote count: 1
downvote count: 1
type: Question
tagged with: testing
tagged with: automated-tests
has comment: http://stackoverflow.com/comment/90049247
score: 0
linked to: http://stackoverflow.com/q/27884404
answer count: 1
has comment: http://stackoverflow.com/comment/89948798
favorite count: 0
duplicate of: http://stackoverflow.com/q/27884404
type: UnansweredQuestion
tagged with: python
has title: How to time tests with pytest?
has answer: http://stackoverflow.com/a/51495108

http://stackoverflow.com/q/51578389
linked to: http://stackoverflow.com/q/2347265
has title: Concatenation of a string to a list
has body: I ran the following code in Jupyter Notebook: list_1 = [] list_1 += "cat" print(list_1) and got the following output: ['c', 'a', 't'] but when i ran this: list_1 = [] list_1 = list_1 + "cat" print(list_1) it gave the following error: TypeError: can only concatenate list (not "str") to list I failed to understand this as in both the methods, a string is being added to a list. Is it something about the '+=' notation or something related to the concatenation of lists and strings that's causing the bug?
type: Question
duplicate of: http://stackoverflow.com/q/2347265
has answer: http://stackoverflow.com/a/51578422
tagged with: concatenation
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90135181
has comment: http://stackoverflow.com/comment/90122125
tagged with: python
favorite count: 0
score: 2
tagged with: python-3.x
tagged with: list
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/a/51559905
has comment: http://stackoverflow.com/comment/90093206
type: AcceptedAnswer
has body: use numpy's nan_to_num() to replace NaN by zeroes in your bottom= argument: menMeans = (np.nan, 35, 30, 35, 27) # NAN VALUE WAS ADDED womenMeans = (20, 32, 34, 20, 25) ind = np.arange(5) width = 0.35 p1 = plt.bar(ind, menMeans, width) p2 = plt.bar(ind, womenMeans, width, bottom=np.nan_to_num(menMeans)) # no more NaNs in bottom= plt.ylabel('Scores') plt.title('Scores by group and gender') plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5')) plt.yticks(np.arange(0, 81, 10)) plt.legend((p1[0], p2[0]), ('Men', 'Women')) plt.ylim((0,80)) plt.show() PS: if you're using the pyplot approach (see difference between pyplot and object-oriented APIs), you should be calling plt.ylim(), instead of what you were doing
upvote count: 1
has comment: http://stackoverflow.com/comment/90087092
accepted answer of: http://stackoverflow.com/q/51559830
answers question: http://stackoverflow.com/q/51559830
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/89975981
type: Comment
has text: As of right now my table is only 3 rows and about 12 columns. Once I can get through these errors and import more data, it will become a much larger table.
comment on: http://stackoverflow.com/a/51503419
score: 0
type: AnswerComment

http://stackoverflow.com/q/51508937
tagged with: smtp
has comment: http://stackoverflow.com/comment/90023980
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90023520
tagged with: python
has comment: http://stackoverflow.com/comment/90023561
linked to: http://stackoverflow.com/q/50301172
has body: I tried the solution for the post here, but it didn't help. Part of my python script sends out email to recipients. When I run the code in my Pycharm it sends out exactly 3 emails which is the number of email addresses for my test case and the number which it suppose to send out. However, when I try to run it on my raspberry pi it randomly sends out the emails and I cannot find a pattern of the difference number of emails that it sends out. So, there is a list called 'toAddrs' which saves the email address of recipients. I tried the following two ways once using a for loop and once without a for loop. But both of these send an arbitrary number of emails. #subject, fromAddr, mainbody and password are already defined msg = MIMEMultipart('') msg.attach(MIMEText(mainbody, 'plain')) msg['Subject'] = subject msg['From'] = fromAddr msg['To'] = toAddrs server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromAddr, password) for i in range(len(toAddrs)): server.sendmail(fromAddr, toAddrs[i], msg.as_string()) server.quit() and another one is: #subject, fromAddr, mainbody and password are already defined msg = MIMEMultipart('') msg.attach(MIMEText(mainbody, 'plain')) msg['Subject'] = subject msg['From'] = fromAddr msg['To'] = ' ,'.join(toAddrs) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromAddr, password) server.sendmail(fromAddr, toAddrs, msg.as_string()) server.quit() I cannot find what might be wrong. I will appreciate any help.
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/90024130
type: Question
has comment: http://stackoverflow.com/comment/90023872
has comment: http://stackoverflow.com/comment/89990169
has comment: http://stackoverflow.com/comment/90023232
has comment: http://stackoverflow.com/comment/90024774
tagged with: raspberry-pi
has title: Python script send out more emails that it supposed to send
has comment: http://stackoverflow.com/comment/89988072
has comment: http://stackoverflow.com/comment/90023593
upvote count: 1
tagged with: email
downvote count: 0
has comment: http://stackoverflow.com/comment/89988050

http://stackoverflow.com/q/51546975
tagged with: post
has comment: http://stackoverflow.com/comment/90062712
score: 0
accepted answer: http://stackoverflow.com/a/51548263
answer count: 1
tagged with: asp.net
has comment: http://stackoverflow.com/comment/90070449
has title: Building data for POST method on .aspx website in Python
has body: I'm new to .NET and Python, but I would like to make a program to scrape .aspx site and work with content there (HTML code is enough). I tried some libraries in Python, but all I got is the first page of that site. Seems like I am building wrong POST data, I don't know the right form of the data, what should be included and what not. http://nastenka.lesy.sk/EZOZV/Publish/ObjednavkyZverejnenie.aspx?YR=2018 import requests, urllib, urllib2 r = requests.get("http://nastenka.lesy.sk/EZOZV/Publish/ObjednavkyZverejnenie.aspx?YR=2018") content = r.text print content start_index = content.find('id="__VIEWSTATE"') + 24 sliced_vs = content[start_index:content.find('"',start_index)] start_index = content.find('id="__VIEWSTATEGENERATOR"') + 33 sliced_vsg = content[start_index:content.find('"',start_index)] start_index = content.find('id="__VIEWSTATEENCRYPTED"') + 33 sliced_vse = content[start_index:content.find('"',start_index)] start_index = content.find('id="__EVENTVALIDATION"') + 30 sliced_EV = content[start_index:content.find('"',start_index)] form_data = {'__EVENTTARGET': 'gvZverejnenie', '__EVENTARGUMENT': 'Page$2', '__VIEWSTATE': sliced_vs, '__VIEWSTATEGENERATOR': sliced_vsg, '__VIEWSTATEENCRYPTED': sliced_vse, '__EVENTVALIDATION': sliced_EV} data_encoded = urllib.urlencode(form_data) r = requests.post('http://nastenka.lesy.sk/EZOZV/Publish/ObjednavkyZverejnenie.aspx?YR=2018',data=data_encoded) content = r.text print content For example, in code I want to get the second page ('Page$2'). I get always the same result, but with different values for ViewState and EventValidation. Where could be the problem, please?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90062168
type: Question
has answer: http://stackoverflow.com/a/51548263

http://stackoverflow.com/comment/90206337
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51617228
has text: The code" result["Ratio"] = (1 / result["Server_count"]) * 100 "working properly . but when i try to print it using print(result['ratio']=(1 / result['server_count']) * 100) it shows syntax error "keyword can't be an expression". Also the resulting values should have column name but it doesnt displaying
type: Comment

http://stackoverflow.com/comment/89993782
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51511839
type: Comment
has text: for the "Your web element" i used >>> element=browser.find_element_by_class_name("submit") >>> actions = ActionChains(browser) >>> actions.move_to_element(element).click().perform() Is that correct? This does not work

http://stackoverflow.com/a/51577325
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/97932400
score: 8
has comment: http://stackoverflow.com/comment/92733935
type: Answer
downvote count: 0
upvote count: 8
accepted answer of: http://stackoverflow.com/q/51577258
answers question: http://stackoverflow.com/q/51577258
has body: One option would be to change the write permissions on the directories pip and conda install packages to for the base environments. These locations vary based on your distribution, but you can check by using something like python -c "import setuptools; print(setuptools.__file__)". The parent directory to setuputils will be where the packages get installed by default. Run chmod -w &lt;packages dir&gt; to remove write permissions. You can always add them back with chmod +w &lt;packages dir&gt; later, but while they're disabled this should keep you from installing packages there by accident. Unless you haphazardly install packages with sudo, that is...

flask
tags question: http://stackoverflow.com/q/51591267
tags question: http://stackoverflow.com/q/51517599
tags question: http://stackoverflow.com/q/51575473
tags question: http://stackoverflow.com/q/51619855
tags question: http://stackoverflow.com/q/51612457
tags question: http://stackoverflow.com/q/51567716
tags question: http://stackoverflow.com/q/51610961
tags question: http://stackoverflow.com/q/51575373
tags question: http://stackoverflow.com/q/51503242
tags question: http://stackoverflow.com/q/51636461
tags question: http://stackoverflow.com/q/51599936
tags question: http://stackoverflow.com/q/51559414
tags question: http://stackoverflow.com/q/51508666
tags question: http://stackoverflow.com/q/51498728
tags question: http://stackoverflow.com/q/51506296
tags question: http://stackoverflow.com/q/51635676
tags question: http://stackoverflow.com/q/51484207
tags question: http://stackoverflow.com/q/51514488
tags question: http://stackoverflow.com/q/51492960
tags question: http://stackoverflow.com/q/51546148
tags question: http://stackoverflow.com/q/51501927
tags question: http://stackoverflow.com/q/51600926
tags question: http://stackoverflow.com/q/51578842
tags question: http://stackoverflow.com/q/51489905
tags question: http://stackoverflow.com/q/51638196
tags question: http://stackoverflow.com/q/51573566
tags question: http://stackoverflow.com/q/51564026
tags question: http://stackoverflow.com/q/51635019
tags question: http://stackoverflow.com/q/51552584
tags question: http://stackoverflow.com/q/51581367
tags question: http://stackoverflow.com/q/51487516
tags question: http://stackoverflow.com/q/51613667
tags question: http://stackoverflow.com/q/51505589
tags question: http://stackoverflow.com/q/51639498
tags question: http://stackoverflow.com/q/51620475
tags question: http://stackoverflow.com/q/51639757
tags question: http://stackoverflow.com/q/51581244
tags question: http://stackoverflow.com/q/51485362
tags question: http://stackoverflow.com/q/51540944
tags question: http://stackoverflow.com/q/51600596
tags question: http://stackoverflow.com/q/51546592
tags question: http://stackoverflow.com/q/51541265
tags question: http://stackoverflow.com/q/51639744
tags question: http://stackoverflow.com/q/51544042
tags question: http://stackoverflow.com/q/51563007
tags question: http://stackoverflow.com/q/51615872
tags question: http://stackoverflow.com/q/51561545
tags question: http://stackoverflow.com/q/51552789
tags question: http://stackoverflow.com/q/51614903
tags question: http://stackoverflow.com/q/51509970
tags question: http://stackoverflow.com/q/51521364
tags question: http://stackoverflow.com/q/51576935
type: Tag
tags question: http://stackoverflow.com/q/51490454
tags question: http://stackoverflow.com/q/51509317
tags question: http://stackoverflow.com/q/51604484
tags question: http://stackoverflow.com/q/51525964
tags question: http://stackoverflow.com/q/51576138
tags question: http://stackoverflow.com/q/51543020
tags question: http://stackoverflow.com/q/51507843
tags question: http://stackoverflow.com/q/51591906
tags question: http://stackoverflow.com/q/51507757
tags question: http://stackoverflow.com/q/51601953
tags question: http://stackoverflow.com/q/51488541
tags question: http://stackoverflow.com/q/51637196
tags question: http://stackoverflow.com/q/51504221
tags question: http://stackoverflow.com/q/51577822
tags question: http://stackoverflow.com/q/51577056
tags question: http://stackoverflow.com/q/51597181
tags question: http://stackoverflow.com/q/51616404
tags question: http://stackoverflow.com/q/51570684
tags question: http://stackoverflow.com/q/51619559
tags question: http://stackoverflow.com/q/51607033
tags question: http://stackoverflow.com/q/51591603
tags question: http://stackoverflow.com/q/51560345
tags question: http://stackoverflow.com/q/51621972
tags question: http://stackoverflow.com/q/51618410
tags question: http://stackoverflow.com/q/51517626
tags question: http://stackoverflow.com/q/51511222
tags question: http://stackoverflow.com/q/51632260

http://stackoverflow.com/comment/89964023
type: QuestionComment
type: Comment
has text: sounds like you have a duplicate index on 'a' or 'b', maybe test against that?
comment on: http://stackoverflow.com/q/51496924
score: 0

http://stackoverflow.com/comment/90094720
type: Comment
has text: The `print("Esperado: [%d]" % saidas)` statements will fail, you can't format a list in that way.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51563736

list
tags question: http://stackoverflow.com/q/51494558
tags question: http://stackoverflow.com/q/51624790
tags question: http://stackoverflow.com/q/51510147
tags question: http://stackoverflow.com/q/51546935
tags question: http://stackoverflow.com/q/51553693
type: Tag
tags question: http://stackoverflow.com/q/51514098
tags question: http://stackoverflow.com/q/51582380
tags question: http://stackoverflow.com/q/51552365
tags question: http://stackoverflow.com/q/51631308
tags question: http://stackoverflow.com/q/51501469
tags question: http://stackoverflow.com/q/51625009
tags question: http://stackoverflow.com/q/51638387
tags question: http://stackoverflow.com/q/51483375
tags question: http://stackoverflow.com/q/51522732
tags question: http://stackoverflow.com/q/51548094
tags question: http://stackoverflow.com/q/51528065
tags question: http://stackoverflow.com/q/51583086
tags question: http://stackoverflow.com/q/51569207
tags question: http://stackoverflow.com/q/51531804
tags question: http://stackoverflow.com/q/51486510
tags question: http://stackoverflow.com/q/51516589
tags question: http://stackoverflow.com/q/51529545
tags question: http://stackoverflow.com/q/51553889
tags question: http://stackoverflow.com/q/51485013
tags question: http://stackoverflow.com/q/51489880
tags question: http://stackoverflow.com/q/51548631
tags question: http://stackoverflow.com/q/51544094
tags question: http://stackoverflow.com/q/51625669
tags question: http://stackoverflow.com/q/51599596
tags question: http://stackoverflow.com/q/51490114
tags question: http://stackoverflow.com/q/51601249
tags question: http://stackoverflow.com/q/51575647
tags question: http://stackoverflow.com/q/51597416
tags question: http://stackoverflow.com/q/51527566
tags question: http://stackoverflow.com/q/51564071
tags question: http://stackoverflow.com/q/51497510
tags question: http://stackoverflow.com/q/51623355
tags question: http://stackoverflow.com/q/51521412
tags question: http://stackoverflow.com/q/51584415
tags question: http://stackoverflow.com/q/51506177
tags question: http://stackoverflow.com/q/51553003
tags question: http://stackoverflow.com/q/51596522
tags question: http://stackoverflow.com/q/51625775
tags question: http://stackoverflow.com/q/51558265
tags question: http://stackoverflow.com/q/51581145
tags question: http://stackoverflow.com/q/51629675
tag name: list
tags question: http://stackoverflow.com/q/51578389
tags question: http://stackoverflow.com/q/51612652
tags question: http://stackoverflow.com/q/51612459
tags question: http://stackoverflow.com/q/51515720
tags question: http://stackoverflow.com/q/51502615
tags question: http://stackoverflow.com/q/51590304
tags question: http://stackoverflow.com/q/51614297
tags question: http://stackoverflow.com/q/51552195
tags question: http://stackoverflow.com/q/51636876
tags question: http://stackoverflow.com/q/51581671
tags question: http://stackoverflow.com/q/51529507
tags question: http://stackoverflow.com/q/51586643
tags question: http://stackoverflow.com/q/51623898
tags question: http://stackoverflow.com/q/51616686
tags question: http://stackoverflow.com/q/51568156
tags question: http://stackoverflow.com/q/51592889
tags question: http://stackoverflow.com/q/51493842
tags question: http://stackoverflow.com/q/51526242
tags question: http://stackoverflow.com/q/51536082
tags question: http://stackoverflow.com/q/51625861
tags question: http://stackoverflow.com/q/51590677
tags question: http://stackoverflow.com/q/51549816
tags question: http://stackoverflow.com/q/51566722
tags question: http://stackoverflow.com/q/51549323
tags question: http://stackoverflow.com/q/51634279
tags question: http://stackoverflow.com/q/51567059
tags question: http://stackoverflow.com/q/51579184
tags question: http://stackoverflow.com/q/51591908
tags question: http://stackoverflow.com/q/51547719
tags question: http://stackoverflow.com/q/51565499
tags question: http://stackoverflow.com/q/51484898
tags question: http://stackoverflow.com/q/51621428

http://stackoverflow.com/a/51563303
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51563186
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51563186
has body: The data filter_data[locations][]=1647-India is like any other data you post. You can feed them to requests.post() like this: requests.post(url, data={'filter_data[locations][]' : '1647-India'}) As in comments, there is QuickStart User Guide how to make complex requests.

http://stackoverflow.com/q/51520630
possible better answer: http://stackoverflow.com/a/60216773
has answer: http://stackoverflow.com/a/60216773
tagged with: numpy
answer count: 4
has title: Subclassing Numpy Array - Propagate Attributes
has comment: http://stackoverflow.com/comment/90012237
tagged with: arrays
downvote count: 0
accepted answer: http://stackoverflow.com/a/51695181
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90014508
tagged with: attributes
score: 23
favorite count: 0
tagged with: subclass
has answer: http://stackoverflow.com/a/51697518
has answer: http://stackoverflow.com/a/51681311
tagged with: python
has body: I would like to know how custom attributes of numpy arrays can be propagated, even when the array passes through functions like np.fromfunction. For example, my class ExampleTensor defines an attribute attr that is set to 1 on default. import numpy as np class ExampleTensor(np.ndarray): def __new__(cls, input_array): return np.asarray(input_array).view(cls) def __array_finalize__(self, obj) -&gt; None: if obj is None: return # This attribute should be maintained! self.attr = getattr(obj, 'attr', 1) Slicing and basic operations between ExampleTensor instances will maintain the attributes, but using other numpy functions will not (probably because they create regular numpy arrays instead of ExampleTensors). My question: Is there a solution that persists the custom attributes when a regular numpy array is constructed out of subclassed numpy array instances? Example to reproduce problem: ex1 = ExampleTensor([[3, 4],[5, 6]]) ex1.attr = "some val" print(ex1[0].attr) # correctly outputs "some val" print((ex1+ex1).attr) # correctly outputs "some val" np.sum([ex1, ex1], axis=0).attr # Attribute Error: 'numpy.ndarray' object has no attribute 'attr'
has answer: http://stackoverflow.com/a/51695181
upvote count: 23

http://stackoverflow.com/q/51508905
has comment: http://stackoverflow.com/comment/90013895
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90015391
tagged with: locust
has comment: http://stackoverflow.com/comment/89987085
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47041257
tagged with: gevent
has title: access original version of patched python module
type: Question
has body: I am load testing my system using the Locust framework. My project contains the Locust source files (not listed as dependency) because I had to make some modifications to the source code for some needed functionality. Unfortunately in locust/core the following code is called from gevent import GreenletExit, monkey from six.moves import xrange monkey.patch_all() In a different part of my project (outside of locust - but still dependent upon the locally modified version of locust) I am trying to use the multiprocessing module: from multiprocessing import Pool def dummy_func pool = Pool(4) #gets hung up here -- likly because of patched sockets in os module results = pool.map(irrelevant_func, irrelevant_data) The issue is the monkey.patch_all() patches the multiprocessing modules dependencies (such as os module) making it unusable. I can't remove the monkey.patch_all() call as its essential to Locust, but I need to access the original version of the multiprocessing module (and all its dependencies) so I can retain its functionality. TLDR: Gevent's MonkeyPatching causes Multiprocessing Pool to hang (wont initialize) because it patches the os modules socket -- how do I get a version of Multiprocessing that accesses an unpatched os module along with a version of gevent that accesses a patched os module My Research for similar bug Python unit test best practice to avoid monkey patching bug Gevent monkeypatching breaking multiprocessing https://groups.google.com/forum/#!topic/gevent/Mjk3qc0i13E
tagged with: python-multiprocessing
linked to: http://stackoverflow.com/q/8678307
tagged with: monkeypatching

http://stackoverflow.com/a/51577022
has comment: http://stackoverflow.com/comment/90137557
has comment: http://stackoverflow.com/comment/90167875
has comment: http://stackoverflow.com/comment/90137047
score: 7
answers question: http://stackoverflow.com/q/51541610
has comment: http://stackoverflow.com/comment/108301555
has body: First: You are recreating the dataset unnecessarily. data_set = tf.data.Dataset.from_tensor_slices((training_inputs, training_labels)) Create the dataset prior to the loop and change the regress_with_tfData input signature to use dataset instead of training_inputs and training_labels. Second: The problem here is that minibatches of size 50 or even 500 are too small to compensate the cost of td.data building latency. You should increase the minibatch size. Interestingly you did so with a minibatch of size 100000, but then maybe it is too big ( I am not certain of this, I think it would need more tests). There are a couple of things you could try: 1) Increase the minibatch size to something like 10000 and see if you get an improvement 2) Change your pipeline to use an iterator, example: data_set = tf.data.Dataset.from_tensor_slices((training_inputs, training_labels)) data_set = data_set.repeat(n_epochs) data_set = data_set.batch(batch_size) iterator = data_set.make_one_shot_iterator() .... next_element = iterator.get_next()
upvote count: 7
type: Answer
has comment: http://stackoverflow.com/comment/90165671
downvote count: 0

http://stackoverflow.com/a/51545623
has comment: http://stackoverflow.com/comment/90059027
has comment: http://stackoverflow.com/comment/90060352
score: 0
answers question: http://stackoverflow.com/q/51545523
has body: First of all, my answers are only guesses. I have no experience with that package. To remove the white space at the left most of the plot set the plt.xlim to something bigger than 700. Try with your lowest value in that axis. I bet that the unit in the color bar is related to your data. Which is the unit of your data? And what your data mean?
type: Answer

http://stackoverflow.com/a/51547687
answers question: http://stackoverflow.com/q/51547637
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 6
has body: Both languages have produced the same sequence of bytes; the only difference is in the way they display those bytes to you. Ruby has an \e string escape sequence for the 1b byte (ASCII ESC, escape), while Python displays that byte as \x1b.
accepted answer of: http://stackoverflow.com/q/51547637
upvote count: 6

http://stackoverflow.com/comment/89984692
type: QuestionComment
type: Comment
score: 2
has text: `if "__iter__" in dir(a):`? Or just try to get it directly (i.e. `a.__iter__`) and capture the `AttributeError` if it doesn't exist? Or `getattr(a, "__iter__", None)` (replace `None` with whatever default you might want). Or...
comment on: http://stackoverflow.com/q/51507799

http://stackoverflow.com/q/51639411
favorite count: 0
linked to: http://stackoverflow.com/q/513882
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90293084
tagged with: dictionary
has answer: http://stackoverflow.com/a/51639497
has answer: http://stackoverflow.com/a/51639714
tagged with: code-duplication
upvote count: 1
has body: Background: I need to read the same key/value from a dictionary (exactly) twice. Question: There are two ways, as shown below, Method 1. Read it with the same key twice, e.g., sample_map = {'A':1,} ... if sample_map.get('A', None) is not None: print("A's value in map is {}".format(sample_map.get('A'))) Method 2. Read it once and store it in a local variable, e.g, sample_map = {'A':1,} ... ret_val = sample.get('A', None) if ret_val is not None: print("A's value in map is {}".format(ret_val)) Which way is better? What are their Pros and Cons? Note that I am aware that print() can naturally handle ret_val of None. This is a hypothetical example and I just use it for illustration purposes.
type: Question
answer count: 3
has answer: http://stackoverflow.com/a/51639478
has title: Use of a temporary variable vs repeatedly read same key/value from a dictionary
downvote count: 0
has comment: http://stackoverflow.com/comment/90244362
score: 1
tagged with: anti-patterns

http://stackoverflow.com/a/51630031
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51629691
upvote count: 2
has body: You can use Counter from collections in combination with defaultdict. As the name suggests, the counter counts the same elements, and a defaultdict lets you access non-existing keys by providing a default value (an empty Counter in this case). Your code then becomes from collections import Counter, defaultdict d = defaultdict(Counter) d['siteA'] = Counter({'00000000': 3, '11111111': 4, '22222222': 5}) d['siteB'] = Counter({'00000000': 1, '11111111': 2, '22222222': 5}) print(d.items()) &gt; dict_items([('siteA', Counter({'22222222': 5, '11111111': 4, '00000000': 3})), &gt; ('siteB', Counter({'22222222': 5, '11111111': 2, '00000000': 1}))]) # d + e: d['siteA'].update({'00000000': 5}) print(d.items()) &gt; dict_items([('siteA', Counter({'00000000': 8, '22222222': 5, '11111111': 4})), &gt; ('siteB', Counter({'22222222': 5, '11111111': 2, '00000000': 1}))]) # d + f d['siteB'].update({'33333333': 10}) print(d.items()) &gt; dict_items([('siteA', Counter({'00000000': 8, '22222222': 5, '11111111': 4})), &gt; ('siteB', Counter({'33333333': 10, '22222222': 5, '11111111': 2, '00000000': 1}))]) # d + g d['siteC'].update({'00000000': 8}) print(d.items()) &gt; dict_items([('siteA', Counter({'00000000': 8, '22222222': 5, '11111111': 4})), &gt; ('siteB', Counter({'33333333': 10, '22222222': 5, '11111111': 2, '00000000': 1})), &gt;. ('siteC', Counter({'00000000': 8}))])

http://stackoverflow.com/comment/90139409
score: 0
type: AnswerComment
has text: Edited the post.
type: Comment
comment on: http://stackoverflow.com/a/51577658

intersection
tags question: http://stackoverflow.com/q/51560417
type: Tag
tag name: intersection
tags question: http://stackoverflow.com/q/51569482
tags question: http://stackoverflow.com/q/51528617

http://stackoverflow.com/q/51575883
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51576026
accepted answer: http://stackoverflow.com/a/51576026
has body: For over a year I used this mess to execute 'for loop' simultaneously. import time #in actual program this is a dynamic dictionary with different amount of keys/values pairs mydict = {1: 'czech', 2: 'dutch', 3: 'English'} def function(id): time.sleep(1) print(mydict[id]) #if you try this code, you will see 'print' for all dictionary keys #simultaneously, despite the fact that it's a for loop with time.sleep #the exec here creates new function with name from 'mydict' and connects #it to a separate process for id in mydict: exec("""def func""" + str(id) + """():\n function(id)""") exec("""p""" + str(id) + """ = Process(target=func""" + str(id) + """)\np""" + str(id) + """.start()""") But now sometimes, when other program (even with different venv) tries to execute similar code, the first program that already executing this code completely breaks. I think it's caused by 'exec' limitations, but I am not sure, since I have never seen any errors. It's just pauses or something like that. If anyone have any idea what is the problem and how it could be tweaked so several simultaneous 'for loops' execution would be possible, I would be happy to read it.
downvote count: 0
answer count: 1
tagged with: exec
favorite count: 0
tagged with: python-3.x
has title: second simultaneous 'for loop' execution break the first one

http://stackoverflow.com/comment/130443217
type: AnswerComment
has text: If speed is of the essence, apply numba to it. Eg if you want to get to an individual number in the above array e.g where the second item in the row is 6 give me the 3rd item in that row (=7) timeit x[x[:,1]==6][:,2][0] # 4.05 µs ± 171 ns but with numba: @jit(nopython = True) def findresult(array,x,y): return array[array[:,1]==x][:,y][0] timeit findresult(x,6,2) # 998 ns ± 136 ns per loop
type: Comment
comment on: http://stackoverflow.com/a/51508733
score: 0

http://stackoverflow.com/comment/89981267
type: QuestionComment
comment on: http://stackoverflow.com/q/51505912
has text: could it be that the loop is running infinitely without hitting connection.commit()?
score: 0
type: Comment

http://stackoverflow.com/q/51609186
has answer: http://stackoverflow.com/a/51609284
tagged with: list
has body: I have large data sets of XYZ data I need to extract only the XY as PTS and find the minimum and maximum. The real data sets are floats... ( I still struggle to understand the list comprehension I guess... ) This is part of a bigger problem with Ascii Grid Files, that Im trying to resolve by creating a larger XYZ data set... (Which is a poor approach I know...) # I have got this... xyz data... PTSXYZ = [[1,1,3],[4,4,2],[6,4,1],[6,6,5]] # I want to get this....xy data PTSXY = [[1,1],[4,4],[6,4],[6,6]] # I have Tried.... this ?? PTSXY = [PTSXYZ[0][i],PTSXYZ[1][i] for i in PTSXYZ] # Addressing Wrong ? #Then If I want the Minimum &amp; Maximum X Values.. print min(PTSXY[:][0]),max(PTSXY[:][0])
tagged with: grid
type: Question
has answer: http://stackoverflow.com/a/51609325
has answer: http://stackoverflow.com/a/51609380
tagged with: ascii
score: 0
answer count: 3
has title: Reducing a X,Y,Z list to an X,Y list and retrieve the min & max X of the XY PTS
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89979880
type: QuestionComment
comment on: http://stackoverflow.com/q/51504958
score: 0
has text: Why do you know about A B C D but not E...? However, this is futile as long as you're not getting more concrete. But if all this is as you describe, csv row by row is not the way to go for you. In a csv all rows must contain the same number of separators as the header. Otherwise you won't be able to read it with csv capable libraries.
type: Comment

http://stackoverflow.com/a/51560741
has comment: http://stackoverflow.com/comment/90088530
score: 0
has comment: http://stackoverflow.com/comment/90088655
type: Answer
has body: To access the value in the dictionary you would need to do this print(responses["WHAT'S YOUR NAME?"]) which would return the value assigned to that, in your case My name is ChatBot! would be the reply. You could replace the query any way you see fit, for example if your responses dictionary was this responses = { "WHAT'S YOUR NAME?":"My name is ChatBot!, "COOKIE":":cookie:" } You could access cookie by just doing reponses["COOKIE"]
answers question: http://stackoverflow.com/q/51560600

http://stackoverflow.com/q/51541386
has comment: http://stackoverflow.com/comment/90050508
has body: I have a dataframe like this: pd.DataFrame({'group': {0: 1, 1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2}, 'year': {0: 2007, 1: 2008, 2: 2009, 3: 2010, 4: 2006, 5: 2007, 6: 2008}, 'amount': {0: 2.0, 1: -4.0, 2: 5, 3: 7.0, 4: 8.0, 5: -10.0, 6: 12.0}}]) group year amount 0 1 2007 2 1 1 2008 -4 2 1 2009 5 3 1 2010 7 4 2 2006 8 5 2 2007 -10 6 2 2008 12 I want to add min, max, number of years that amount is negative,number of years that amount is positive for each group, up until each year (inclusive). My ideal dataframe looks like this group year amount min_utd max_utd no_n_utd no_p_utd 0 1 2007 2 2 2 0 1 1 1 2008 -4 -4 2 1 1 2 1 2009 5 -4 5 1 2 3 1 2010 7 -4 7 1 3 4 2 2006 8 8 8 0 1 5 2 2007 -10 -10 8 1 1 6 2 2008 12 -10 12 1 2 I am only aware of agg with which you can do for the whole group, or rolling when you do for a sliding window, but I dont know how to calculate from the beginning up to each line.
answer count: 2
tagged with: pandas
has title: Pandas - min and max of a column up until each line
favorite count: 0
possible better answer: http://stackoverflow.com/a/51541710
tagged with: python
has answer: http://stackoverflow.com/a/51541710
has answer: http://stackoverflow.com/a/51541683
type: AnsweredQuestion
downvote count: 2
accepted answer: http://stackoverflow.com/a/51541683
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90051029
score: -1

http://stackoverflow.com/q/51620634
type: UnansweredQuestion
has title: Generate random point positons on a torus
tagged with: python
tagged with: plot
score: 1
type: Question
has body: I'm working on a code to simulate propagation of particles on a torus surface. Initially, particles are gather on a "local" space, as shown on the following pic : Blue points are initial particles. The problem is, when I zoom in, particles don't seem to be spread randomly : First, I see they form like raws. Moreover, I'm working with N = 5 particles, but there seems to be 25 particles here (5 raws of 5). I suppose it comes from meshgrid() since 25 = 5^2, but I don't really understand how this function works to be honest. Here is my code : Creating the red torus : angle = np.linspace(0, 2*np.pi, 32) theta, phi = np.meshgrid(angle, angle) X = (R + r * np.cos(phi)) * np.cos(theta) Y = (R + r * np.cos(phi)) * np.sin(theta) Z = r * np.sin(phi) Placing initial points : thetaInit = ((np.random.rand(N)-0.5)*np.pi/16) phiInit = ((np.random.rand(N)-0.5)*np.pi/32) theta2, phi2 = np.meshgrid(phiInit, thetaInit) Xinit = (R + r * np.cos(phi2)) * np.cos(theta2) Yinit = (R + r * np.cos(phi2)) * np.sin(theta2) Zinit = r * np.sin(phi2) Where N is the number of particles, and r, R are respectively minor and major radius of the torus.
has comment: http://stackoverflow.com/comment/90207047
has comment: http://stackoverflow.com/comment/90207167
tagged with: random
upvote count: 1
downvote count: 0
favorite count: 0
answer count: 0

http://stackoverflow.com/a/51601684
accepted answer of: http://stackoverflow.com/q/51601633
score: 4
type: AcceptedAnswer
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51601633
downvote count: 0
has body: you can chain the results of itertools.repeat: import itertools list(itertools.chain.from_iterable(itertools.repeat(x,3) for x in ["A","B","C"])) result: ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'] this solution minimizes the loops &amp; the temporary lists (none is created)

http://stackoverflow.com/comment/90121637
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51577407
has text: @abarnert - thanks and noted exprStack - result was showing some visual difference between both. Also as per second comment - the code is not very clean - leftovers are there from trial and error + considering my lack of experience with pyparsing. However I don't think that is causing the original issue I am trying to understand.
score: 0

http://stackoverflow.com/a/51625320
downvote count: 1
has comment: http://stackoverflow.com/comment/90215721
accepted answer of: http://stackoverflow.com/q/51625207
has body: Make c as a function which returns a+b value
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90215475
type: Answer
answers question: http://stackoverflow.com/q/51625207
upvote count: 2
score: 1

http://stackoverflow.com/q/51629652
has answer: http://stackoverflow.com/a/51652331
tagged with: python
has title: How do you send a text response using the Python client for Dialogflow v2?
tagged with: dialogflow-es
upvote count: 1
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90255897
has comment: http://stackoverflow.com/comment/90244776
has body: I was following this tutorial that demonstrated how to create and deploy a chatbot using the v1 version of the Dialogflow API. I am trying to follow along using Dialogflow V2, but I am struggling with even the most basic of tasks, such as sending messages. So, how do I send a message from the Python client for Dialogflow V2?
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90239307
type: Question

python
tags question: http://stackoverflow.com/q/51590304
tags question: http://stackoverflow.com/q/51601932
tags question: http://stackoverflow.com/q/51578424
tags question: http://stackoverflow.com/q/51586751
tags question: http://stackoverflow.com/q/51552583
tags question: http://stackoverflow.com/q/51566331
tags question: http://stackoverflow.com/q/51550950
tags question: http://stackoverflow.com/q/51530112
tags question: http://stackoverflow.com/q/51497423
tags question: http://stackoverflow.com/q/51536281
tags question: http://stackoverflow.com/q/51573503
tags question: http://stackoverflow.com/q/51604235
tags question: http://stackoverflow.com/q/51617433
tags question: http://stackoverflow.com/q/51598038
tags question: http://stackoverflow.com/q/51499207
tags question: http://stackoverflow.com/q/51622143
tags question: http://stackoverflow.com/q/51538779
tags question: http://stackoverflow.com/q/51587370
tags question: http://stackoverflow.com/q/51578425
tags question: http://stackoverflow.com/q/51541533
tags question: http://stackoverflow.com/q/51491217
tags question: http://stackoverflow.com/q/51567471
tags question: http://stackoverflow.com/q/51557972
tags question: http://stackoverflow.com/q/51620414
tags question: http://stackoverflow.com/q/51598310
tags question: http://stackoverflow.com/q/51548826
tags question: http://stackoverflow.com/q/51584343
tags question: http://stackoverflow.com/q/51541043
tags question: http://stackoverflow.com/q/51583624
tags question: http://stackoverflow.com/q/51624320
tags question: http://stackoverflow.com/q/51550957
tags question: http://stackoverflow.com/q/51546036
tags question: http://stackoverflow.com/q/51501178
tags question: http://stackoverflow.com/q/51598254
tags question: http://stackoverflow.com/q/51614297
tags question: http://stackoverflow.com/q/51507787
tags question: http://stackoverflow.com/q/51519086
tags question: http://stackoverflow.com/q/51609003
tags question: http://stackoverflow.com/q/51554290
tags question: http://stackoverflow.com/q/51574834
tags question: http://stackoverflow.com/q/51491211
tags question: http://stackoverflow.com/q/51506296
tags question: http://stackoverflow.com/q/51600164
tags question: http://stackoverflow.com/q/51547935
tags question: http://stackoverflow.com/q/51583346
tags question: http://stackoverflow.com/q/51615437
tags question: http://stackoverflow.com/q/51540806
tags question: http://stackoverflow.com/q/51530515
tags question: http://stackoverflow.com/q/51514488
tags question: http://stackoverflow.com/q/51585989
tags question: http://stackoverflow.com/q/51501418
tags question: http://stackoverflow.com/q/51544847
tags question: http://stackoverflow.com/q/51611358
tags question: http://stackoverflow.com/q/51585660
tags question: http://stackoverflow.com/q/51609513
tags question: http://stackoverflow.com/q/51525789
tags question: http://stackoverflow.com/q/51512306
tags question: http://stackoverflow.com/q/51620195
tags question: http://stackoverflow.com/q/51612266
tags question: http://stackoverflow.com/q/51625314
tags question: http://stackoverflow.com/q/51607065
tags question: http://stackoverflow.com/q/51587332
tags question: http://stackoverflow.com/q/51632928
tags question: http://stackoverflow.com/q/51531488
tags question: http://stackoverflow.com/q/51503925
tags question: http://stackoverflow.com/q/51612273
tags question: http://stackoverflow.com/q/51567310
tags question: http://stackoverflow.com/q/51630434
tags question: http://stackoverflow.com/q/51536111
tags question: http://stackoverflow.com/q/51604174
tags question: http://stackoverflow.com/q/51598223
tags question: http://stackoverflow.com/q/51628514
tags question: http://stackoverflow.com/q/51534731
tags question: http://stackoverflow.com/q/51632134
tags question: http://stackoverflow.com/q/51634251
tags question: http://stackoverflow.com/q/51499643
tags question: http://stackoverflow.com/q/51592488
tags question: http://stackoverflow.com/q/51545301
tags question: http://stackoverflow.com/q/51514212
tags question: http://stackoverflow.com/q/51635689

http://stackoverflow.com/q/51541372
upvote count: 2
accepted answer: http://stackoverflow.com/a/51542283
score: 0
answer count: 2
downvote count: 2
tagged with: linkedin-api
has body: Is it possible to scrap a company's news feed on linkedin? To collect data like how many comments in each post? I wanna do it using python
favorite count: 0
has answer: http://stackoverflow.com/a/51541469
has title: Scraping linkedin news feed
tagged with: python
tagged with: web-scraping
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51541469
has answer: http://stackoverflow.com/a/51542283

http://stackoverflow.com/comment/89969364
type: Comment
has text: Haha, amazing. So presumably you could apply this to a number of different lines with similar but slightly different curves.
score: 1
comment on: http://stackoverflow.com/a/51498990
type: AnswerComment

python-sphinx
tags question: http://stackoverflow.com/q/51487209
tag name: python-sphinx
tags question: http://stackoverflow.com/q/51561265
type: Tag

http://stackoverflow.com/comment/90160105
type: QuestionComment
comment on: http://stackoverflow.com/q/51486063
has text: @Divakar, As a general rule, is this true of only `iloc`, or does `loc` also return views? Probably beyond the scope of a single comment, but I'm also interested in *why* direct indexing via `df[col_list]` should return a copy (is it a design choice / side-effect / is there any benefit?).
score: 2
type: Comment

http://stackoverflow.com/a/51584443
has comment: http://stackoverflow.com/comment/90135197
has comment: http://stackoverflow.com/comment/90135030
type: Answer
has comment: http://stackoverflow.com/comment/90134903
has body: Use a match function to determine what to lift, and pass along the target object where you move key-value pairs to to recursive calls. If that target is missing, you know the current call is for the top-level. The match function should return the new key for the new dictionary. To produce a new dictionary, just produce a new dictionary and put recursion results into that object. I prefer to use @singledispatch() to handle different types when recursing: from functools import singledispatch @singledispatch def lift_values(obj, match, targetname=None, **kwargs): """Lift key-value pairs from a nested structure to the top For key-value pairs anywhere in the nested structure, if match(path, value) returns a value other than `None`, the key-value pair is moved to the top-level dictionary when targetname is None, or to a new dictionary stored under targetname is not None, using the return value of the match function as the key. path is the tuple of all keys and indices leading to the value. For example, for an input {'foo': True, 'bar': [{'spam': False, 'ham': 42}]} and the match function lambda p, v: p if isinstance(v, bool) else None and targetname "flags", this function returns {'flags': {('foo',): True, ('bar', 0, 'spam'): False}, 'bar': [{'ham': 42}]} """ # leaf nodes, no match testing needed, no moving of values return obj @lift_values.register(list) def _handle_list(obj, match, _path=(), **kwargs): # list values, no lifting, just passing on the recursive call return [lift_values(v, match, _path=_path + (i,), **kwargs) for i, v in enumerate(obj)] @lift_values.register(dict) def _handle_list(obj, match, targetname=None, _path=(), _target=None): result = {} if _target is None: # this is the top-level object, key-value pairs are lifted to # a new dictionary stored at this level: if targetname is not None: _target = result[targetname] = {} else: # no target name? Lift key-value pairs into the top-level # object rather than a separate sub-object. _target = result for key,…
score: 3
has comment: http://stackoverflow.com/comment/90135299
upvote count: 3
has comment: http://stackoverflow.com/comment/90135316
has comment: http://stackoverflow.com/comment/90134967
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90135147
accepted answer of: http://stackoverflow.com/q/51584385
has comment: http://stackoverflow.com/comment/90135099
answers question: http://stackoverflow.com/q/51584385

http://stackoverflow.com/comment/90114474
type: Comment
comment on: http://stackoverflow.com/a/51572886
has text: I'm still not really seeing a clean way of dealing with user input that may be a stringified zero. If I check len() thats fine, but then to do math I have to change the type. And if my function also returns zero, then I have to change it back to a string, and check len() again to determine whether the data is worth rendering back to the user. That is about 4 lines of code to do what len() or exists() does in perl.
type: AnswerComment
score: 0

tensorflow-estimator
tags question: http://stackoverflow.com/q/51537682
tags question: http://stackoverflow.com/q/51616960
tags question: http://stackoverflow.com/q/51496412
tag name: tensorflow-estimator
type: Tag
tags question: http://stackoverflow.com/q/51625529
tags question: http://stackoverflow.com/q/51623671

http://stackoverflow.com/comment/90101088
has text: this code can't work in it's current state.
comment on: http://stackoverflow.com/q/51567059
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90210865
has text: I don't have high enough reputation for it to show :(
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51618750

http://stackoverflow.com/q/51580491
tagged with: python
has comment: http://stackoverflow.com/comment/90127310
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90127473
has comment: http://stackoverflow.com/comment/90126677
type: Question
has answer: http://stackoverflow.com/a/51581487
score: 0
answer count: 1
has title: getting html dynamic content python3
has body: I wanted to get a part of html dynamic content from a website, I can see this content in "inspect element" but not in "view source". I tried to use BeautifulSoup and selenium libraries with no success, since after loading the page I need to press some screen buttons to load the content. For example, in the website http://play.typeracer.com I can load its html source code but I can't load the content that shows up after pressing "Practice" on the webpage. ( tables and text) Hope I was explicit, thanks for your attention
has comment: http://stackoverflow.com/comment/90127502
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90126579
tagged with: http://stackoverflow.com/tag/html
accepted answer: http://stackoverflow.com/a/51581487

http://stackoverflow.com/comment/90174232
type: Comment
type: QuestionComment
has text: yeah I just edited it and add some more details as well as a pic of what the results were
comment on: http://stackoverflow.com/q/51604147
score: 0

http://stackoverflow.com/q/51563893
has comment: http://stackoverflow.com/comment/90094936
answer count: 0
has comment: http://stackoverflow.com/comment/90094842
type: Question
has comment: http://stackoverflow.com/comment/90095543
tagged with: database
tagged with: image
score: 0
tagged with: python-3.x
has title: Use Python to search online database and download images
has comment: http://stackoverflow.com/comment/90094960
type: UnansweredQuestion
has body: I'd like my Python code to iterate through a numpy array and search an online database with each of these numbers. This seems fairly complicated, since it must enter the number into a certain search box after navigating to the URL, and then I would like it to return all the images that appear after searching for each number (there are multiple images in each search result). Is there a straightforward way to do this?
tagged with: python

http://stackoverflow.com/comment/89977606
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51503607
has text: Is it possible you meant `"hello.py"` instead of `"helo.py"`?

http://stackoverflow.com/q/51529791
has comment: http://stackoverflow.com/comment/90027829
has comment: http://stackoverflow.com/comment/90027919
tagged with: ipython
has body: How do you exit the ipdb debugger? According to this question typing q should just work. I am on Python 3.6.6, Ipython 6.4.0 and that does not work in the following context: I have a function, f(x), that is called from another function in a loop. After 2 iterations I just want to stop evaluation and exit the debugger. My f(x) just looks like this: def f(x): ipdb.set_trace() Literally meant to allow me to inspect x at runtime. However, typing q does not exit the debugger. Typing os._exit(0) kills the kernel. There must be something better? This is within a jupyter notebook.
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90027911
favorite count: 0
has comment: http://stackoverflow.com/comment/90027800
has comment: http://stackoverflow.com/comment/90027878
has answer: http://stackoverflow.com/a/51529821
tagged with: python
tagged with: jupyter-notebook
tagged with: python-3.x
score: 2
tagged with: ipdb
upvote count: 2
has comment: http://stackoverflow.com/comment/90027930
linked to: http://stackoverflow.com/q/32055062
type: UnansweredQuestion
has title: how to break out of ipdb debugger?
has comment: http://stackoverflow.com/comment/90027902
type: Question
has comment: http://stackoverflow.com/comment/90027866

http://stackoverflow.com/comment/89975582
type: Comment
has text: @Carl what about this - don't put the `cv2.imshow('Screen', frame)` in the while loop, put it just before - then does it work? If you put it in the loop, it'll create a frame for each iteration, but if you put it before, it should only create one
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51485453

http://stackoverflow.com/comment/89958074
type: QuestionComment
score: 0
has text: Oh, I see. In GrandChild I can pass anything to arg1, but it doesn't have to be named arg1. But the solution still works, just the mandatory arguments should not be named arg1,arg2 when creating the objects, but simply passed values without keywords. Either way, the problem is another.
comment on: http://stackoverflow.com/q/51494723
type: Comment

http://stackoverflow.com/comment/90194692
type: QuestionComment
comment on: http://stackoverflow.com/q/51613638
type: Comment
has text: I have tried it and it does not highlight the whole row but the items found, it seems to me that you are not implementing it correctly, it shows the code of the implementation that you use.
score: 0

http://stackoverflow.com/q/51531804
answer count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/51531828
favorite count: 0
accepted answer: http://stackoverflow.com/a/51531828
upvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/489999
type: AnsweredQuestion
tagged with: list
has title: Convert List to integer in Python
duplicate of: http://stackoverflow.com/q/489999
type: Question
has body: In Python, I want to convert list into int. so if i have input like this: a=[1,2,3,4] i want this output: 1234 so How it is possible?
possible better answer: http://stackoverflow.com/a/51531867
has answer: http://stackoverflow.com/a/51531867
score: -1
has answer: http://stackoverflow.com/a/51531869

http://stackoverflow.com/q/51575139
has body: The following code is giving me the error: Traceback (most recent call last): File "AMZGetPendingOrders.py", line 66, in &lt;module&gt; item_list.append(item['SellerSKU']) TypeError: string indices must be integers The code: from mws import mws import time import json import xmltodict access_key = 'xx' #replace with your access key seller_id = 'yy' #replace with your seller id secret_key = 'zz' #replace with your secret key marketplace_usa = '00' orders_api = mws.Orders(access_key, secret_key, seller_id) orders = orders_api.list_orders(marketplaceids=[marketplace_usa], orderstatus=('Pending'), fulfillment_channels=('MFN'), created_after='2018-07-01') #save as XML file filename = 'c:order.xml' with open(filename, 'w') as f: f.write(orders.original) #ConvertXML to JSON dictString = json.dumps(xmltodict.parse(orders.original)) #Write new JSON to file with open("output.json", 'w') as f: f.write(dictString) #Read JSON and parse our order number with open('output.json', 'r') as jsonfile: data = json.load(jsonfile) #initialize blank dictionary id_list = [] for order in data['ListOrdersResponse']['ListOrdersResult']['Orders']['Order']: id_list.append(order['AmazonOrderId']) #This "gets" the orderitem info - this code actually is similar to the initial Amazon "get" though it has fewer switches orders_api = mws.Orders(access_key, secret_key, seller_id) #opens and empties the orderitem.xml file open('c:orderitem.xml', 'w').close() #iterated through the list of AmazonOrderIds and writes the item information to orderitem.xml for x in id_list: orders = orders_api.list_order_items(amazon_order_id = x) filename = 'c:orderitem.xml' with open(filename, 'a') as f: f.write(orders.original) #ConvertXML to JSON amz_items_pending = json.dumps(xmltodict.parse(orders.original)) #Write new JSON to file with open("pending.json", 'w') as f: f.write(amz_items_pending) #read JSON and parse item_no and qty with open('pending.json', 'r') as jsonfile1: data1 = json.load(jsonfile1) #initialize blank…
has title: PYTHON JSONtoDICT help needed - It appears python is interpreting my json-dictionary conversion as a list
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/6077675
has answer: http://stackoverflow.com/a/51575455
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90117399
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51575203
tagged with: http://stackoverflow.com/tag/json
type: Question

http://stackoverflow.com/comment/90203720
has text: I edited the post. I'm currently trying out the solution of Dhanush1215 (below).
score: 1
comment on: http://stackoverflow.com/q/51618025
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51507858
linked to: http://stackoverflow.com/q/12265451
answer count: 1
has answer: http://stackoverflow.com/a/51507859
score: 0
tagged with: pandas
tagged with: python
has body: I've seen online how to format a Pandas DataFrame with .style. However, I have a table with a bunch of text, and would like to be able to format the cells, depending on the words inside. Borrowing from this logic in the above linked reference: def color_negative_red(val): color = 'red' if val &lt; 0 else 'black' return 'color: %s' % color For example, color the cell red if the word "BBC" is in a cell. Color it green if "XYZ" is in the cell. Color it black if "ZYX" is in the cell, etc. def style_dataframe(val): color = "red" if "BBC" in val else "white" # fuzzy match 'BBC' color = "green" if val == "XYZ" else color # find exact match color = "black" if val == "ZYX" else color # find exact match return 'background-color: %s' % color ... df.style.applymap(style_dataframe) df.to_html("test.html") However, this doesn't color anything. Screenshot of test.html:
type: UnansweredQuestion
has title: Stylize cell if word found in Pandas DataFrame?
type: Question
tagged with: pandas-styles

http://stackoverflow.com/comment/90045138
comment on: http://stackoverflow.com/q/51534279
has text: In addition to my last comment, you may get better convergence results if all `p0` values are within the same order of magnitude. btw, when I said to multiply `p0` by 1E9 I meant only the lifetime (`p0[1]`)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51534957
type: Question
tagged with: recursion
accepted answer: http://stackoverflow.com/a/51535159
has comment: http://stackoverflow.com/comment/90037791
score: -1
has comment: http://stackoverflow.com/comment/90037636
has comment: http://stackoverflow.com/comment/90039199
answer count: 2
has comment: http://stackoverflow.com/comment/90037793
has title: Create a recursive function with counter
has comment: http://stackoverflow.com/comment/90038117
possible better answer: http://stackoverflow.com/a/51535250
favorite count: 0
has comment: http://stackoverflow.com/comment/90037677
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51535250
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51535159
has comment: http://stackoverflow.com/comment/90037638
type: AnsweredQuestion
downvote count: 3
has body: I want to create a recursive function with 2 parameters (steps, number). Inside the recursion something with the number happens and calls the function again with steps-1 and a new number. As soon as steps == 0 I want to increase a counter, so I see how many function calls with steps 0 are encountered, depending on the algorithm within the function. Is there a way to do this - without global variables or additional parameters, both are not possible! I tried it with: if not counter in locals(): counter=0 but this doesn't work it says UnboundLocalError: local variable 'counter' referenced before assignment here the complete code: def IsaacRule(steps, number): if not counter in locals(): counter = 0 if steps == 0: counter+=1 return counter if ((number - 1) / 3) % 2 == 1: IsaacRule(steps-1, (number - 1) / 3) if (number * 2) % 2 == 0: IsaacRule(steps-1, number*2) return counter with global variable (and counter=0 outside of the function) it works - but I am not allowed to use a global variable

http://stackoverflow.com/comment/90201097
type: QuestionComment
score: 0
has text: I don't know much about twitter or sentiment analysis, but if you get to the point where you're ready to write your results to a csv file, the [csv](https://docs.python.org/3/library/csv.html) module is very helpful.
comment on: http://stackoverflow.com/q/51616546
type: Comment

http://stackoverflow.com/q/51620139
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/90206191
favorite count: 0
has answer: http://stackoverflow.com/a/68188240
has comment: http://stackoverflow.com/comment/90206767
has body: Tried running a file with the following imports: from flask_sqlalchemy import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker Received the following error: ImportError: No module named 'flask_sqlalchemy' SQLAlchemy is installed. Still, I tried to reinstall into the directory in which it will be used. I got this: The directory '/Users/_/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/_/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Requirement already satisfied: Flask-SQLAlchemy in /Library/Python/2.7/site-packages (2.3.2) Requirement already satisfied: Flask&gt;=0.10 in /Library/Python/2.7/site-packages (from Flask-SQLAlchemy) (1.0.2) Requirement already satisfied: SQLAlchemy&gt;=0.8.0 in /Library/Python/2.7/site-packages (from Flask-SQLAlchemy) (1.2.10) Requirement already satisfied: Jinja2&gt;=2.10 in /Library/Python/2.7/site-packages (from Flask&gt;=0.10-&gt;Flask-SQLAlchemy) (2.10) Requirement already satisfied: itsdangerous&gt;=0.24 in /Library/Python/2.7/site-packages (from Flask&gt;=0.10-&gt;Flask-SQLAlchemy) (0.24) Requirement already satisfied: Werkzeug&gt;=0.14 in /Library/Python/2.7/site-packages (from Flask&gt;=0.10-&gt;Flask-SQLAlchemy) (0.14.1) Requirement already satisfied: click&gt;=5.1 in /Library/Python/2.7/site-packages (from Flask&gt;=0.10-&gt;Flask-SQLAlchemy) (6.7) Requirement already satisfied: MarkupSafe&gt;=0.23 in /Library/Python/2.7/site-packages (from Jinja2&gt;=2.10-&gt;Flask&gt;=0.10-&gt;Flask-SQLAlchemy) (1.0) The bit about me not owning the directory is incorrect. I'm the only one on this machine. I own eve…
has comment: http://stackoverflow.com/comment/90206358
has comment: http://stackoverflow.com/comment/90206473
has comment: http://stackoverflow.com/comment/90206230
has comment: http://stackoverflow.com/comment/90206674
has comment: http://stackoverflow.com/comment/90206279
tagged with: python
has answer: http://stackoverflow.com/a/68183231
has comment: http://stackoverflow.com/comment/90206325
score: 14
type: AnsweredQuestion
upvote count: 14
has answer: http://stackoverflow.com/a/60438611
has comment: http://stackoverflow.com/comment/90206249
has title: ImportError: No module named 'flask_sqlalchemy' w/ 2 Versions of Python Installed
has comment: http://stackoverflow.com/comment/90206338
has comment: http://stackoverflow.com/comment/90206625
has comment: http://stackoverflow.com/comment/90206404
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/67447156
type: Question
has answer: http://stackoverflow.com/a/64995629
has answer: http://stackoverflow.com/a/72665703
accepted answer: http://stackoverflow.com/a/60438611
has answer: http://stackoverflow.com/a/64309304
has comment: http://stackoverflow.com/comment/90206319
has answer: http://stackoverflow.com/a/60892697
has comment: http://stackoverflow.com/comment/90206653
has comment: http://stackoverflow.com/comment/90206700
answer count: 16
has answer: http://stackoverflow.com/a/53371217
has answer: http://stackoverflow.com/a/58089800
has answer: http://stackoverflow.com/a/51620300
has answer: http://stackoverflow.com/a/78296056
has comment: http://stackoverflow.com/comment/90206274
has answer: http://stackoverflow.com/a/57593709
has answer: http://stackoverflow.com/a/79145169
has comment: http://stackoverflow.com/comment/90206442
has comment: http://stackoverflow.com/comment/90206562
possible better answer: http://stackoverflow.com/a/53371217
has comment: http://stackoverflow.com/comment/90206344
downvote count: 0
has answer: http://stackoverflow.com/a/59990491
has answer: http://stackoverflow.com/a/54642718

http://stackoverflow.com/q/51592393
answer count: 1
has body: I have many dataframe like this: TIME A B C D E F G H I K 2018/07/30 10:51:14.742 540 136 20 1752 1887 2052 1 1 0 0 2018/07/30 10:51:14.774 536 136 20 1879 1889 2053 1 1 0 0 2018/07/30 10:51:14.805 536 136 16 2011 1888 2049 1 1 0 0 2018/07/30 10:51:14.836 532 132 16 1986 1866 2028 1 1 0 0 2018/07/30 10:51:14.868 524 124 16 1762 1858 2049 1 1 0 0 2018/07/30 10:51:14.899 500 120 16 1806 1857 2038 1 1 0 0 2018/07/30 10:51:14.930 460 116 16 1995 1856 2009 1 1 0 0 2018/07/30 10:51:14.961 420 108 16 2024 1863 2064 1 1 0 0 2018/07/30 10:51:14.992 392 100 16 1989 1868 2042 1 1 0 0 2018/07/30 10:51:15.023 380 92 16 1819 1887 2040 1 1 0 0 2018/07/30 10:51:15.055 376 84 16 1934 1868 2045 1 1 0 0 2018/07/30 10:51:15.086 376 76 16 2034 1864 2070 1 1 0 0 2018/07/30 10:51:15.117 376 72 16 1976 1863 2033 1 1 0 0 2018/07/30 10:51:15.149 368 64 16 1826 1866 2057 1 0 0 0 2018/07/30 10:51:15.180 352 60 20 1852 1878 2046 1 0 0 0 2018/07/30 10:51:15.211 344 56 20 1863 1893 2039 1 0 0 0 2018/07/30 10:51:15.242 328 52 20 2120 1909 2062 1 0 0 0 2018/07/30 10:51:15.274 308 48 20 2028 1915 2105 1 0 0 0 2018/07/30 10:51:15.305 280 44 20 1871 1911 2052 1 0 0 0 2018/07/30 10:51:15.336 256 40 20 1927 1908 2032 1 0 0 0 2018/07/30 10:51:15.367 240 36 20 2076 1912 2031 1 0 0 0 2018/07/30 10:52:00.054 108 28 44 1869 1930 1982 0 0 1 0 2018/07/30 10:52:00.085 108 28 52 2134 1960 2094 0 0 1 0 2018/07/30 10:52:00.117 108 28 64 2084 1987 2137 0 0 1 0 2018/07/30 10:52:00.148 108 28 72 1897 1971 2112 0 0 1 0 2018/07/30 10:52:00.179 104 28 72 1977 1999 2127 0 0 1 0 2018/07/30 10:52:00.211 104 28 72 2104 1969 2081 0 0 1 0 2018/07/30 10:52:00.242 104 28 64 1904 1975 2046 0 0 1 0 I would like to do something like: IF (df['K'] == 1) 'for MORE THAN' 1 second DO something ELSE DO something else How can I save and remember the 0->1 transition (and viceversa), calculate the timestamps difference, and do the comparisons to decide what to do? All this in an iterative fashion? Thank you.
tagged with: python
has comment: http://stackoverflow.com/comment/90150460
has answer: http://stackoverflow.com/a/51592669
type: AnsweredQuestion
has title: Timestamp analysis in a dataframe for decide actions
tagged with: timestamp
type: Question
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51592669
score: 0
tagged with: pandas

http://stackoverflow.com/q/51599431
has comment: http://stackoverflow.com/comment/90169356
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54396620
has comment: http://stackoverflow.com/comment/90169632
tagged with: python
type: Question
has body: I have an array column (required of me, I know this is not typical convention) that I need to filter on in a query. I am trying to use contains(), db.session.query(table).filter((table.name.ilike ('%'+name+'%')), table.languages.contains(language)).limit(200) But I keep getting this error: NotImplementedError: ARRAY.contains() not implemented for the base ARRAY type; please use the dialect-specific ARRAY type I am new to Flask-Sqlalchemy so I am not sure how to use this correctly. Any help is much appreciated!
score: 0
answer count: 1
tagged with: flask-sqlalchemy
has title: query filter on postgresql array column using array.contains()
has comment: http://stackoverflow.com/comment/90165014
tagged with: postgresql

http://stackoverflow.com/q/51600579
has body: I am currently using the loc function as: import numpy as np import pandas as pd df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]}) a=df.loc[(df.A==1), ['B']] print(a) This returns "B 2" instead of "2" so I can't append that value into my output table as: output_table['column'][row]=a How can I get just "2" instead of the header and value?
tagged with: pandas
has answer: http://stackoverflow.com/a/51600802
favorite count: 0
type: Question
has title: Find value in DataFrame using conditions
tagged with: spyder
tagged with: python
score: 0
upvote count: 1
answer count: 1
downvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90167324

http://stackoverflow.com/a/51565975
type: Answer
score: 4
has body: The way to do this: from foo import bar %debug --breakpoint /path/to/foo.py:10 bar() This will import bar into the namespace and run it with the breakpoint on line 10 of the module.
upvote count: 4
answers question: http://stackoverflow.com/q/51565847
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51565847

http://stackoverflow.com/comment/90030876
score: 0
type: Comment
type: QuestionComment
has text: @Hozikimaru I have figured it out, I had to access the value by using `print (data["text"].value)` in python. thank you for everything!
comment on: http://stackoverflow.com/q/51525462

http://stackoverflow.com/q/51568990
type: Question
accepted answer: http://stackoverflow.com/a/51569060
has body: I am trying to retrieve values from db and I am stack from start because sqlite3 is unable to open the db file after I was giving the right path. Version 1: sqlite_file = os.environ.get('DATABASE_URL', 'sqlite:///db.sqlite') conn = sqlite3.connect(sqlite_file) c = conn.cursor() Version 2: sqlite_file = app.config['SQLALCHEMY_DATABASE_URI'] conn = sqlite3.connect(sqlite_file) c = conn.cursor() Where: SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'sqlite:///db.sqlite') In both situations the error is Error on request: Traceback (most recent call last): File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/werkzeug/serving.py", line 209, in run_wsgi execute(self.server.app) File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/werkzeug/serving.py", line 197, in execute application_iter = app(environ, start_response) File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise raise value File "/home/ubuntu/workspace/avb/app.py", line 222, in &lt;module&gt; conn = sqlite3.connect(sqlite_file) sqlite3.OperationalError: unable to open database file
tagged with: sqlite
downvote count: 0
answer count: 1
score: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51569060
has title: I need a hint for sqlite3
has comment: http://stackoverflow.com/comment/90104127
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90104222
upvote count: 1

http://stackoverflow.com/comment/90050465
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51541265
type: QuestionComment
has text: @DeepSpace what do you mean?

http://stackoverflow.com/q/51524285
accepted answer: http://stackoverflow.com/a/51524368
has title: Adding records in Pandas datetime columns in Python
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51524368
has body: I have data set like below: Value Time delta time 2 2009-05-27 18:45 0:15:00 4 2009-05-27 19:00 0:15:00 1 2009-05-27 19:15 0:15:00 1 2009-05-27 19:30 0:15:00 2 2009-05-27 20:45 1:15:00 I have calculated the time different between each rows using the following code: df['deltatime']= df['Date'].diff(periods=1) I need to add records in between records which have a delta time more than 15 min. I want the out put of the code to be something like below with 0 values for the added records: Value Time delta time 2 2009-05-27 18:45 0:15:00 4 2009-05-27 19:00 0:15:00 1 2009-05-27 19:15 0:15:00 1 2009-05-27 19:30 0:15:00 0 2009-05-27 19:45 0:15:00 0 2009-05-27 20:00 0:15:00 0 2009-05-27 20:15 0:15:00 0 2009-05-27 20:30 0:15:00 2 2009-05-27 20:45 0:15:00 I was wondering if anyone could help me with this problem?
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/a/51611970
answers question: http://stackoverflow.com/q/51611358
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90188802
has body: Replace a = ["x" * n] by a = ["x"] * n and it should work, provided you get rid of all syntax errors. The following is the output. [7] [7, 7] [7, 7, 1] [7, 7, 1, 8] [7, 7, 1, 8, 2]
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51611358
type: Answer

http://stackoverflow.com/comment/93685294
comment on: http://stackoverflow.com/q/51493785
score: 0
type: Comment
type: QuestionComment
has text: @physicsmajor: Yes, I added my answer. Please have a look and accept the answer if it works for you!

http://stackoverflow.com/a/51562462
type: Answer
downvote count: 0
has body: As I mentioned above, a good solution to this type of thing would be to dump the CSV into a sqlite db and the just query as needed :)
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51547269
accepted answer of: http://stackoverflow.com/q/51547269
upvote count: 1

http://stackoverflow.com/q/51495719
linked to: http://stackoverflow.com/q/33124347
has answer: http://stackoverflow.com/a/51496819
downvote count: 0
has comment: http://stackoverflow.com/comment/89959443
answer count: 1
accepted answer: http://stackoverflow.com/a/51496819
favorite count: 0
has body: I'm writing in Python but I'm sure other languages have the same approach. I'm coding a tool for a 3D Software (Softimage) and the SDK manual doesn't specify anything about how I need to specify the color and I got to this conclusion just by trial and error looking for some codes in the internet. The color needed to be specified with an integer number which I get it like this: With colors in 0-255 values: Rvalue | Gvalue &lt;&lt; 8 | Bvalue &lt;&lt; 16 | Avalue &lt;&lt; 24 It seems to work perfectly, now I'd like to convert this integer number back to RGBA values. How should I proceed ?
tagged with: software-design
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has title: Bitshift Int Color back to RGB
type: Question

http://stackoverflow.com/comment/90191978
type: QuestionComment
has text: @Joel Yes, but I am not able to figure out what went wrong
type: Comment
comment on: http://stackoverflow.com/q/51613385
score: 0

http://stackoverflow.com/comment/89949479
comment on: http://stackoverflow.com/a/51490359
type: Comment
has text: No, I mean the Object Oriented style to make widget on top of other widget. For example if we want to hide widget we can use `btn.place_forget()`, to make widget at the top, is there any way that using object oriented style?
score: 0
type: AnswerComment

lstm
tags question: http://stackoverflow.com/q/51600250
tags question: http://stackoverflow.com/q/51541385
tags question: http://stackoverflow.com/q/51636620
tags question: http://stackoverflow.com/q/51506404
tags question: http://stackoverflow.com/q/51575433
tags question: http://stackoverflow.com/q/51618745
tag name: lstm
tags question: http://stackoverflow.com/q/51578810
tags question: http://stackoverflow.com/q/51484969
tags question: http://stackoverflow.com/q/51543875
tags question: http://stackoverflow.com/q/51537837
tags question: http://stackoverflow.com/q/51637854
tags question: http://stackoverflow.com/q/51609643
tags question: http://stackoverflow.com/q/51557380
type: Tag
tags question: http://stackoverflow.com/q/51586563
tags question: http://stackoverflow.com/q/51629480
tags question: http://stackoverflow.com/q/51618251
tags question: http://stackoverflow.com/q/51617856
tags question: http://stackoverflow.com/q/51602088

http://stackoverflow.com/a/51558680
score: 1
has comment: http://stackoverflow.com/comment/90085190
has comment: http://stackoverflow.com/comment/90085141
has body: You can use replace() and bfill() import numpy as np df['col_name'].replace(0, np.nan).bfill() If your 0 is a string, use df['col_name'].replace("0", np.nan).bfill() bfill means you will fill the NaNs backwards. You can also fill forwards using ffill() df['col_name'].replace(0, np.nan).ffill() As noted in comments, you can also set everything at once using to_replace arg: df.col.replace(to_replace=0, method='ffill') Example: df = pd.DataFrame({'col': [1,2,3,0,5,6,7,0,9]}) col 0 1 1 2 2 3 3 0 4 5 5 6 6 7 7 0 8 9 df.col.replace(0, np.nan).bfill() 0 1.0 1 2.0 2 3.0 3 5.0 4 5.0 5 6.0 6 7.0 7 9.0 8 9.0 Notice that once np.nan is a float, pandas may interpret the column to have dtype float. However, you can always set explicitly the type back to int using astype df.col.replace(0, np.nan).bfill().astype(int) 0 1 1 2 2 3 3 5 4 5 5 6 6 7 7 9 8 9
downvote count: 0
has comment: http://stackoverflow.com/comment/90085257
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90085127
answers question: http://stackoverflow.com/q/51558647

http://stackoverflow.com/q/51518172
has title: python findall() method does not recognize regular expression with (){}
has body: I am learning the findall() method in the regular expression section. I have a problem which I did not find the solution and explanation. The findall() method does not recognize the regular expression pattern correctly or as I expected when I used {} to specify the number of the string for matching. To be explicity, I take the example from the book. Here is the code: import re haRegex = re.compile(r'(Ha){3}') mo = haRegex.findall('HaHaHaHaHaHa') when I run the script, I got this: ['Ha', 'Ha'] However, when I replaced (Ha){3} with HaHaHa, I got ['HaHaHa', 'HaHaHa'] which is I expected from the first script. Besides, the pattern worked perfectly with search() method. I got 'HaHaHa' with group() method. Anyone knows what happened?
type: Question
duplicate of: http://stackoverflow.com/q/31915018
score: 0
tagged with: findall
tagged with: regex
tagged with: pattern-matching
answer count: 0
has comment: http://stackoverflow.com/comment/90004839
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90396122
linked to: http://stackoverflow.com/q/31915018

http://stackoverflow.com/comment/90076859
type: QuestionComment
has text: why are you `deepcopy`ing pattern?
comment on: http://stackoverflow.com/q/51544483
score: 0
type: Comment

http://stackoverflow.com/a/51551939
has comment: http://stackoverflow.com/comment/90088474
type: Answer
answers question: http://stackoverflow.com/q/51542959
score: 0
has comment: http://stackoverflow.com/comment/90080031
has body: try this command: scrapy crawl &lt;spider name&gt; -o file.csv -t csv

http://stackoverflow.com/comment/90070358
type: Comment
type: QuestionComment
score: 0
has text: Also, even ignoring the `"` typo, this code won't run, and it's not clear how it's _supposed_ to work. Your `Person.__init__` doesn't have any of those variables that it's trying to pass to `super().__init__`, and then it tries to use `id`, which it also doesn't have as a variable. And then, for good measure, you call the constructors with the wrong number of arguments.
comment on: http://stackoverflow.com/q/51551588

http://stackoverflow.com/comment/90167326
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51586711
score: 0
has text: Thanks everyone for your help. I understand the problem a little better now, but I still don't have a solution.

http://stackoverflow.com/comment/90163598
type: Comment
type: AnswerComment
has text: much better. The reason why `map` doesn't work as a sort key is that it returns a generator function, not the expected list. So it doesn't work in python 3 to provide a list key
score: 0
comment on: http://stackoverflow.com/a/51597741

http://stackoverflow.com/comment/90188975
score: 0
type: AnswerComment
type: Comment
has text: I use Sqlite driver. I tried to use `getvalue()` instead of `getbuffer()`, but it does not help. I have no issues with other datasets. I can store them in DB and extract them to the files. But I have one datasets which cause problems, probably because of size. Any ideas how to solve this issue?
comment on: http://stackoverflow.com/a/51601055

http://stackoverflow.com/q/51536179
has answer: http://stackoverflow.com/a/51536219
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51536729
accepted answer: http://stackoverflow.com/a/51536729
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/90040324
has title: Weird thing about JSON content output in python
answer count: 3
score: 0
has body: Forgive me here if this has already been asked. I am seeing some weird results from a simple python code snippet: import json ''' copy contents of one json file into another ''' with open('./new_file.json', 'w') as f1: with open('./old_file.json') as f2: data = json.load(f2) json.dump(data, f1) The code snippet above copies contents of one json file into the other. The original file does not have pretty formatting (i.e content is all on one line) After running the code, I then do the following: $ diff -q new_file.json old_file.json Files new_file.json and old_file.json differ The file contents apparently are different which is strange. I then tried to do: $ cat new_file.json | python -m json.tool &gt; foo $ cat old_file.json | python -m json.tool &gt; bar And then when I do compare the files bar and foo, I get: :~/$ diff -q foo bar :~/$ Which shows that the resulting content after formatting are the same. Is there any explanation for this? Thanks in advance.
tagged with: python
tagged with: diff
tagged with: file
has answer: http://stackoverflow.com/a/51536715
possible better answer: http://stackoverflow.com/a/51536219
type: Question

http://stackoverflow.com/a/51572285
has comment: http://stackoverflow.com/comment/90111102
answers question: http://stackoverflow.com/q/51572176
has comment: http://stackoverflow.com/comment/90111109
downvote count: 0
score: 1
type: Answer
upvote count: 1
has body: Instead of doing the previous if statement, you can simply look at what has been previously put into the c3 list (as that is a result of the previous if statement). Here is an example of how you can achieve this in python: c1 = ["Buy", "nan", "nan", "nan", "Buy", "nan", "nan", "nan", "nan", "Buy", "nan"] c2 = ["nan", "nan", "Sell", "nan", "nan", "Sell", "Sell", "nan", "nan", "nan", "Sell"] c3 = [] for index in range(len(c1)): if c1[index] == "Buy": c3.append("Buy") elif c2[index] == "Sell": c3.append("Sell") elif c1[index] == "nan" and c2[index] == "nan": # Implied if reached this point (so else would also suffice here) c3.append(c3[index-1]) # look at previous result in list print(c3) Output: ['Buy', 'Buy', 'Sell', 'Sell', 'Buy', 'Sell', 'Sell', 'Sell', 'Sell', 'Buy', 'Sell']

http://stackoverflow.com/q/51621752
type: UnansweredQuestion
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/90209101
has body: I am executing Python script in PHP which is working fine. I am getting the output of Python script on my webpage. But the problem is that I created a variable in PHP which has the same value as the result of Python code but when I'm comparing both it is showing not equal. Python: if(results==[True]): print("picture matched") Result: picture matched PHP: $output = shell_exec("python check.py"); var_dump($output); $out = "picture matched"; var_dump($out); if($output == $out) { echo "match"; } else { echo "not"; } Result: string (16) "picture matched " string (16) "picture matched " not I don't know why it's showing not, it should show match because both have the same type, value, and characters.
has comment: http://stackoverflow.com/comment/90209162
downvote count: 3
has comment: http://stackoverflow.com/comment/90209895
upvote count: 1
has title: Script executing
has comment: http://stackoverflow.com/comment/90210075
has comment: http://stackoverflow.com/comment/90209135
type: Question
score: -2
has answer: http://stackoverflow.com/a/51621864
has comment: http://stackoverflow.com/comment/90209102
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/51622229

http://stackoverflow.com/q/51562651
has title: Python : mock an attribute or mock the whole class?
type: Question
has body: I am trying to mock the Popen instance in the following business code: process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) output = process.communicate()[0] if process.returncode != 0: This is my test code setup: @mock.patch('subprocess.Popen.returncode') @mock.patch('subprocess.Popen.communicate') def testCommandExecutesCommunicate(self, mock_popen_communicate, mock_popen_returncode): I have also tried: @mock.patch('subprocess.Popen.returncode') @mock.patch('subprocess.Popen.communicate') def testCommandExecutesCommunicate(self, mock_popen_communicate, mock_popen_returncode): In both situations, I get an error with returncode mocking Error Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 329, in run testMethod() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mock/mock.py", line 1297, in patched arg = patching.__enter__() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mock/mock.py", line 1369, in __enter__ original, local = self.get_original() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mock/mock.py", line 1343, in get_original "%s does not have the attribute %r" % (target, name) AttributeError: &lt;class 'subprocess.Popen'&gt; does not have the attribute 'returncode' How should I mock out Popen? Should I mock out the Popen class somehow? Or am I on the right track by mocking out the methods + attributes?
tagged with: mocking
has comment: http://stackoverflow.com/comment/90092128
downvote count: 0
has answer: http://stackoverflow.com/a/51566217
answer count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90092366
has comment: http://stackoverflow.com/comment/90092228
type: UnansweredQuestion
upvote count: 1
tagged with: unit-testing
score: 1

http://stackoverflow.com/comment/90224159
has text: This depends very much on how you manage your memory in C++. As I mentioned in my answer (which is apparently not worth an upvote) you can also return a copy of the C++ memory to Python. Then Python will run the destructor on its owned memory and you don't have to worry about it.
comment on: http://stackoverflow.com/a/51614104
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51563503
has body: I know I am probably going about this the wrong way. But i am trying to figure out what resource URL's in our proxy server config are broken or redirecting to a different URL than what we have on file. An example of a resource being passed into out proxy prefix URL is: https://login.proxy.library.ohio.edu/login?auth=ou&amp;url=https://www.whatismyip.com/ When this URL is resolved it should redirect to the proxied link https://www-whatismyip-com.proxy.library.ohio.edu/ What I am wanting is to get the final status code of the final URL after it is resolved and redirected What I have code wise, just a snippet... proxy_url = "https://login.proxy.library.ohio.edu/login?auth=ou&amp;url=https://www.whatismyip.com/" conn = requests.head(proxy_url, allow_redirects=True) print conn.url[:-3] The [:-3] is to remove some weird unwanted characters at the end of the string. However it is only returning the original link I am passing it. How can I get the correct proxied URL after it's resolved and redirects.
tagged with: proxy
score: 0
answer count: 1
has title: Python Requests getting final link
has answer: http://stackoverflow.com/a/51563677
type: UnansweredQuestion
tagged with: python
tagged with: python-requests
type: Question

http://stackoverflow.com/comment/90119498
comment on: http://stackoverflow.com/q/51576453
score: 0
type: Comment
type: QuestionComment
has text: I don't know too well how django works but at a first glance yes, it's something similar. Basically creating some boilerplate functionality and configuration

http://stackoverflow.com/a/51487773
downvote count: 0
has body: Your problem is that when you iterate over a the list column_names using for i in column_names[1:-2], the value of i will be the element in the list (not the corresponding index). In your case, one simple thing would be to use enumerate, as shown in the following example: column_names = ["a", "b", "c", "d", "e"] for i, val in enumerate(column_names[1:-2]): column_names[i+1] += '_Vol_Adj' print(column_names) #['a', 'b_Vol_Adj', 'c_Vol_Adj', 'd', 'e'] I am updating the value at index i+1 inside the loop because we are starting the iteration at index 1. Or you could use range(1, len(column_names)-2) as @Barmar suggested: for i in range(1, len(column_names)-2): column_names[i+1] += '_Vol_Adj'
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51487677
upvote count: 2
has comment: http://stackoverflow.com/comment/89944568

fogbugz-api
tag name: fogbugz-api
tags question: http://stackoverflow.com/q/51498991
type: Tag

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

http://stackoverflow.com/comment/113895422
type: QuestionComment
comment on: http://stackoverflow.com/q/51573592
has text: We discovered a lot of our new features in Spyder 4 are causing severe freezes in the editor. Most of them will be fixed in our next version (4.2.0), to be released in November 2020.
score: 0
type: Comment

http://stackoverflow.com/q/51520784
has comment: http://stackoverflow.com/comment/90010680
possible better answer: http://stackoverflow.com/a/51521132
upvote count: 3
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90011092
has body: The official documentation indicates that python first tries to check via __contains__(), then __iter__(), and finally __getitem__(), depending on which function is defined, in order to resolve an in call. Eg: if y in x: print("y present in x") else: print("y not present in x") The linked documentation indicates that if there exists any non negative index i such that x[i] == y, then the result is True else False. How does it perform a search over all such i? A linear traversal over 'all' positive numbers seems out of the question. There must be some bounds in which the linear traversal happens (for lists, it should be 0 to len()). How are those bounds determined?
has comment: http://stackoverflow.com/comment/90010545
has comment: http://stackoverflow.com/comment/90010910
has comment: http://stackoverflow.com/comment/90010420
has answer: http://stackoverflow.com/a/51521006
type: Question
has comment: http://stackoverflow.com/comment/90011140
has comment: http://stackoverflow.com/comment/90010559
has answer: http://stackoverflow.com/a/51521308
tagged with: membership
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90010466
answer count: 5
has answer: http://stackoverflow.com/a/51521132
score: 3
has title: How does python's `in` function work when it triggers via `__getitem__()`'?
has comment: http://stackoverflow.com/comment/90010837
has answer: http://stackoverflow.com/a/51529373
has answer: http://stackoverflow.com/a/51520963
accepted answer: http://stackoverflow.com/a/51521308
has comment: http://stackoverflow.com/comment/90010603

http://stackoverflow.com/comment/90095561
type: AnswerComment
comment on: http://stackoverflow.com/a/51564139
type: Comment
has text: Would the problem be fixed, if I moved this part to the file that contains those global variables?
score: 0

scripting
tags question: http://stackoverflow.com/q/51584796
tags question: http://stackoverflow.com/q/51522687
tag name: scripting
tags question: http://stackoverflow.com/q/51489236
type: Tag

http://stackoverflow.com/comment/89980509
has text: Note however that this solution is marginally slower than the groupby solution I had (though less clunky) - see performance check in my question's edit.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51503825
type: AnswerComment

http://stackoverflow.com/q/51585914
has answer: http://stackoverflow.com/a/51585947
accepted answer: http://stackoverflow.com/a/51698697
tagged with: python
favorite count: 0
upvote count: 1
tagged with: django
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90137328
score: 1
has title: import views.py from app directory
type: Question
has body: In setting up Django app, I want to import main_app/views.py in the url.py of the main project folder. main_app folder is located parallel to the main project folder. Here is how I am referencing to import views.py in main project folder\url.py: import sys sys.path.append('../main_app') from django.conf.urls import url from django.contrib import admin from django.urls import path from main_app import views urlpatterns = [ path('admin/', admin.site.urls), url(r'^', 'main_app.urls'), ] However, I am receiving ModuleNotFoundError: No module named 'main_app'
downvote count: 0
has answer: http://stackoverflow.com/a/51698697
possible better answer: http://stackoverflow.com/a/51585947
has answer: http://stackoverflow.com/a/51586061
answer count: 3

http://stackoverflow.com/a/51523815
type: Answer
answers question: http://stackoverflow.com/q/51523674
has body: You initialize empty data frame here: variable_step = pd.DataFrame() Assuming your intention is to put list into a data frame, you should: variable_step = pd.DataFrame(start) # or any other list you need Also, you address items by index in the data frame in the last loop to assign values while data frame is empty. Use .append() instead
score: 0

http://stackoverflow.com/q/51600489
downvote count: 0
has title: Why does a request via Python `requests` takes almost seven times longer than in Postman?
has body: I am currently doing a HTTP Post request to a server in Python 2.7 with requests.post() which takes around 700ms. There is also absolutely no proxy server which could cause delays but still I am bypassing any proxies because it seems to be an issue of that library. Nevertheless I was curious about that time because in my opinion it takes very long for an answer with about 230 characters. That is why I tried the same request in Postman. The result was that the request in Postman took less than 100ms! Which is much more appropriate for the task I have to do. It is all about time. I want to know if there is any specific parameter in requests.post() which I have to set or is this function just that slow? The request looks like this currently (very basic stuff): req = requests.post(url, json={"Username": username, "Password": password, "TerminalNo": terminalno)}) json = req.json() Header from the server if needed: cache-control →private content-length →228 content-type →application/json; charset=utf-8 date →Mon, 30 Jul 2018 17:58:05 GMT server →Microsoft-IIS/7.5 x-aspnet-version →2.0.50727 x-powered-by →ASP.NET
tagged with: http-post
has answer: http://stackoverflow.com/a/78111200
linked to: http://stackoverflow.com/q/45552540
linked to: http://stackoverflow.com/q/17743212
upvote count: 6
answer count: 4
has answer: http://stackoverflow.com/a/68520033
favorite count: 0
linked to: http://stackoverflow.com/q/62599036
type: UnansweredQuestion
score: 6
tagged with: python
tagged with: python-requests
has answer: http://stackoverflow.com/a/62603843
has comment: http://stackoverflow.com/comment/90167656
has comment: http://stackoverflow.com/comment/90167704
type: Question
has answer: http://stackoverflow.com/a/60843169

http://stackoverflow.com/q/51606692
has body: This is my bash script; # Binarize raster for later polygon creation path=/home/rose/Desktop/test/DSM_BM24_2017_1000_4735.tif pathdir=$(echo $path | cut -d "/" -f 1,2,3,4,5) gdal_calc.py -A $path --outfile=$pathdir/binary.tif --NoDataValue=-9999 --calc "1 * (A != -9999)" # Polygonize raster binary=$pathdir/binary.tif b=$(basename $binary) basebinary=$(echo $b | cut -d "." -f 1) gdal_polygonize.py $binary $pathdir/polygon$basebinary.shp polygon$basebinary # Make EPSG:2193 projection file for polygon ogr2ogr -a_srs EPSG:2193 -f "ESRI Shapefile" /home/rose/Desktop/test/finalpolygonbinary.shp /home/rose/Desktop/test/polygonbinary.shp # Define variable to import to py and postgis script 'pypostgis' polygon='$pathdir/finalpolygon$basebinary.shp' # Call python script python pypostgis.py $polygon This is my python script that is being called in my bash script, which grabs the polygon shapefile and imports it into a table in PgAdmin III; import psycopg2 import qgis.utils import os import sys from qgis.core import * from qgis.core import QgsVectorLayer, QgsVectorLayerImport from qgis.core import QgsDataSourceURI, QgsVectorLayer # import layer into database shp2pgs function def shp2pgs(layer): conn = psycopg2.connect("dbname='rosespace' host='localhost' port = '5432' user='rose' password='postgres' ") cursor = conn.cursor() uri = "dbname='rosespace' host='localhost' port=5432 user='rose' password='postgres' table=\"public\".\"%s\" (geom) sql=" %layer.name().lower() importvector = QgsVectorLayerImport.importLayer(layer, uri, "postgres", layer.crs(), False, False) print importvector # Import and use $polygon variable from bash script for layer, which will eventually be called by the function above shapefile = sys.argv[1] print shapefile basename_shp = (os.path.splitext(os.path.basename(shapefile))[0]).lower() layer = QgsVectorLayer(shapefile, basename_shp, 'ogr') #Call function with shapefile variable - layer, originally from above bash script shp2pgs(layer) When I ran the bash …
has comment: http://stackoverflow.com/comment/90211153
type: Question
has title: Python 2.7, PgAdmin III & BASH 4.3.48: Error Invalid Provider when running py script inside bash script
tagged with: python
has comment: http://stackoverflow.com/comment/90179669
score: 0
has comment: http://stackoverflow.com/comment/90208999
answer count: 0
type: UnansweredQuestion
tagged with: pgadmin
tagged with: gdal
tagged with: bash

http://stackoverflow.com/comment/90059897
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51545986
score: 0
has text: @abarnert Afraid not. The most relevant answer I found is the one down v there v :)

http://stackoverflow.com/comment/110050897
comment on: http://stackoverflow.com/a/52242947
score: 5
type: AnswerComment
type: Comment
has text: Like that, you will not get the output instantly ! so you've to wait until the full progress completed till you see the full result !

http://stackoverflow.com/a/51521235
downvote count: 1
has body: Python seems to interpret 0xbin() as 0xb in (), meaning is eleven in an empty tuple. The answer is no, therefore False.
has comment: http://stackoverflow.com/comment/90051731
has comment: http://stackoverflow.com/comment/90015977
has comment: http://stackoverflow.com/comment/90011699
has comment: http://stackoverflow.com/comment/90048440
type: Answer
upvote count: 232
answers question: http://stackoverflow.com/q/51521158
has comment: http://stackoverflow.com/comment/90011660
has comment: http://stackoverflow.com/comment/90064245
accepted answer of: http://stackoverflow.com/q/51521158
has comment: http://stackoverflow.com/comment/90011362
score: 231
has comment: http://stackoverflow.com/comment/90019738
has comment: http://stackoverflow.com/comment/90026539
has comment: http://stackoverflow.com/comment/90035117
type: AcceptedAnswer

opencv
tags question: http://stackoverflow.com/q/51532845
tags question: http://stackoverflow.com/q/51594822
tags question: http://stackoverflow.com/q/51531870
type: Tag
tags question: http://stackoverflow.com/q/51491771
tags question: http://stackoverflow.com/q/51582034
tags question: http://stackoverflow.com/q/51614092
tags question: http://stackoverflow.com/q/51557176
tags question: http://stackoverflow.com/q/51542807
tags question: http://stackoverflow.com/q/51629238
tags question: http://stackoverflow.com/q/51553493
tags question: http://stackoverflow.com/q/51606215
tags question: http://stackoverflow.com/q/51606818
tags question: http://stackoverflow.com/q/51594411
tags question: http://stackoverflow.com/q/51553928
tags question: http://stackoverflow.com/q/51625724
tags question: http://stackoverflow.com/q/51616160
tags question: http://stackoverflow.com/q/51504806
tags question: http://stackoverflow.com/q/51493545
tags question: http://stackoverflow.com/q/51485839
tags question: http://stackoverflow.com/q/51485185
tags question: http://stackoverflow.com/q/51621684
tags question: http://stackoverflow.com/q/51587321
tags question: http://stackoverflow.com/q/51568501
tags question: http://stackoverflow.com/q/51527688
tags question: http://stackoverflow.com/q/51517182
tags question: http://stackoverflow.com/q/51625716
tags question: http://stackoverflow.com/q/51539706
tags question: http://stackoverflow.com/q/51624496
tags question: http://stackoverflow.com/q/51605934
tags question: http://stackoverflow.com/q/51626749
tags question: http://stackoverflow.com/q/51535027
tags question: http://stackoverflow.com/q/51584560
tags question: http://stackoverflow.com/q/51544855
tags question: http://stackoverflow.com/q/51578659
tags question: http://stackoverflow.com/q/51593390
tags question: http://stackoverflow.com/q/51626213
tags question: http://stackoverflow.com/q/51618576
tags question: http://stackoverflow.com/q/51544330
tags question: http://stackoverflow.com/q/51569216
tags question: http://stackoverflow.com/q/51517235
tag name: opencv
tags question: http://stackoverflow.com/q/51523765
tags question: http://stackoverflow.com/q/51636588
tags question: http://stackoverflow.com/q/51570207
tags question: http://stackoverflow.com/q/51578631
tags question: http://stackoverflow.com/q/51488275
tags question: http://stackoverflow.com/q/51602100
tags question: http://stackoverflow.com/q/51599456
tags question: http://stackoverflow.com/q/51485285
tags question: http://stackoverflow.com/q/51496728
tags question: http://stackoverflow.com/q/51637031
tags question: http://stackoverflow.com/q/51541754
tags question: http://stackoverflow.com/q/51604394
tags question: http://stackoverflow.com/q/51559640
tags question: http://stackoverflow.com/q/51584562
tags question: http://stackoverflow.com/q/51632623
tags question: http://stackoverflow.com/q/51489792
tags question: http://stackoverflow.com/q/51560541
tags question: http://stackoverflow.com/q/51485494
tags question: http://stackoverflow.com/q/51573652
tags question: http://stackoverflow.com/q/51607038
tags question: http://stackoverflow.com/q/51522350
tags question: http://stackoverflow.com/q/51560539
tags question: http://stackoverflow.com/q/51502837
tags question: http://stackoverflow.com/q/51498510
tags question: http://stackoverflow.com/q/51531414
tags question: http://stackoverflow.com/q/51588683
tags question: http://stackoverflow.com/q/51606048
tags question: http://stackoverflow.com/q/51628313
tags question: http://stackoverflow.com/q/51546787
tags question: http://stackoverflow.com/q/51541385
tags question: http://stackoverflow.com/q/51492385
tags question: http://stackoverflow.com/q/51579469
tags question: http://stackoverflow.com/q/51576642
tags question: http://stackoverflow.com/q/51490371
tags question: http://stackoverflow.com/q/51503664
tags question: http://stackoverflow.com/q/51610855
tags question: http://stackoverflow.com/q/51486639
tags question: http://stackoverflow.com/q/51628357

http://stackoverflow.com/comment/90069421
type: Comment
type: QuestionComment
has text: Maybe cross-post to https://stats.stackexchange.com/questions/tagged/copula? Your question begs for proper answer!
comment on: http://stackoverflow.com/q/51536478
score: 0

http://stackoverflow.com/q/51503609
tagged with: python
has body: I need to install pyspark for anaconda. My machine does not have internet connection hence, this wont work. It times out. ./conda install -c conda-forge pyspark I also tried ./conda install --offline &lt;psyapark.tar&gt; it tries to go to the internet. I dont get this I have the the source file: pyspark-2.3.1.tar How can I install this tar file under anaconda?
type: UnansweredQuestion
type: Question
tagged with: anaconda
tagged with: pyspark
has answer: http://stackoverflow.com/a/51503768
has title: how do you install pyspark from tar file for anaconda distribution?
answer count: 1
score: 0
linked to: http://stackoverflow.com/q/45156080

http://stackoverflow.com/q/51536641
score: 1
accepted answer: http://stackoverflow.com/a/51536772
upvote count: 1
has answer: http://stackoverflow.com/a/51536962
type: Question
has body: I have a dataframe like this: col1 x y z A yes no yes B no no yes C no yes no D yes no yes E no no yes F yes yes no I would like to select data like this, If my criteria is to find all yes for A, I should get [x,z], ie the values for A which ever is yes If B, [z] C should give [y] What to do?
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/51536719
has answer: http://stackoverflow.com/a/51536719
tagged with: pandas
has title: How to fetch a column header if a particular condition is met based on row and column value of the dataframe?
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51536772
has answer: http://stackoverflow.com/a/51536794
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/90229573
has text: It fails on a line as ' printf("%s","/*non comment*/"); #non comment '
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51622212
type: Comment

http://stackoverflow.com/comment/90238252
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51622212
type: AnswerComment
has text: @kantal it would fail in that case, but that's incredibly specific and if I had to bet that they didn't have any strings containing /* */ then that's a bet I'd gladly take.

http://stackoverflow.com/comment/89990324
type: QuestionComment
has text: This reminds me of the classic `{True: 'yes', 1: 'no', 1.0: 'maybe'}` which evaluates to `{True: 'maybe'}` because `bool` is a subclass of `int` with values `0` and `1`, which means that `True` & `False` hash to the same dictionary or set keys and are therefore "identical" to their integer values in terms of set membership.
comment on: http://stackoverflow.com/q/51505826
score: 0
type: Comment

http://stackoverflow.com/q/51544042
tagged with: generator
type: AnsweredQuestion
score: 2
upvote count: 2
has title: Loading bar in flask using stream_with_context on google app engine flexible environment
type: Question
linked to: http://stackoverflow.com/q/9240597
tagged with: flask
has answer: http://stackoverflow.com/a/51598272
has body: Use case - some user data is getting loaded in the backend (flask), and the progress is shown on the frontend through a loading bar. The backend has a generator which loads the data and keeps yielding the progress (this generator is returned as a response using stream_with_context). The frontend queries the flask view using a javascript EventSource object. Code: @app.route("/progress", methods=['GET']) def progress(): gen = get_user_data() return Response(stream_with_context(gen), mimetype= 'text/event-stream') def get_user_data(): n = 100 (number of data points to be loaded) for i in range(1,n+1): #load data yield "data:" + str((float(i)/(n))*100) + "\n\n" yield "data:" + "close" + "\n\n" This works fine on my local environment. However, when I deploy it on google app engine flexible environment, the loading bar goes directly from 0 to 100. That is, instead of the front end getting updates each time my generator yields, I'm getting all the EventSource messages at once (when the generator has finished execution). My app.yaml: runtime: python env: flex entrypoint: gunicorn --timeout 240 -b :$PORT app:app runtime_config: python_version: 2 manual_scaling: instances: 1 resources: cpu: 1 memory_gb: 0.5 disk_size_gb: 10 Any idea on how I can get this to work on google app engine?
answer count: 1
downvote count: 0
favorite count: 0
tagged with: gunicorn
tagged with: google-app-engine
tagged with: python
accepted answer: http://stackoverflow.com/a/51598272

http://stackoverflow.com/comment/90047622
type: AnswerComment
comment on: http://stackoverflow.com/a/51539463
type: Comment
has text: You can skip the `parallelize` part: `df = sqlContext.createDataFrame(l, ["First_Name", "Last_Name", "Age"])`. Also see this [related post.](https://stackoverflow.com/questions/48745029/create-single-row-dataframe-from-list-of-list-pyspark/48750921#48750921)
score: 2

http://stackoverflow.com/comment/90087615
has text: Which torch.nn.Conv2d's are you referring to?
comment on: http://stackoverflow.com/q/51549461
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90113865
score: 0
has text: @Hexer: Oh, so it's already x86. You might be able to adapt one of the existing open-source superoptimizers more easily than writing your own from scratch. I wasn't suggesting you could just *use* an existing program unmodified, although it's closer than I was imagining. You might also want to look at [Applying Genetic Programming to Bytecode and Assembly](https://digitalcommons.morris.umn.edu/cgi/viewcontent.cgi?article=1013&context=horizons), an academic paper from 2014.
type: AnswerComment
comment on: http://stackoverflow.com/a/51567822
type: Comment

http://stackoverflow.com/q/51610959
has answer: http://stackoverflow.com/a/51616635
answer count: 3
accepted answer: http://stackoverflow.com/a/51611787
tagged with: python
has body: So I'm trying to write a custom encoder that handles different numpy values: class NumpyEncoder(DjangoJSONEncoder): def default(self, obj): if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return obj.tolist() if np.isnan(obj) or np.isinf(obj): return None else: return super().default(obj) However, it doesn't appear to be handling np.NaN or np.inf objects: obj = {'test': np.NaN, 'test2': np.inf} json.dumps(obj, cls=LazyNumpyEncoder) Out[5]: '{"test": NaN, "test2": Infinity}' I've also tried using elif isinstance(obj, np.nan):, but that hasn't worked either. What I want is my NaN and Infinite (including negative infinite values) to be turned into nulls. Anyone know where I've gone wrong?
has comment: http://stackoverflow.com/comment/90187621
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/90188122
type: Question
has answer: http://stackoverflow.com/a/71338100
score: 3
has comment: http://stackoverflow.com/comment/90187893
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51611787
tagged with: python-3.6
tagged with: numpy
has title: Python custom JSON encoder isn't handling numpy NaN or Infinite values
downvote count: 0
possible better answer: http://stackoverflow.com/a/51616635
favorite count: 0

http://stackoverflow.com/q/51502943
has body: So if I have 3 dictionaries: dictionary = {'id':879, 'data':{'price': 18.90, 'location':'london', 'zipcode':'ha30ds'}} dictionary2 = {'id':871, 'data':{'price': 24.00, 'location':'paris', 'zipcode':'nw93uo'}} dictionary3 = {'id':873, 'data':{'price': 17.00, 'paris':'london', 'zipcode':'nw34kh'}} and put them in a list: list = [dictionary,dictionary2,dictionary3] where list[0]['data']['price'] == 18.90 I want to sort this list of dictionaries by price.... I tried this: newlist = sorted(list, key=['lambda'] k: k['data']['price']) but this doesn't work....any ideas?
has comment: http://stackoverflow.com/comment/89974393
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89974778
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/13237941
has title: I want to know how to sort a list of dictionaries, where the dictionary has a dictionary within it
duplicate of: http://stackoverflow.com/q/13237941
type: Question
score: 0
tagged with: sorting

http://stackoverflow.com/q/51584415
score: 4
tagged with: list
accepted answer: http://stackoverflow.com/a/51584456
has answer: http://stackoverflow.com/a/51584530
upvote count: 4
has title: How to combine every 5 lists inside of a list in python?
has answer: http://stackoverflow.com/a/51584479
downvote count: 0
has answer: http://stackoverflow.com/a/51584464
tagged with: iteration
possible better answer: http://stackoverflow.com/a/51584479
type: Question
type: AnsweredQuestion
has body: I have a large list of lists, for example: list = [['a'], ['b'], ['c'], ['1234'], ['d'], ['e'], ['g'], ['h'], ['i'], ['56']] I would like to combine every 5 lists into one list of elements and so on. I am having total of 150995 lists inside a list. Expected output: new_list = [['a' , 'b', 'c', '1234', 'd'], ['e', 'g', 'h', 'i', '56']] I tried with below code. but it is flattens to one list. list(zip(*list)[0]) How can I do this?
has answer: http://stackoverflow.com/a/51584456
has answer: http://stackoverflow.com/a/51584555
has comment: http://stackoverflow.com/comment/90134273
tagged with: append
favorite count: 0
has answer: http://stackoverflow.com/a/51584561
has answer: http://stackoverflow.com/a/51584462
tagged with: python
answer count: 7

http://stackoverflow.com/comment/90051516
type: QuestionComment
comment on: http://stackoverflow.com/q/51541433
has text: i think your question would get more attention if you added the expected output, & removed columns from `df1` & `df2` that are not involved in this join.
score: 2
type: Comment

http://stackoverflow.com/a/51616348
upvote count: 1
answers question: http://stackoverflow.com/q/51615965
type: AcceptedAnswer
has body: a) G.subgraph(A).edges() b) [(i,j) for i,j in G.edges() if i in A and j not in A] c) [(i,j) for i,j in G.edges() if i not in A and j in A] If you want their union, try the following: G.edges()-G.subgraph(G.nodes()-A).edges()
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51615965

http://stackoverflow.com/a/53657012
upvote count: 1
has body: Another example is useful when you want to have one of name from keyword.kwlist, e.g. class Emails(models.Model): from_ = models.CharField(name='from', ...) # workaround to have `.from` field to = models.CharField(...) content = models.TextField(...) since initially it will forbid to set field with name to from with exception: SyntaxError: invalid syntax
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51514315
score: 1

http://stackoverflow.com/comment/90121627
score: 0
type: QuestionComment
has text: Style guide (aka formatting): https://www.python.org/dev/peps/pep-0008/
type: Comment
comment on: http://stackoverflow.com/q/51577957

http://stackoverflow.com/comment/90136702
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51578449
type: Comment
has text: Not work so well, the problem still there, I wonder if it is a bug of vscode X(

datetime
tags question: http://stackoverflow.com/q/51578419
tags question: http://stackoverflow.com/q/51628241
tags question: http://stackoverflow.com/q/51539728
tags question: http://stackoverflow.com/q/51622485
tags question: http://stackoverflow.com/q/51637621
tags question: http://stackoverflow.com/q/51619615
tags question: http://stackoverflow.com/q/51524285
tags question: http://stackoverflow.com/q/51569968
tags question: http://stackoverflow.com/q/51575485
tags question: http://stackoverflow.com/q/51526392
tags question: http://stackoverflow.com/q/51509741
tags question: http://stackoverflow.com/q/51552012
tags question: http://stackoverflow.com/q/51522500
tags question: http://stackoverflow.com/q/51484983
tags question: http://stackoverflow.com/q/51488454
tags question: http://stackoverflow.com/q/51600841
tags question: http://stackoverflow.com/q/51544078
tags question: http://stackoverflow.com/q/51542167
tags question: http://stackoverflow.com/q/51557329
tags question: http://stackoverflow.com/q/51486751
tags question: http://stackoverflow.com/q/51527011
tags question: http://stackoverflow.com/q/51631248
tags question: http://stackoverflow.com/q/51572059
tags question: http://stackoverflow.com/q/51526090
tags question: http://stackoverflow.com/q/51494857
tags question: http://stackoverflow.com/q/51600075
tags question: http://stackoverflow.com/q/51505025
tags question: http://stackoverflow.com/q/51571615
tags question: http://stackoverflow.com/q/51587468
tags question: http://stackoverflow.com/q/51600355
tags question: http://stackoverflow.com/q/51625243
tag name: datetime
tags question: http://stackoverflow.com/q/51506897
tags question: http://stackoverflow.com/q/51598727
tags question: http://stackoverflow.com/q/51579951
tags question: http://stackoverflow.com/q/51606524
tags question: http://stackoverflow.com/q/51636583
type: Tag
tags question: http://stackoverflow.com/q/51491893
tags question: http://stackoverflow.com/q/51512416
tags question: http://stackoverflow.com/q/51547064
tags question: http://stackoverflow.com/q/51603690
tags question: http://stackoverflow.com/q/51580548
tags question: http://stackoverflow.com/q/51522291
tags question: http://stackoverflow.com/q/51617578
tags question: http://stackoverflow.com/q/51528367
tags question: http://stackoverflow.com/q/51611137
tags question: http://stackoverflow.com/q/51581663

http://stackoverflow.com/q/51502602
score: 0
accepted answer: http://stackoverflow.com/a/51502930
tagged with: pandas
tagged with: python
has body: I'm trying to convert SPSS timestamps to human readable timestamps such as data['Completion_date'] = pd.to_datetime( data['Completion_date']/86400, unit='D', origin=pd.Timestamp("1582-10-14")) but get Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "pandas/_libs/tslibs/timestamps.pyx", line 644, in pandas._libs.tslibs.timestamps.Timestamp.__new__ File "pandas/_libs/tslibs/conversion.pyx", line 275, in pandas._libs.tslibs.conversion.convert_to_tsobject File "pandas/_libs/tslibs/conversion.pyx", line 470, in pandas._libs.tslibs.conversion.convert_str_to_tsobject File "pandas/_libs/tslibs/conversion.pyx", line 439, in pandas._libs.tslibs.conversion.convert_str_to_tsobject File "pandas/_libs/tslibs/np_datetime.pyx", line 121, in pandas._libs.tslibs.np_datetime.check_dts_bounds pandas._libs.tslibs.np_datetime.OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1582-10-14 00:00:00 Example: 13725072000 should convert to 2017-09-18 Dates in SPSS are recorded in seconds since October 14, 1582, the date of the beginning of the Julian calendar. How else would I do it?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51502930
tagged with: dataframe
has title: Convert 'seconds since October 14, 1582' to Python datetime
type: Question
has comment: http://stackoverflow.com/comment/89973790
answer count: 2
possible better answer: http://stackoverflow.com/a/69834924
has answer: http://stackoverflow.com/a/69834924

http://stackoverflow.com/a/51511208
accepted answer of: http://stackoverflow.com/q/51510616
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51510616
has body: # -*- coding: utf-8 -*- from distutils.core import setup setup( name = "zeus", version = "0.1", author = "yourname", author_email = "youraddress@xyz.com", description = ("A simple and easy to use Machine Learning Library."), license = "GPL-2,0", packages=['zeus', 'zeus.tree', 'zeus.linear_regressors'], install_requires=['numpy'], zip_safe=False ) Your packaging didn't include the sub modules which is causing the import error. The changed line is: packages=['zeus', 'zeus.tree', 'zeus.linear_regressors'] Instead you only had: packages=['zeus']
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51535939
score: 0
type: Answer
has body: Regarding your examples your input sequence is just (x 2x 3x) etc. This is not a problem for recurrent neural networks. You want to learn a calculation policy, not long term dependecies in features. RNNs are very powerful and can find very complex pattern, but for this they are not the right tool. To solve such a problem you can take a look at evolutionary algorithms.
answers question: http://stackoverflow.com/q/51524005

http://stackoverflow.com/comment/89949377
type: Comment
type: QuestionComment
has text: yeah i began to know. actually i want to do two steps: 1) creating new urls from the list 2) scraping the data from new urls
comment on: http://stackoverflow.com/q/51490114
score: 0

http://stackoverflow.com/comment/90025932
has text: You can use `urrlib`: https://stackoverflow.com/a/22776/3275464
comment on: http://stackoverflow.com/q/51528727
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90098703
type: Comment
has text: df.fillna(0) works fine!!
score: 0
comment on: http://stackoverflow.com/q/51564790
type: QuestionComment

http://stackoverflow.com/comment/90142429
has text: But the problem is that systemd alone behaves correctly. The difficulty is to have this running from Ansible (i.e. block forever or no showing the failures). If you have a solution how to solve this with Ansible, you can post an answer. Like that, thinking you know everything, you might block others from giving/receiving answers. Cheers!
type: Comment
comment on: http://stackoverflow.com/q/51583624
score: 0
type: QuestionComment

http://stackoverflow.com/a/62510480
has body: Update your Gunicorn version and change the version number in your requirements.txt. Then try re-uploading your project. I was using version 0.16.1 and updating to the current version solved this exact problem for me.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51507757

http://stackoverflow.com/comment/90238738
comment on: http://stackoverflow.com/q/51635541
type: Comment
score: 0
has text: You should consider sharing some code of how you are currently getting the progress of svn and how you call svn.
type: QuestionComment

http://stackoverflow.com/q/51557646
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51557944
has body: I have an excel-file that is roughly 1000 rows and 25 columns wide. What I want to do is to create a script that looks through the excel-file based on an user input. (names in this case) My current code goes as following: import xlrd file_location =r"C:\Users\extoskben\Desktop\Datorer.xlsx" workbook = xlrd.open_workbook(file_location) sheet = workbook.sheet_by_index(0) User = input("What's the users name?: ") I want the code to read from the excel-file and print the result from all columns based on the name it matches with. EDIT: Structure of the excel file : [Name ] [x] [x] [x] [Serialnumber] [x] [x] [ Model ] [1] Oskar Beneke x x x 123456789 x x Thinkpad t470 [2] Example name x x x 987654321 x x Thinkpad t470s I would like to know how I can print out the results from only the Rows 1 5 and 8 and leave the "X's" out from my print.
tagged with: xlrd
has comment: http://stackoverflow.com/comment/90083906
score: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51557944
tagged with: python
has comment: http://stackoverflow.com/comment/90083775
has title: Using XLRD module to search for a string on imported excel-file
favorite count: 0
has comment: http://stackoverflow.com/comment/90082038
has comment: http://stackoverflow.com/comment/90082450
upvote count: 2
tagged with: excel

super
tags question: http://stackoverflow.com/q/51609471
tag name: super
type: Tag
tags question: http://stackoverflow.com/q/51540486

http://stackoverflow.com/q/51631329
downvote count: 2
has answer: http://stackoverflow.com/a/51637663
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90227469
has title: How to transfer a random value from one element to another?
has comment: http://stackoverflow.com/comment/90226813
has comment: http://stackoverflow.com/comment/90227969
has comment: http://stackoverflow.com/comment/90226818
type: Question
accepted answer: http://stackoverflow.com/a/51637663
answer count: 1
score: -1
has comment: http://stackoverflow.com/comment/90227654
has comment: http://stackoverflow.com/comment/90228317
favorite count: 0
has comment: http://stackoverflow.com/comment/90226968
has body: I want to create a list of 10,000 elements, and each of them transfers a value to another randomly selected element and repeat for 100,000 times (or more). The distribution of the transferred value can be assigned (e.g. normal or log-normal etc). What I can think of is using a loop and assign another list to save the transfer values. Considering the time of running might be very long, is there a way to finish this efficiently? for example: 1. Initial state: x = [5, 5, 5, 5, 5] 2. All the elements randomly decrease by a number: x = [4, 3, 4, 1, 2] 3. I will create another list, x2, to save the changes, this values will be assigned to the elements (but not the exact element this value come from, e.g. x2[0] will never be assigned to x[0]) in x randomly: x2 = [1, 2, 1, 4, 3] 4. Finally I might get: x = [7, 7, 7, 2, 2] x2[1] and x2[2] added to x[0], x2[3] to x[1], x2[4] to x[2], x2[0] to x[3] and nothing happened for x[4] (this is an example as all things are random). My current code is shown as below, with fixed values and I cannot exclude x[i] in the selection process. import random x = [5]*5 x2 = [] # Change the values in list x, and create list x2 to store the changes. for i in range(len(x)): rand_i = random.randint(1,4) x[i] = x[i]-rand_i x2 = x2+[rand_i] # Randomly add values in list x2 to elements in list x. # Do not add x2[i] to x[i]. for i in range(len(x2)): ii = random.randrange(len(x2)) x[ii] = float(x[ii]) + float(x2[i]) print(sorted(x))
has comment: http://stackoverflow.com/comment/90235569

http://stackoverflow.com/comment/90011862
has text: its not an error this is the output <function __main__.Square.area> @joerobot
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51483639

http://stackoverflow.com/q/51531910
tagged with: testing
has body: I'm trying to import the unit test from a __init__.py file. Hence I'm getting the error ImportError: cannot import name 'Testcase' from 'unittest' Clarify me if I'm wrong.
score: 1
has comment: http://stackoverflow.com/comment/90031601
has answer: http://stackoverflow.com/a/56634740
has answer: http://stackoverflow.com/a/51532774
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90031543
tagged with: python
has title: ImportError: cannot import name 'Testcase' from 'unittest'
type: UnansweredQuestion
upvote count: 1
type: Question

http://stackoverflow.com/q/51584906
has answer: http://stackoverflow.com/a/71888717
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51584935
type: Question
accepted answer: http://stackoverflow.com/a/51584935
score: 18
has comment: http://stackoverflow.com/comment/107029427
upvote count: 18
has body: df1 = pd.DataFrame(np.arange(15).reshape(5,3)) df1.iloc[:4,1] = np.nan df1.iloc[:2,2] = np.nan df1.dropna(thresh=1 ,axis=1) It seems that no nan value has been deleted. 0 1 2 0 0 NaN NaN 1 3 NaN NaN 2 6 NaN 8.0 3 9 NaN 11.0 4 12 13.0 14.0 if i run df1.dropna(thresh=2,axis=1) why it gives the following? 0 2 0 0 NaN 1 3 NaN 2 6 8.0 3 9 11.0 4 12 14.0 i just dont understand what thresh is doing here. If a column has more than one nan value, should the column be deleted?
has answer: http://stackoverflow.com/a/70711104
answer count: 3
tagged with: pandas
has title: thresh in dropna for DataFrame in pandas in python
downvote count: 0
possible better answer: http://stackoverflow.com/a/70711104
favorite count: 0
has comment: http://stackoverflow.com/comment/90135423

http://stackoverflow.com/comment/90100899
comment on: http://stackoverflow.com/q/51567058
has text: So for example original file has images/1.jpg|image/2.jpg. After each image goes through the api hosted_url will have the location where the file was uploaded ie., http://new1.jpg. What the script should do is replace 'images/1.jpg' with 'http://new1.jpg' and so on for each file.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90235396
comment on: http://stackoverflow.com/a/51635525
score: 1
type: AnswerComment
type: Comment
has text: You would have to make sure, that `A` is the smallest of the two strings. better use `min(len(A), len(B))` as the stopping value.

http://stackoverflow.com/q/51613505
accepted answer: http://stackoverflow.com/a/51613566
has answer: http://stackoverflow.com/a/51613532
tagged with: dataframe
has title: list the number of rows in dataframe in pandas
duplicate of: http://stackoverflow.com/q/41125138
score: 0
has answer: http://stackoverflow.com/a/51613931
tagged with: python
answer count: 4
type: AnsweredQuestion
has body: I have the following pandas dataframe df= slNo name 1 a 2 b 3 c I want to add a new column as follows slNo name dummy 1 a 1 2 b 2 3 c 3 The code should involve the number of rows in the datafarme and the dummy should be from1 to the no of rows in the dataframe. In R the following is the operation. df['newcolumn']=c(1:nrow(df)) I request someone to guide me. Am unable to find a solution
has answer: http://stackoverflow.com/a/51613566
type: Question
linked to: http://stackoverflow.com/q/41125138
has answer: http://stackoverflow.com/a/51613793
possible better answer: http://stackoverflow.com/a/51613532

terminal
tags question: http://stackoverflow.com/q/51625388
tags question: http://stackoverflow.com/q/51632029
tags question: http://stackoverflow.com/q/51542965
tags question: http://stackoverflow.com/q/51580904
tags question: http://stackoverflow.com/q/51589511
tag name: terminal
tags question: http://stackoverflow.com/q/51523301
tags question: http://stackoverflow.com/q/51628258
type: Tag

http://stackoverflow.com/a/61318502
score: 0
has body: It could be that the problem arises due to a format error at some places in the dataframe. You could try setting the parameter errors="coerce" to avoid converting those entries and setting them to NaT. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html
answers question: http://stackoverflow.com/q/51544078
type: Answer

pyinstaller
tags question: http://stackoverflow.com/q/51558349
tags question: http://stackoverflow.com/q/51488552
type: Tag
tags question: http://stackoverflow.com/q/51614097
tags question: http://stackoverflow.com/q/51489523
tags question: http://stackoverflow.com/q/51547826
tag name: pyinstaller
tags question: http://stackoverflow.com/q/51544246
tags question: http://stackoverflow.com/q/51500699
tags question: http://stackoverflow.com/q/51625233
tags question: http://stackoverflow.com/q/51535558
tags question: http://stackoverflow.com/q/51516128
tags question: http://stackoverflow.com/q/51556733
tags question: http://stackoverflow.com/q/51515471
tags question: http://stackoverflow.com/q/51494470
tags question: http://stackoverflow.com/q/51525534

http://stackoverflow.com/comment/89947705
type: Comment
type: QuestionComment
has text: What happens inside those functions? Is it I/O heavy or CPU heavy?
comment on: http://stackoverflow.com/q/51489236
score: 0

http://stackoverflow.com/comment/90168861
type: QuestionComment
type: Comment
score: 6
has text: I think you are trying to ask how you can reference local variables *by name*, based on user input, is that correct? The short answer is: "don't do that."
comment on: http://stackoverflow.com/q/51601342

http://stackoverflow.com/a/51593833
has body: As the link on the original question suggest, just transponse your dataframe df1.T.plot.pie(subplots=True, figsize=(10, 3))
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51593500
downvote count: 0
has comment: http://stackoverflow.com/comment/90153812
answers question: http://stackoverflow.com/q/51593500
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90153401

http://stackoverflow.com/comment/90215078
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51625132
type: AnswerComment
has text: Thanks, I had actually been trying `[i[0] for i in a for a in players]`, I see why your solution works as opposed to mine though

http://stackoverflow.com/comment/103238817
comment on: http://stackoverflow.com/q/51563007
type: QuestionComment
score: 0
type: Comment
has text: Do you have a solution?

http://stackoverflow.com/q/51617674
tagged with: mathematical-optimization
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/90203755
has title: Passing list of lists as input to scipy.optimize.curve_fit
has comment: http://stackoverflow.com/comment/90201453
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90202554
has body: I am trying to solve an example marketing mix model problem using python and the curve_fit function. I need to fit two sets of parameters, which i add to my function as a * arg list of lists. I can get the curve fit to work for one set of parameter (a single list) but not two. Code #import packages from scipy.optimize import curve_fit import pandas as pd import numpy as np from statsmodels.tsa.filters.filtertools import recursive_filter as rec Dataset a = np.array(0).repeat(150) b = np.array(0).repeat(150) c = np.array(0).repeat(150) a[0:90] = np.random.uniform(5,10,(90,)) b[50:150] = np.random.uniform(20,40,(100,)) c[30:100] = np.random.uniform(5,25,(70,)) df = pd.DataFrame({'a':a,'b':b,'c':c}) Fitting one set of parameters def mmm(data,*param): dic = {} j = 0 for i in data: dic[i] = rec(data[i],param[j]) j += 1 return(np.sum(pd.DataFrame(dic),1)) The function, applies the recursive filter to each field in the data argument with a different lambda parameter and returns the dataframe row sum. kpi = mmm(df,*(0.5,0.5,0.1)) + np.random.uniform(-5,5) When passing a *argument to the scipy curve fit function you have to define a function that outputs a function. As described here:Pass tuple as input argument for scipy.optimize.curve_fit Fit the curve a = np.zeros(3) def make_func(): def mmm(data,*param): dic = {} j = 0 for i in data: dic[i] = rec(data[i],param[j]) j += 1 return(np.sum(pd.DataFrame(dic),1)) return(mmm) leastsq, covar = curve_fit(make_func(),df,kpi,a) print(leastsq) array([0.87560795, 0.87192766, 0.84864161]) Fitting two sets of parameters def mmm(x,*arg): c = args[0] a = args[1] dic = {} j = 0 for i in x: dic[i] = c[j] * rec(x[i], a[j]) j += 1 return(np.sum(pd.DataFrame(dic),1)) The function, applies the recursive filter to each field in the data argument with a different lambda (a), multiplies it by a scalar (c) and takes the row sum of the dataframe. args = [[4,5,3],[0.2,0.4,0.5]] kpi = mmm(df,*args) + np.random.uniform(-5,5) Fit the curve args = np.zero…
tagged with: curve-fitting
tagged with: python
linked to: http://stackoverflow.com/q/18326524
has answer: http://stackoverflow.com/a/51619331

numpy
tags question: http://stackoverflow.com/q/51541031
tags question: http://stackoverflow.com/q/51530094
tags question: http://stackoverflow.com/q/51548878
tags question: http://stackoverflow.com/q/51575947
tags question: http://stackoverflow.com/q/51610959
tags question: http://stackoverflow.com/q/51508327
tags question: http://stackoverflow.com/q/51540702
tags question: http://stackoverflow.com/q/51548970
tags question: http://stackoverflow.com/q/51486063
tags question: http://stackoverflow.com/q/51599191
tags question: http://stackoverflow.com/q/51485603
tags question: http://stackoverflow.com/q/51521063
tags question: http://stackoverflow.com/q/51613581
tags question: http://stackoverflow.com/q/51542188
tags question: http://stackoverflow.com/q/51597306
tags question: http://stackoverflow.com/q/51562302
tags question: http://stackoverflow.com/q/51533472
tags question: http://stackoverflow.com/q/51509939
tags question: http://stackoverflow.com/q/51567471
tags question: http://stackoverflow.com/q/51548826
tags question: http://stackoverflow.com/q/51615437
tags question: http://stackoverflow.com/q/51536111
tags question: http://stackoverflow.com/q/51499643
tags question: http://stackoverflow.com/q/51586757
tags question: http://stackoverflow.com/q/51520630
tags question: http://stackoverflow.com/q/51576736
tags question: http://stackoverflow.com/q/51554659
tags question: http://stackoverflow.com/q/51584223
tags question: http://stackoverflow.com/q/51492335
tags question: http://stackoverflow.com/q/51594489
tags question: http://stackoverflow.com/q/51631249
tags question: http://stackoverflow.com/q/51558911
tags question: http://stackoverflow.com/q/51541302
tags question: http://stackoverflow.com/q/51543705
tags question: http://stackoverflow.com/q/51490806
tags question: http://stackoverflow.com/q/51542532
tags question: http://stackoverflow.com/q/51577129
tags question: http://stackoverflow.com/q/51541943
tags question: http://stackoverflow.com/q/51574859
tags question: http://stackoverflow.com/q/51501766
tags question: http://stackoverflow.com/q/51537879
tags question: http://stackoverflow.com/q/51578212
tags question: http://stackoverflow.com/q/51594431
tags question: http://stackoverflow.com/q/51617421
tags question: http://stackoverflow.com/q/51553722
tags question: http://stackoverflow.com/q/51523666
tags question: http://stackoverflow.com/q/51522488
tags question: http://stackoverflow.com/q/51594900
tags question: http://stackoverflow.com/q/51510635
tags question: http://stackoverflow.com/q/51570512
tags question: http://stackoverflow.com/q/51587306
tags question: http://stackoverflow.com/q/51586582
tags question: http://stackoverflow.com/q/51485967
tags question: http://stackoverflow.com/q/51571422
tags question: http://stackoverflow.com/q/51540659
tags question: http://stackoverflow.com/q/51506252
tags question: http://stackoverflow.com/q/51622601
tags question: http://stackoverflow.com/q/51484600
tags question: http://stackoverflow.com/q/51578328
tags question: http://stackoverflow.com/q/51559974
tags question: http://stackoverflow.com/q/51624851
tags question: http://stackoverflow.com/q/51533162
tags question: http://stackoverflow.com/q/51598353
tags question: http://stackoverflow.com/q/51507943
tags question: http://stackoverflow.com/q/51565436
tags question: http://stackoverflow.com/q/51498521
tags question: http://stackoverflow.com/q/51637222
tags question: http://stackoverflow.com/q/51555629
tags question: http://stackoverflow.com/q/51559330
tags question: http://stackoverflow.com/q/51581240
tags question: http://stackoverflow.com/q/51638943
tags question: http://stackoverflow.com/q/51522993
tags question: http://stackoverflow.com/q/51605581
tags question: http://stackoverflow.com/q/51601160
tags question: http://stackoverflow.com/q/51501758
tags question: http://stackoverflow.com/q/51528185
tags question: http://stackoverflow.com/q/51574119
tags question: http://stackoverflow.com/q/51523619
tags question: http://stackoverflow.com/q/51528266
tags question: http://stackoverflow.com/q/51607953

http://stackoverflow.com/q/51555750
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51557627
has title: Django ValidationError when deleting queryset
tagged with: django-queryset
downvote count: 0
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/90078644
favorite count: 0
accepted answer: http://stackoverflow.com/a/51557627
has body: I am writing a Django command to delete data older than x days from my app. The filtering is made using the following: qs = Data.objects.filter(date_created__lte=timezone.now()-timedelta(days=days_del)) With days_del being an integer and date_created a DateTimeField. When trying to either print this queryset, or calling .delete() on it result in a JSONDecodeError and ValidationError. I don't really get why this happens or how I can prevent it trying to decode JSON fileds in this case. Note that I am using the jsonfield pypi package and the Data model has a JSONField. It is possible that some data are stalled and causing the problem (see traceback), is there a way to ignore the validation and proceed with the deletion anyway? Traceback (most recent call last): File "/root/virtualenvs/myproj-prod/lib/python3.6/site-packages/jsonfield/fields.py", line 83, in pre_init return json.loads(value, **self.load_kwargs) File "/usr/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/usr/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.6/json/decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 464 (char 463) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/root/virtualenvs/myproj-prod/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/root/virtualenvs/myproj-prod/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/virtualenvs/myproj-prod/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_opt…
tagged with: python
has comment: http://stackoverflow.com/comment/90078508
tagged with: python-3.x
tagged with: django
upvote count: 1
type: Question

http://stackoverflow.com/a/51492253
score: 4
answers question: http://stackoverflow.com/q/51491893
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/89953376
has comment: http://stackoverflow.com/comment/89953426
has body: Maybe you could use something like the following. Note that it relies on the fact that the average year has 365.25 days, so it may be a day off sometimes. import datetime as dt def year_days_diff(x): diff = (dt.datetime.now() - x).days return str(int(diff / 365.25)) + ' years ' + str(int(diff / 365.25 % 1 * 365.25)) + ' days' Example: birth_date = dt.datetime.now() - dt.timedelta(10000) year_days_diff(birth_date) output: '27 years 138 days'

http://stackoverflow.com/q/51554682
tagged with: spss-modeler
downvote count: 0
answer count: 1
tagged with: decision-tree
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Running CHAID on continuous predictors
score: 1
has answer: http://stackoverflow.com/a/52638439
upvote count: 1
has body: Please, did anyone try to run CHAID algorithm on continuous predictors ?? At first, I used SPSS Modeler and it worked fine. but when I tried it on Python 3.6, it didn't work for me. Thanks :) P.S. CHAID package could be found here : https://github.com/Rambatino/CHAID
type: Question

http://stackoverflow.com/comment/90143706
type: QuestionComment
has text: If it is just an `XML` formatted string that is returned from the query you could parse it using [`ET.fromstring`](https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml) and then save to a file following [this](https://stackoverflow.com/questions/28813876/how-do-i-get-pythons-elementtree-to-pretty-print-to-an-xml-file/28814053) question.
comment on: http://stackoverflow.com/q/51587370
score: 0
type: Comment

http://stackoverflow.com/a/51549151
answers question: http://stackoverflow.com/q/51548902
has comment: http://stackoverflow.com/comment/90092238
score: 1
has body: csv.writer.writerows accepts an iterable of iterables, while writerow accepts an iterable. You are feeding a series of floats, which would only work with writerow and only if you wish all values to be on the first line. Therefore, you can amend to: list_of_lists = [[i] for i in basefilevalue.values] writer.writerows(list_of_lists) This will write each element of the series basefilevalue on a separate line. However, it's unclear why you are resorting to the csv module when, as in your existing code, you can use pd.Series.to_csv.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51548902
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90095007
comment on: http://stackoverflow.com/q/51563985
type: QuestionComment
type: Comment
has text: You can also consider a list/dict comprehension `values = ['first', 'second']` and `{'list': [{'value': [v]} for v in values]}`
score: 2

http://stackoverflow.com/comment/89941564
has text: And when `x = y`, the distance is minimized at `k = 0`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51486003

http://stackoverflow.com/q/51564120
has title: TypeError: string indices must be integers using pandas apply with lambda
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/51564218
answer count: 2
downvote count: 0
score: 4
tagged with: series
has body: I have a dataframe, one column is a URL, the other is a name. I'm simply trying to add a third column that takes the URL, and creates an HTML link. The column newsSource has the Link name, and url has the URL. For each row in the dataframe, I want to create a column that has: &lt;a href="[the url]"&gt;[newsSource name]&lt;/a&gt; Trying the below throws the error File "C:\Users\AwesomeMan\Documents\Python\MISC\News Alerts\simple_news.py", line 254, in df['sourceURL'] = df['url'].apply(lambda x: '{1}'.format(x, x[0]['newsSource'])) TypeError: string indices must be integers df['sourceURL'] = df['url'].apply(lambda x: '&lt;a href="{0}"&gt;{1}&lt;/a&gt;'.format(x, x['source'])) But I've used x[colName] before? The below line works fine, it simply creates a column of the source's name: df['newsSource'] = df['source'].apply(lambda x: x['name']) Why suddenly ("suddenly" to me) is it saying I can't access the indices?
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51564282
favorite count: 0
has answer: http://stackoverflow.com/a/51564218
possible better answer: http://stackoverflow.com/a/51564282
tagged with: lambda
type: AnsweredQuestion
tagged with: dataframe

http://stackoverflow.com/q/51552017
answer count: 1
has comment: http://stackoverflow.com/comment/90071467
has comment: http://stackoverflow.com/comment/90071719
score: -3
favorite count: 0
has comment: http://stackoverflow.com/comment/90071350
accepted answer: http://stackoverflow.com/a/51566574
has comment: http://stackoverflow.com/comment/90071271
tagged with: kivy
tagged with: python-3.x
tagged with: kivy-language
has body: I basically have no clue on why the ScrollView isn't scrolling Here is the python code: from kivy.app import App from kivy.config import Config from kivy.clock import Clock from kivy.core.window import Window from kivy.properties import ObjectProperty from kivy.properties import StringProperty from kivy.properties import NumericProperty from kivy.properties import ListProperty from kivy.uix.floatlayout import FloatLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.screenmanager import * from kivy.uix.scrollview import ScrollView class ScrollButton(Button): pass class DropperScrollView(ScrollView): layout=ObjectProperty() class MainWindow(FloatLayout): mainbox=ObjectProperty() dropper=ObjectProperty() mainbutton=ObjectProperty() dropper_button_1=ObjectProperty() dropper_button_2=ObjectProperty() dropper_button_3=ObjectProperty() dropper_button_4=ObjectProperty() scroll_list=ObjectProperty() def open_dropper(self,dt): self.dropper.open(self.mainbutton) def btn_1(self,a): if self.scroll_list.layout.children==[]: btn_1=ScrollButton(text='Button 1') btn_2=ScrollButton(text='Button 2') self.scroll_list.layout.add_widget(btn_1) self.scroll_list.layout.add_widget(btn_2) class BioWikiaApp(App): ratio=1/7 window_width=360 window_height=640 squared_ratio=NumericProperty(ratio) squared_dropper_size_hint=ListProperty([ratio,ratio*9/16]) squared_dropper_size=ListProperty([window_width*ratio,window_height*ratio*9/16]) def build(self): Window.size=(self.window_width,self.window_height) Window.clearcolor=(155/255,220/255,160/255,1) return MainWindow() if __name__=='__main__': app=BioWikiaApp() app.run() And the kivy file: #:import Clock kivy.clock.Clock #:import App kivy.app.App #:import Window kivy.core.window.Window #:import NoTransition kivy.uix.screenmanager.NoTransition &lt;DropperScrollView&gt;: layout:scroll_layout size_hint_x:app.squared_ratio pos_hint:{'…
has comment: http://stackoverflow.com/comment/90072112
tagged with: python
has comment: http://stackoverflow.com/comment/90071679
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90071883
tagged with: scrollviewer
has comment: http://stackoverflow.com/comment/90072368
downvote count: 3
has answer: http://stackoverflow.com/a/51566574
has title: Why isn't the ScrollView working properly?
type: Question
has comment: http://stackoverflow.com/comment/90071636
upvote count: 0

http://stackoverflow.com/a/51509356
answers question: http://stackoverflow.com/q/51488486
downvote count: 0
type: Answer
upvote count: 3
has body: TLDR; The real, best answer may be a duplicate of Get Twitter card from API The answer suggests to inspect a request to the URL and examine HTML elements. This works for your example tweet, but unfortunately it likely will not be general enough to work for all others. For example, I used hard-coded tags found in the example that may not be in others. But surely this can serve as a starting point and be adapted to work for all tweets. Most importantly proves it can be done. import tweepy from tweepy import OAuthHandler import requests # fill values consumer_key = '' consumer_secret = '' access_token = '' access_secret = '' auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth) tweet_id = 1021517076069056514 status = api.get_status(id=tweet_id) tweet_url = status.entities['urls'][0]['expanded_url'] r = requests.get(tweet_url) from bs4 import BeautifulSoup soup = BeautifulSoup(r.content, 'html.parser') media_container = soup.select('div.card2.js-media-container') tweet_card = media_container[0].select('div.js-macaw-cards-iframe-container') tweet_card_url = tweet_card[0]['data-full-card-iframe-url'] twitter_base_url = 'http://www.twitter.com' r2 = requests.get(''.join([twitter_base_url, tweet_card_url])) final_page = r2.content soup2 = BeautifulSoup(final_page, 'html.parser') final_data = soup2.find('img', {'class': 'u-block'}) headline = final_data['alt'] image_link = final_data['data-src'] print 'Headline: {}'.format(headline) print 'Image Link: {}'.format(image_link) gets: Headline: Global central banks have rattled bond markets Image Link: https://pbs.twimg.com/card_img/1021513789722841093/LQWGa8uL?format=jpg&amp;name=600x314
score: 3

http://stackoverflow.com/q/51559330
answer count: 2
has answer: http://stackoverflow.com/a/51584109
upvote count: 0
has comment: http://stackoverflow.com/comment/90085846
favorite count: 0
possible better answer: http://stackoverflow.com/a/51584269
has answer: http://stackoverflow.com/a/51584269
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51584109
has body: The Python code below executes in about 2 sec. An equivalent code in C executes in 6 ms. Some explanations: I have serial data of 2 ADC channels (adc0, adc1, adc0, adc1, ...). If adc1 &lt;= 10 I must add adc1 to the sum, else I must add adc0. These values are multiplied by different coefficients (0.1 and 0.01). #!/usr/bin/env python import time import numpy as np dd = np.random.randint(0, 20, size=(2*1000*1000)) t_start = time.clock() avg_sum1 = 0.0 BlockOffset = 0 while BlockOffset &lt; len(dd): if dd[BlockOffset + 1] &lt;= 10: avg_sum1 += dd[BlockOffset + 1] * 0.1 else: avg_sum1 += dd[BlockOffset + 0] * 0.01 BlockOffset += 2 print('Avg: ' + str(avg_sum1 / len(dd) / 2)) print('Exe time: ' + str(time.clock() - t_start)) What is fastest way to do this with built-in functions or numpy?
downvote count: 1
has title: What is fastest way to compute average of python array different elements with condition?
type: Question
has comment: http://stackoverflow.com/comment/90085489
has comment: http://stackoverflow.com/comment/90085744
has comment: http://stackoverflow.com/comment/90087806
score: -1
tagged with: numpy

http://stackoverflow.com/a/61527643
type: Answer
score: 2
has body: Just finished debugging the same issue. By RFC 2965: The term effective host name is related to host name. If a host name contains no dots, the effective host name is that name with the string .local appended to it. Otherwise the effective host name is the same as the host name. Note that all effective host names contain at least one dot. Python Requests module uses http.cookiejar module to handle the cookies. It verifies the received cookies before applying them to a session. Use the following code to get debug output: import logging import http.cookiejar logging.basicConfig(level=logging.DEBUG) http.cookiejar.debug = True Here is an example, when received cookie is not applied: DEBUG:http.cookiejar:add_cookie_header DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): localhost DEBUG:urllib3.connectionpool:http://localhost:80 "POST /api/login HTTP/1.1" 200 6157 DEBUG:http.cookiejar:extract_cookies: Date: Thu, 30 Apr 2020 15:45:11 GMT Server: Werkzeug/0.14.1 Python/3.5.3 Content-Type: application/json Content-Length: 6157 Set-Cookie: token=1234; Domain=localhost; Path=/ Keep-Alive: timeout=5, max=100 Connection: Keep-Alive DEBUG:http.cookiejar: - checking cookie token=1234 DEBUG:http.cookiejar: non-local domain .localhost contains no embedded dot Requests sent to localhost, expect web server to set domain part of a cookie to localhost.local Here is an example, when received cookie was applied correctly: DEBUG:http.cookiejar:add_cookie_header DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): localhost DEBUG:urllib3.connectionpool:http://localhost:80 "POST /api/login HTTP/1.1" 200 6157 DEBUG:http.cookiejar:extract_cookies: Date: Thu, 30 Apr 2020 15:52:08 GMT Server: Werkzeug/0.14.1 Python/3.5.3 Content-Type: application/json Content-Length: 6157 Set-Cookie: token=1234; Domain=localhost.local; Path=/ Keep-Alive: timeout=5, max=100 Connection: Keep-Alive DEBUG:http.cookiejar: - checking cookie token=1234 DEBUG:http.cookiejar: setting cookie: &lt;…
downvote count: 0
answers question: http://stackoverflow.com/q/51492267
upvote count: 2

http://stackoverflow.com/q/51564270
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90095536
favorite count: 0
has comment: http://stackoverflow.com/comment/90095521
type: UnansweredQuestion
tagged with: sockets
has answer: http://stackoverflow.com/a/51569027
tagged with: python
has title: Syntax Error I do not understand why it is happening
has comment: http://stackoverflow.com/comment/90095577
has comment: http://stackoverflow.com/comment/90095528
type: Question
tagged with: syntax-error
has body: So I am currently building a blogging type system from scratch in python and I am currently trying to run my blog creation program and I keep getting an error saying File "create.py", line 55 cc.sendall(rp) ^ SyntaxError: invalid syntax Here is my full code thanks in advance to any responses I get. import socket, os HOST, PORT = '', 8080 ls = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ls.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ls.bind((HOST, PORT)) ls.listen(1) while True: cc, ca = ls.accept() rq = cc.recv(1024) rp = """\ HTTP/1.1 200 OK Post succesfully posted! Return to the homepage? """ substrings = [] substrings.insert(0, rq[rq.find("GET ")+3:rq.find(" HTTP/1.1")]) if substrings[0] != ' /favicon.ico': substrings.insert(1, rq[12:rq.find("&")]) substrings.insert(2, rq[rq.find("&")+7:len(substrings[0])+3]) f = open("posts/{}.html".format(substrings[1]), "w+") f.write("""\ {} {} Comment """.format(substrings[1], substrings[1], substrings[2]) cc.sendall(rp) cc.close() So it was just that ) but now I am getting an error saying: Traceback (most recent call last): File "create.py", line 54, in <module> """.format(substrings[1], substrings[1], substrings[2])) KeyError: '\n\t\turl = {}\n\t\tcomment = prompt(\'What is your comment?\');\n\t\tnewurl = "http'
has comment: http://stackoverflow.com/comment/90095479
score: 0
upvote count: 1

plot-annotations
tags question: http://stackoverflow.com/q/51495982
tag name: plot-annotations
type: Tag

http://stackoverflow.com/q/51535166
tagged with: python
has comment: http://stackoverflow.com/comment/90262795
tagged with: qwebenginepage
type: UnansweredQuestion
score: 1
tagged with: pyqt5
upvote count: 1
has title: How to modify a link url before it is navigated to
has comment: http://stackoverflow.com/comment/90264601
has comment: http://stackoverflow.com/comment/90039678
type: Question
has comment: http://stackoverflow.com/comment/90263159
has comment: http://stackoverflow.com/comment/90038833
has comment: http://stackoverflow.com/comment/90038436
has body: I want to catch a click on a page and add at the anchor link some text. For example, If the user click on an anchor with href mysite.com/about, I want modify the link in: mysite.com/about?myvar=value I used QWebEngineUrlRequestInterceptor but the click on the link is not catched. What I am doing wrong? from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtWebEngineWidgets import * from PyQt5.QtPrintSupport import * import os import sys class MyPage(QWebEnginePage): def __init__(self, parent=None): super(MyPage, self).__init__(parent) def triggerAction(self, action, checked=False): if action == QWebEnginePage.OpenLinkInNewWindow: self.createWindow(QWebEnginePage.WebBrowserWindow) return super(MyPage, self).triggerAction(action, checked) def acceptNavigationRequest(self, url, navtype, mainframe): if navtype == QWebEnginePage.NavigationTypeLinkClicked: # go somewhere else self.setUrl(QUrl('https://wikipedia.org')) # abort the current navigation return False return super(MyPage, self).acceptNavigationRequest(url, navtype, mainframe) class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.myPage = MyPage(self) #fab #self.setPage(self.myPage) #fab self.browser = QWebEngineView() self.browser.setUrl(QUrl(WEBSITE_HOME)) self.browser.loadFinished.connect(self.update_title) self.setCentralWidget(self.browser) navtb = QToolBar("Navigation") navtb.setIconSize(QSize(16, 16)) # self.addToolBar(navtb) back_btn = QAction(QIcon(os.path.join('images', 'arrow-back.png')), "Back", self) back_btn.setStatusTip("Back to previous page") back_btn.triggered.connect(self.browser.back) navtb.addAction(back_btn) next_btn = QAction(QIcon(os.path.join('images', 'arrow-forward.png')), "Forward", self) next_btn.setStatusTip("Forward to next page") next_btn.triggered.connect(self.browser.forward) navtb.addAction(next_btn) reload_btn = QAction(QIcon(os.path.join('images', 'refresh.png')), "Reload", self) r…
tagged with: hyperlink
has comment: http://stackoverflow.com/comment/90039591
has comment: http://stackoverflow.com/comment/90039052
has comment: http://stackoverflow.com/comment/90039698
has comment: http://stackoverflow.com/comment/90261082
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90045172
has comment: http://stackoverflow.com/comment/90264495
has answer: http://stackoverflow.com/a/51650630

http://stackoverflow.com/comment/90056301
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51544141
score: 1
has text: Try `pip install --upgrade --force-reinstall pyparsing`

http://stackoverflow.com/q/51529616
favorite count: 0
has body: I've scrolled the internet all over and theres no simple, clean explanation for this. How can I open the Python shell, but inside a terminal window such as CMD? I have an application for it, but want to run it inside a terminal, so I can practice Python code inside my IDE like VS code.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90027500
has comment: http://stackoverflow.com/comment/90027453
tagged with: python
has answer: http://stackoverflow.com/a/51529746
has answer: http://stackoverflow.com/a/51529757
type: Question
has title: How to run the python shell inside a terminal in Windows?
score: 0
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/90027714
downvote count: 1

http://stackoverflow.com/q/51576272
downvote count: 0
score: 1
tagged with: mnist
type: Question
tagged with: random-forest
tagged with: scikit-learn
has title: Why does performance suffer when fitting a Random Forest model after reducing with PCA?
has answer: http://stackoverflow.com/a/51581373
accepted answer: http://stackoverflow.com/a/51581373
upvote count: 1
answer count: 1
has body: This question has to do with comparing speed between a Random Forest Classifier model on a full set of features vs a Random Forest model on a reduced number of components after doing PCA. I'm using the MNIST dataset which has 60,000 rows for my training (X_train) and 10,000 for my test (X_test), and 784 features which are pixels representing the 28x28 image. For the full set of features, I am measuring the time it takes to fit using clock() like so: clf = RandomForestClassifier() t0 = time.clock() clf.fit(X_train, y_train) runtime = time.clock() - t0 For doing PCA and Random Forest, I am doing something similar: pca = PCA(n_components = 0.95) t0 = time.clock() components = pca.fit_transform(X_train) clf.fit(components, y_train) runtime = time.clock() - t0 For the full set, I get a runtime of ~6 seconds while for the second set, I get a runtime of ~27 seconds. Even if I split out to look at just the runtimes of fitting (removing the time it takes to do the pca), I still consistently get approx 6 seconds compared against 14 seconds. The number of features for the full set is 784 while the PCA reduced that to 154 components. My limited understanding is that at the very least, fitting the model should be quicker with PCA because of the reduced number of features - why is it not? I've tried scaling before PCA, tuning hyperparameters, among other things but it is pretty consistent the counter-intuitive difference in runtime and I believe there's just something I'm not understanding conceptually.
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: pca

http://stackoverflow.com/q/51496937
linked to: http://stackoverflow.com/q/17676036
score: 0
tagged with: http://stackoverflow.com/tag/html
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89961916
tagged with: python
has answer: http://stackoverflow.com/a/51497072
tagged with: popup
has title: Automate filling HTML pop up forms in python
has body: I am looking for resources or guide so that I could build a Python code to fill my ~2k online forms automatically. Sorry I dont have any script to share as many resources in which python code is written to go to form URL and fill it. Since in my case it is a pop up form it doesnt really have a real URL. Please be kind, I am new to Python. Is there a way to do something to imitate clicks on browser window and fill in new values in the form ?
type: Question
answer count: 1

h2o
tags question: http://stackoverflow.com/q/51602029
tags question: http://stackoverflow.com/q/51543158
tags question: http://stackoverflow.com/q/51527546
tag name: h2o
type: Tag

http://stackoverflow.com/q/51512519
has comment: http://stackoverflow.com/comment/90060057
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: python-packaging
has answer: http://stackoverflow.com/a/59216818
has body: I have this dependency issue: Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. You can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation. Could not find a version that matches futures<4.0.0,>=2.2.0,>=3.2.0; python_version < "3.2" Tried: 0.2.python3, 0.1, 0.2, 1.0, 2.0, 2.1, 2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.1.5, 2.1.6, 2.1.6, 2.2.0, 2.2.0, 3.0.0, 3.0.0, 3.0.1, 3.0.1, 3.0.2, 3.0.2, 3.0.3, 3.0.3, 3.0.4, 3.0.4, 3.0.5, 3.0.5, 3.1.0, 3.1.0, 3.1.1, 3.1.1 There is obviously an issue. The only version of package futures that could resolve the conflict (="3.2.0") is not available. edit: I updated the message above. now the python version also comes into the conflict. Whats are my options here? I would like to continue to use pipenv and the Pipfile.lock edit This is the graph genereated by pipenv. It took me a while to figure out that it does not work with pip v10 installed in the virtualenv. But now here it is. pipenv graph apiai==1.2.3 - numpy [required: Any, installed: 1.14.3] beautifulsoup4==4.6.0 boto3==1.7.15 - botocore [required: >=1.10.15,<1.11.0, installed: 1.10.15] - docutils [required: >=0.10, installed: 0.14] - jmespath [required: >=0.7.1,<1.0.0, installed: 0.9.3] - python-dateutil [required: >=2.1,<3.0.0, installed: 2.7.2] - six [required: >=1.5, installed: 1.11.0] - jmespath [required: >=0.7.1,<1.0.0, installed: 0.9.3] - s3transfer [required: >=0.1.10,<0.2.0, installed: 0.1.13] - botocore [required: <2.0.0,>=1.3.0, installed: 1.10.15] - docutils [required: >=0.10, installed: 0.14] - jmespath [required: >=0.7.1,<1.0.0, installed: 0.9.3] - python-dateutil [required: >=2.1,<3.0.0, installed: 2.7.2] - six [required: >=1.5, installed: 1.11.0] celery==4.1.0 - billiard [required: >=3.5.0.2,<3.6.0, installed: 3.5.0.3] - kombu [required: >=4.0.2,<5.0, inst…
type: Question
tagged with: pipenv
has comment: http://stackoverflow.com/comment/90147969
has comment: http://stackoverflow.com/comment/90034888
upvote count: 9
has comment: http://stackoverflow.com/comment/90060081
has title: pipenv: How to resolve dependency conflicts
score: 9
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51602122
has body: Did you expect this? I tried to make it simple. contacts_to_parse = [ { "contact_order": "1", "contact_type": "Other", "contact_role": "role here", "contact_text": "contact text here" }, { "contact_order": "2", "contact_type": "Mail Alias", "contact_role": "role here", "contact_text": "contact text here" } ] def check(contacts): result = [] for item in contacts: result.append({}) for key, val in item.items(): result[-1][key.replace('_', ' ').title()] = val return result print(check(contacts_to_parse)) Result: [ { 'Contact Order': '1', 'Contact Type': 'Other', 'Contact Role': 'role here', 'Contact Text': 'contact text here' }, { 'Contact Order': '2', 'Contact Type': 'Mail Alias', 'Contact Role': 'role here', 'Contact Text': 'contact text here' } ]
score: 0
answers question: http://stackoverflow.com/q/51602026
type: Answer

http://stackoverflow.com/q/51617315
score: 0
has title: Tensorflow lite accuracy drop on mobile device
has answer: http://stackoverflow.com/a/51742000
has comment: http://stackoverflow.com/comment/103481522
answer count: 1
accepted answer: http://stackoverflow.com/a/51742000
tagged with: android
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/50938992
tagged with: tensorflow
type: Question
has body: I followed the both Tensorflow for Poets Tutorials: Tensorflow for Poets 1 and Tensorflow for Poets 2. My retrained model gives accurate results for a test on my laptop but after converting into the .tflite file and trying to classify the same image on my Android device the accuracy drops under 1%. I used the following commands to retrain und convert: python retrain.py \ --bottleneck_dir=tf_files/bottlenecks \ --how_many_training_steps=500 \ --model_dir=tf_files/models/ \ --summaries_dir=tf_files/training_summaries/"${ARCHITECTURE}" \ --output_graph=tf_files/retrained_graph.pb \ --output_labels=tf_files/retrained_labels.txt \ --architecture="${ARCHITECTURE}" \ --image_dir=tf_files/flower_photos toco \ --input_file=tf_files/retrained_graph.pb \ --output_file=tf_files/optimized_graph.lite \ --input_format=TENSORFLOW_GRAPHDEF \ --output_format=TFLITE \ --input_shape=1,224,224,3 \ --input_array=Placeholder \ --output_array=final_result \ --inference_type=FLOAT \ --input_data_type=FLOAT Strangely the optimized file is almost as high as the original (both around 80 MB). Using Tensorflow 1.9.0 and Python 3.6.6. Any help or tip is appreciated!

http://stackoverflow.com/comment/97857135
has text: In case anyone in curious, I'm getting the same error on a Windows system, so... *shrug*
comment on: http://stackoverflow.com/q/51538779
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51554322
has body: I'm trying to write a rock-paper-scissors game in python.this is the code: D_0 = {1: "rock", 2: "scissors", 3: "paper"} from random import randint play = False name = input("What is your name?: ") print("%s you have to pick among rock,paper and scissors." % name) while play == False: p_1 = input("which one?") computer = D_0[randint(1, 3)] print("my choice is: ",computer) if p_1 == computer: print("it's a draw") elif p_1 == "scissors" and computer == "paper": print("you won!") elif p_1 == "paper" and computer == "scissors": print("you lost!") elif p_1 == "scissors" and computer == "rock": print("you lost!") elif p_1 == "rock" and computer == "paper": print("you lost!") elif p_1 == "rock" and computer == "scissors": print("you won!") elif p_1 == "paper" and computer == "rock": print("you won!") else: print("Invalid input") break again = input("do you want another round?:") if again == "yes": play = False else: play = True the program works well but I want it to ask the player whether or not he/she wants to do another round.If the answer is yes the program must restart the loop. The problem is I don't know how to do that.I know it's probably related to True and False and I attempted to do something as you can see in the code but it didn't work. please Help me.
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/51554391
score: 0
tagged with: while-loop
has title: restarting while loop in a game
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51554391
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90075552

recursion
type: Tag
tags question: http://stackoverflow.com/q/51521555
tags question: http://stackoverflow.com/q/51519227
tags question: http://stackoverflow.com/q/51498018
tags question: http://stackoverflow.com/q/51633831
tags question: http://stackoverflow.com/q/51506378
tags question: http://stackoverflow.com/q/51495560
tags question: http://stackoverflow.com/q/51492451
tags question: http://stackoverflow.com/q/51626227
tags question: http://stackoverflow.com/q/51585130
tag name: recursion
tags question: http://stackoverflow.com/q/51622768
tags question: http://stackoverflow.com/q/51623594
tags question: http://stackoverflow.com/q/51550083
tags question: http://stackoverflow.com/q/51489385
tags question: http://stackoverflow.com/q/51484712
tags question: http://stackoverflow.com/q/51572986
tags question: http://stackoverflow.com/q/51546593
tags question: http://stackoverflow.com/q/51534957
tags question: http://stackoverflow.com/q/51524628
tags question: http://stackoverflow.com/q/51563620

http://stackoverflow.com/q/51499610
tagged with: configuration-files
favorite count: 0
tagged with: linux
tagged with: parsing
tagged with: drbd
has body: Is the configuration-file format that DRBD uses a somewhat standard one with existing parsers in Python or is it not which would require me to write my own parser? Example: resource server42 { volume 0 { device /dev/drbd9; disk /dev/vg01/server42-root-drbd; meta-disk /dev/vg01/server42-root-metadata; } volume 1 { device /dev/drbd10; disk /dev/vg01/server42-swap-drbd; meta-disk /dev/vg01/server42-swap-metadata; } volume 2 { device /dev/drbd11; disk /dev/vg01/server42-temp-drbd; meta-disk /dev/vg01/server42-temp-metadata; } volume 3 { device /dev/drbd12; disk /dev/vg01/server42-var-drbd; meta-disk /dev/vg01/server42-var-metadata; } on server23 { address 10.20.30.40:7796; } on server24 { address 10.20.30.41:7796; } }
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has title: Is the DRBD configuration-file format a standard one?
type: Question
has answer: http://stackoverflow.com/a/51565557
accepted answer: http://stackoverflow.com/a/51565557
upvote count: 1
answer count: 1

http://stackoverflow.com/q/51549804
tagged with: pysal
possible better answer: http://stackoverflow.com/a/52628937
has body: I want to plot two tematic maps side by side to compare then. I am using geopandas to plot the maps and pysal to generate the maps from spatial analysis.
type: Question
has title: How to plot two maps side by side using pysal or geopandas?
answer count: 3
downvote count: 0
score: 4
favorite count: 0
has answer: http://stackoverflow.com/a/52628937
tagged with: geopandas
tagged with: python
upvote count: 4
accepted answer: http://stackoverflow.com/a/51571827
tagged with: maps
has answer: http://stackoverflow.com/a/73568320
has answer: http://stackoverflow.com/a/51571827
type: AnsweredQuestion

http://stackoverflow.com/comment/90204329
comment on: http://stackoverflow.com/a/51619165
score: 0
type: AnswerComment
has text: You're welcome! If you have more issues, I recommend checking out some resources like [Program Arcade Games](http://programarcadegames.com/) first. I also recommend adding a [`pygame.time.Clock`](http://www.pygame.org/docs/ref/time.html#pygame.time.Clock) instance and calling `clock.tick(FPS)` each frame if you choose the `pygame.event.get` solution.
type: Comment

http://stackoverflow.com/comment/90230183
score: 0
type: AnswerComment
has text: That is a poor assumption. I'd say its much better to assume that OP's example is accurate.
comment on: http://stackoverflow.com/a/51631955
type: Comment

http://stackoverflow.com/comment/89969437
type: AnswerComment
has text: Python doesn't have JARs. That's Java.
type: Comment
comment on: http://stackoverflow.com/a/51500506
score: 1

http://stackoverflow.com/q/51630968
has answer: http://stackoverflow.com/a/51631510
has title: Use the same column spacing as another QGridLayout with a different number of columns
answer count: 1
has body: I have a QGridLayout with 5 columns, and widgets with fixed widths are in columns 1 and 3, so that resizing the window will change the padding around them. I would like to have another QGridLayout above that, but this time with 3 columns, where the 3rd one stretches to the end. I can't seem to get it to match the other layout though, and I'm wondering if there's anything I could do. Here's an image of the box. The red arrows are the resizing width, and I'd like the green arrow to match those if possible. If I set the column stretch to 1|2 or 1|1|4 it resizes at the same rate, but is a bit far offset to the right. I'm still learning Qt so it'd also be nice to know how how most people deal with issues like this.
type: UnansweredQuestion
tagged with: python
tagged with: qt
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/90244622
score: 0

http://stackoverflow.com/q/51528769
tagged with: apache-spark
has answer: http://stackoverflow.com/a/51528831
downvote count: 0
score: 1
favorite count: 0
has title: How to implement FPGrowth algorithm in Python?
possible better answer: http://stackoverflow.com/a/51538899
has body: I've successfully used the apriori algorithm in Python as follows: import pandas as pd from mlxtend.frequent_patterns import apriori from mlxtend.frequent_patterns import association_rules df = pd.read_csv('C:\\Users\\marka\\Downloads\\Assig5.csv') df = apriori(df, min_support=0.79, use_colnames=True) rules = association_rules(df, metric="lift", min_threshold=1) rules[ (rules['lift'] &gt;= 1) &amp; (rules['confidence'] &gt;= 1) ] I'd like to use the FPGrowth algorithm to see if I get the same result but I believe I'm using it wrong since I don't get similar output. The documentation for spark (https://spark.apache.org/docs/1.6.0/mllib-frequent-pattern-mining.html) says: from pyspark.mllib.fpm import FPGrowth data = sc.textFile("data/mllib/sample_fpgrowth.txt") transactions = data.map(lambda line: line.strip().split(' ')) model = FPGrowth.train(transactions, minSupport=0.2, numPartitions=10) result = model.freqItemsets().collect() for fi in result: print(fi) So my code is in turn: from pyspark.mllib.fpm import FPGrowth from pyspark import SparkConf from pyspark.context import SparkContext sc = SparkContext.getOrCreate(SparkConf().setMaster("local[*]")) data = sc.textFile("C:\\Users\\marka\\Downloads\\Assig6.txt") transactions = data.map(lambda line: line.strip().split(' ')) model = FPGrowth.train(transactions, minSupport=0.2, numPartitions=10) result = model.freqItemsets().collect() for fi in result: print(fi) But I get the following instead of a real answer, what am I doing wrong? FreqItemset(items=['1\t1\t1\t1\t1\t1\t1\t0\t0\t0\t0\t1\t1\t0\t0\t1\t1\t1\t1\t1\t0\t0'], freq=24) To make Assig6 I just resaved my original csv as txt I started changing my format and updated my code per user10136092 but still get the undesired output. Here is my code, output, and a sample picture of my new input. from pyspark.mllib.fpm import FPGrowth from pyspark import SparkConf from pyspark.context import SparkContext sc = SparkContext.getOrCreate(SparkConf().setMaster("local[*]")) data…
has answer: http://stackoverflow.com/a/51538899
has comment: http://stackoverflow.com/comment/111284672
tagged with: python
accepted answer: http://stackoverflow.com/a/51528831
tagged with: machine-learning
upvote count: 1
type: Question
type: AnsweredQuestion
tagged with: pyspark
answer count: 2

http://stackoverflow.com/q/51636588
has answer: http://stackoverflow.com/a/51637601
answer count: 1
score: 0
tagged with: python
has title: Reporject the image to 3D using opencv3
has body: I'm trying to use cv2.reprojectImageTo3D function to get (x,y,z) coordinates. but it gives me negatives values of z. can i convert this coordinates to real distance? can i calculate the depth from it?
type: UnansweredQuestion
tagged with: disparity-mapping
type: Question
tagged with: opencv
tagged with: stereo-3d

http://stackoverflow.com/q/51541042
has answer: http://stackoverflow.com/a/51541616
type: Question
tagged with: split
has comment: http://stackoverflow.com/comment/90052045
score: 0
answer count: 3
has title: python splitting numbers in a column
tagged with: parsing
has answer: http://stackoverflow.com/a/51542046
has body: Please help explain how to do the following, I am struggling so much. I have a data set named data3: Type (column1) = string values of GTIN or GCP Key (column2) = 14 digit numbers I need to break those 14 digit numbers up into this logic: if type = GCP then return first three letters from key. if type = GTIN and positions 2-6 in the 14 digits = 00000 then return positions 7-9 in key. if type = gtin and positions 2-6 are not 00000 then return digits 2-4 in key . EXAMPLE: - Type -Key - GTIN -1234589564652344 - GCP -1564546545452344 - GTIN -6000005645324234 If the type is GCP I just want first three numbers in key such as 156. If it's GTIN and has 5 zeros in postitions 2-6 I want positions 7-9 which would be 564 in. If the type is GTIN and does not have 5 zeros in positions 2-6 then I want to return digits 2-4 such as 234 in the above example
has comment: http://stackoverflow.com/comment/90050735
tagged with: python
accepted answer: http://stackoverflow.com/a/51542046
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90049937
has answer: http://stackoverflow.com/a/51541912
possible better answer: http://stackoverflow.com/a/51541616
has comment: http://stackoverflow.com/comment/90050930

http://stackoverflow.com/comment/90035237
comment on: http://stackoverflow.com/a/51531608
type: AnswerComment
type: Comment
has text: @ekartik Please consider [accepting an answer](https://stackoverflow.com/help/accepted-answer), if it solved your problem.
score: 0

http://stackoverflow.com/q/51563692
tagged with: admin
has title: Django autocomplete fields do NOT work when using a horizontal filter on a many to many field
tagged with: django-templates
has answer: http://stackoverflow.com/a/51596697
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/51596697
type: AnsweredQuestion
has body: I am using django's auto complete light to make a custom form. In this model there is another field which I would like to apply a horizontal filter to. However whenever I apply the filter, the autocomplete forms do not work anymore. @admin.register(model) class modelAdmin(VersionAdmin): form = autoCompleteForm filter_horizontal = ('many_to_many_field',) Open to any solutions, I have searched around and cannot seem to find any other similar problem.
type: Question
tagged with: autocomplete
score: 0
answer count: 1

http://stackoverflow.com/q/51621307
has answer: http://stackoverflow.com/a/55196699
answer count: 2
downvote count: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90208582
has comment: http://stackoverflow.com/comment/90208478
favorite count: 0
has comment: http://stackoverflow.com/comment/90208636
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90208325
tagged with: python
has comment: http://stackoverflow.com/comment/90208451
type: Question
score: 5
tagged with: feature-selection
has body: As far as I know, in Bag Of Words method, features are a set of words and their frequency counts in a document. In another hand, N-grams, for example unigrams does exactly the same, but it does not take into consideration the frequency of occurance of a word. I want to use sklearn and CountVectorizer to implement both BOW and n-gram methods. For BOW my code looks like this: CountVectorizer(ngram_range=(1, 1), max_features=3000) Is is enought to set 'binary' parameter to True to perform n-gram feature selection? CountVectorizer(ngram_range=(1, 1), max_features=3000, binary=True) What are the advantages of n-gram over the BOW method?
tagged with: feature-extraction
upvote count: 5
has title: Bag of Words (BOW) vs N-gram (sklearn CountVectorizer) - text documents classification
has comment: http://stackoverflow.com/comment/90208567
has answer: http://stackoverflow.com/a/62985928
tagged with: n-gram

http://stackoverflow.com/q/51600018
accepted answer: http://stackoverflow.com/a/51600152
tagged with: functional-programming
answer count: 1
downvote count: 1
tagged with: keyword-argument
favorite count: 0
has answer: http://stackoverflow.com/a/51600152
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90166265
upvote count: 0
has title: Use a yet to be defined variable as a kwarg in Python
has body: Here's my set up: X = [0,1,2,3] y = [10,20,30,40] def mainfunc(X,y,**kwargs): for i in range(len(y)): c = subfunc(a=X[i],b=y[i],**kwargs) print c def subfunc(a,b,c=None): if c is not None: return a*b + c else: return a*b If I run mainfunc(X=X,y=y) or mainfunc(X=X,y=y,c=2) I'll get the results I expect. But what I'm ultimately interested in, is to run mainfunc(X=X,y=y,c=i), where i is the index of the mainfunc loop. Is that something I can do?
type: Question
tagged with: function
score: -1

http://stackoverflow.com/q/51488457
upvote count: 1
has answer: http://stackoverflow.com/a/51491932
type: AnsweredQuestion
score: 1
has title: Azure Event Hub Python SDK
has body: Can anyone explain how to use the "Event Hub-compatible name" and "Event Hub-Compatible endpoint" using the python event hub SDK. The SDK asks for # Address can be in either of these formats: # "amqps://&lt;URL-encoded-SAS-policy&gt;:&lt;URL-encoded-SAS- # "key&gt;@&lt;mynamespace&gt;.servicebus.windows.net/myeventhub" # "amqps://&lt;mynamespace&gt;.servicebus.windows.net/myeventhub" ADDRESS = os.environ.get('EVENT_HUB_ADDRESS') # SAS policy and key are not required if they are encoded in the URL USER = os.environ.get('EVENT_HUB_SAS_POLICY') KEY = os.environ.get('EVENT_HUB_SAS_KEY') I need help fitting the strings given under the default endpoint into this example.
tagged with: azure-eventhub
type: Question
tagged with: azure-iot-hub
answer count: 2
has answer: http://stackoverflow.com/a/51493465
accepted answer: http://stackoverflow.com/a/51493465
downvote count: 0
tagged with: azure
tagged with: mqtt
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/51491932

http://stackoverflow.com/comment/90056151
has text: The issue is no longer that you don't have `matplotlib` installed. Now, you need to reinstall the dependency `pyparsing`. Try `pip install pyparsing`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51544141
score: 0

http://stackoverflow.com/comment/90052675
type: AnswerComment
comment on: http://stackoverflow.com/a/51541091
score: 0
type: Comment
has text: unfortunately I can not run my script that way. The script does not take arguments to start, it simply waits for them afterwards.

http://stackoverflow.com/q/51599227
type: Question
tagged with: python
tagged with: jupyter-notebook
score: 4
has answer: http://stackoverflow.com/a/51610408
answer count: 1
has body: If I turn on line numbers in my code cells in a Jupyter Notebook the rendered output when I go to download as HTML does not include the line numbers in the output. Is there a setting in nbconvert that allows this? (I did not see anything obvious in the nbconvert docs) If not, is it possible with custom templating in nbconvert? Why: I want to be able to reference Line numbers from my markdown cells for tutorials. Ipython 6.1.0 nbconvert 5.3.1 jupyter client 5.1.0
upvote count: 4
accepted answer: http://stackoverflow.com/a/51610408
type: AnsweredQuestion
downvote count: 0
has title: Export Jupyter notebook to HTML with line numbers?
favorite count: 0
tagged with: nbconvert

http://stackoverflow.com/q/51598295
has body: So, what I am trying to do is when you open the window, it starts a process in which every 0.2 seconds it changes the first and 3rd value of the color (in which it converts the elements of the range into a hex value and then a string) to go from rgb( 86, 32, 86) to rgb(126, 32, 126). Although I thought this might just work, it doesn't. I only get a background of the first color and that's all. from tkinter import * import time root = Tk() for i in range(86,126): h = hex(i) h = str(h) h = h[2] + h[3] root.configure(background=("#" + h + "32" + h )) time.sleep(0.2) root.mainloop()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90180518
tagged with: python
has answer: http://stackoverflow.com/a/51598400
has answer: http://stackoverflow.com/a/51598662
tagged with: background
type: Question
tagged with: for-loop
score: 0
answer count: 2
has title: How can i make this code do what it's supposed to do?
tagged with: colors
linked to: http://stackoverflow.com/q/36670373
tagged with: tkinter

http://stackoverflow.com/q/51544050
tagged with: linux
tagged with: python
has body: I have a commercial c library (a.so) that has several functions. When you call the a.open() function, it performs a dlopen() call for another library dynamically. If calling a.open('b'), it will open b.so. If calling a.open('c'), it will open c.so. The problem is that a.so and b.so share a global variable defined in a.so, but referenced by b.so (and c.so,etc.). I am able to load a.so correctly in python using ctypes and see all the symbols in Python. However, when I call a.open('b'), it attempts to load b.so but returns undefined symbol. //a.c -source for a.so library int aglobal = 0; void open(char* lib) { dlopen(lib); } //b.c - source for b.so library extern int aglobal; Here is my python code to load: from ctypes import cdll p = ctypes.CDLL('a.so') p.open('b') returns the error code: undefined symbol: aglobal Some other notes: files are linked with -fPIC -rdynamic -shared When I write a C program that does the same as the python program, there is not a problem. I've tried swig to wrap the library also, and numerous other things, build options, etc. but same results. Is Python binding the symbols differently or something?
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51545592
accepted answer: http://stackoverflow.com/a/51545592
has comment: http://stackoverflow.com/comment/90061464
type: Question
tagged with: ctypes
tagged with: http://stackoverflow.com/tag/c
linked to: http://stackoverflow.com/q/20849755
upvote count: 1
has title: Loading C library in Python that dlopens another C library - unresolved shared symbol
answer count: 1
tagged with: dlopen
favorite count: 0

http://stackoverflow.com/comment/90196726
has text: You may not be importing what you think you're importing. Does anything else have the same name as `B`? What does `import B; print(dir(B))` show you?
type: QuestionComment
comment on: http://stackoverflow.com/q/51615689
score: 2
type: Comment

http://stackoverflow.com/q/51630353
has comment: http://stackoverflow.com/comment/90225031
has answer: http://stackoverflow.com/a/51630474
accepted answer: http://stackoverflow.com/a/51630474
has body: Here is my code: def factR(n): if n == 1: return n return n * factR(n-1) for i in range (11): print factR(i) The factR(n) function works fine. I have tested it. But after I have added the last two lines it returned a RuntimeError. May I know the reason?
tagged with: runtime-error
has comment: http://stackoverflow.com/comment/90225019
tagged with: python-2.7
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90224955
has answer: http://stackoverflow.com/a/51631135
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90225056
possible better answer: http://stackoverflow.com/a/51630476
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51630476
type: Question
has comment: http://stackoverflow.com/comment/90224921
has title: I tried to print out 1! to 10! but hit a runtimeError

http://stackoverflow.com/comment/90205818
type: AnswerComment
has text: OP specifically asks to use a class. Also `properties.get(propName, "Some indicator of failure")` is more pythonic than this solution. You may also want to check out json [`loads`](https://docs.python.org/3/library/json.html#json.loads) if a dictionary is actually desired.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51620055

configuration-files
type: Tag
tags question: http://stackoverflow.com/q/51499610
tag name: configuration-files
tags question: http://stackoverflow.com/q/51548114
tags question: http://stackoverflow.com/q/51576453
tags question: http://stackoverflow.com/q/51506216
tags question: http://stackoverflow.com/q/51542792

http://stackoverflow.com/comment/90004305
type: Comment
comment on: http://stackoverflow.com/q/51517759
has text: There's a difference between modifying data that you've just *imported* into your current file, and modifying a source file.
score: 0
type: QuestionComment

http://stackoverflow.com/a/51630757
has comment: http://stackoverflow.com/comment/90226550
has comment: http://stackoverflow.com/comment/90226732
type: Answer
has comment: http://stackoverflow.com/comment/90226423
downvote count: 0
answers question: http://stackoverflow.com/q/51630493
score: 1
has body: If I'm not wrong, you want to create new lists from buyers and prices? This might work - newlist = ['http://econpy.pythonanywhere.com/ex/00'+str(i)+'.html' for i in range(1, 6)] buyers, prices = [], [] for n in newlist: page = requests.get(n) tree = html.fromstring(page.content) buyers.append(tree.xpath('//div[@title="buyer-name"]/text()') prices.append(tree.xpath('//span[@class="item-price"]/text()') Now you can access buyers and prices outside the for loop. Let me know if I wrongly understood your question
upvote count: 1

http://stackoverflow.com/comment/90045562
has text: Unfortunately, this doesn't work for bredcrumbs. It adds this breadcrumb under the blue line. But the problem is upper right section line Odhlásiť / Logout etc
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51538828
type: Comment

http://stackoverflow.com/comment/90143628
comment on: http://stackoverflow.com/q/51589198
type: Comment
score: 1
has text: That looks fine. Perhaps you have some invisible characters in there. Try retyping that section from scratch.
type: QuestionComment

http://stackoverflow.com/q/51517968
tagged with: javascript
has comment: http://stackoverflow.com/comment/90012161
has comment: http://stackoverflow.com/comment/90007831
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/90008447
favorite count: 0
tagged with: python-3.x
has title: API response is NULL in Node but works fine in Python
has comment: http://stackoverflow.com/comment/90011586
tagged with: python
has answer: http://stackoverflow.com/a/51522458
has comment: http://stackoverflow.com/comment/90005136
accepted answer: http://stackoverflow.com/a/51522458
has comment: http://stackoverflow.com/comment/90008083
tagged with: node.js
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90008255
downvote count: 0
has body: I have to utilize node for this project and it is returning as null. 'use strict'; var https = require('https'); var pathString = '/api/SomeAPI/Start?Query=SomeData&amp;Account=USER\sean1234&amp;needed=0'; var request = https.get({ host: "some-host-path", path: pathString, header: {'Content-Type': 'application/json'} }, function(response) { var json = ""; response.on('data', function(chunk) { json += chunk; console.log("json is: " + json); }); response.on('end', function() { var jsonData = JSON.parse(json); var count = 0; var reply = ""; var keys; console.log("jsonData is: " +jsonData); console.log("Object.keys(jsonData) is: " + Object.keys(jsonData)); console.log("Object.keys(jsonData[0]) is: " + Object.keys(jsonData[0])); //console.log("Object.keys(jsonData[0].SomeData is: " + Object.keys(jsonData[0].SomeData)); //The previous line raises an Error: TypeError: Cannot convert undefined or null to object console.log("\njsonData[0].SomeData: " +jsonData[0].SomeData); count = jsonData[0].SomeData; console.log("JSON.stringify(count): " + JSON.stringify(count)); }); }); The logs from above node.js code are as follows: json is: [{"SomeData":null}] jsonData is: [object Object] Object.keys(jsonData) is: 0 Object.keys(jsonData[0]) is: SomeData jsonData[0].SomeData: null JSON.stringify(count): null As you can see, they are returning as null but when I tried to access the same API this time with Python, it returned the correct value as expected: import json import requests api_url = 'some-api-url' response = requests.get(api_url, headers={'Content-Type': 'application/json'}) print(response.status_code) loaded = json.loads(response.content.decode('utf-8')) print(loaded) logs from the above Python code: 200 [{'SomeData': 2893}] I have no choice but to utilize node for this project. Did I miss something? What seems wrong here? P.S. In case I did not make my point clear, I am using the exact same API for both Node and Python codes above.
type: Question

http://stackoverflow.com/comment/90183331
comment on: http://stackoverflow.com/q/51596908
has text: if i try to login it always returned to this page: http://signbank.a2hosted.com/accounts/login/?next=http%3A//signbank.a2hosted.com/
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90353187
has text: yes, ideally all site packages should be in ur script library. What issue are u facing now?
type: Comment
comment on: http://stackoverflow.com/a/51627156
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90247809
comment on: http://stackoverflow.com/a/51628415
score: 0
type: Comment
type: AnswerComment
has text: Cheers Amit, much appreciated.

http://stackoverflow.com/comment/90020595
has text: @bedford, Replace your cert_check with the one above. find which line that you think should be parsed as JSON, update the question with the data. question should be something like in this file (example of file contents) I'm trying to parse this line (enter example of line) as json. and get these fields. You don't have enough info in the question to answer it.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51508248

http://stackoverflow.com/comment/90299121
type: QuestionComment
comment on: http://stackoverflow.com/q/51620536
score: 0
has text: Where do you want to insert the 6 rows? Before the "data data data data" row , or after? Can you provide a picture of the **Expected** result of where the rows should appear?
type: Comment

http://stackoverflow.com/q/51634530
duplicate of: http://stackoverflow.com/q/9427163
tagged with: python-2.7
score: 0
has title: Removing a redundant dictionary from a list of dictionaries in Python
has answer: http://stackoverflow.com/a/51634607
accepted answer: http://stackoverflow.com/a/51634607
answer count: 1
linked to: http://stackoverflow.com/q/9427163
tagged with: redundancy
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
has body: Lets say I have a list of dictionaries: [{'county': 'Lincoln County', 'state': 'SD', 'fips': '46083'}, {'county': 'Minnehaha County', 'state': 'SD', 'fips': '46099'}, {'county': 'Minnehaha County', 'state': 'SD', 'fips': '46099'},...] In the above example, 2 of the dictionaries in this list are the same. What I want to do is check and see, by the fips key if the value. I know that I can use something like this to check in a dictionary, and in essence, create a new list of only unique entries: result = {} for key,value in dictionary.items(): if value not in result.values(): result[key] = value print result But I am having difficulty apply this to a list of dictionaries. What am I doing wrong here? for i in dictionary: for key,value in dictionary[i].items(): if value not in result.values(): result[key] = value
type: Question

http://stackoverflow.com/a/51554831
accepted answer of: http://stackoverflow.com/q/51554027
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51554027
has comment: http://stackoverflow.com/comment/90096259
has comment: http://stackoverflow.com/comment/90110735
has comment: http://stackoverflow.com/comment/90098265
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/90106163
downvote count: 0
has body: Your code will run successfully only for the first time, aka it will click on the 2nd page and then it will throw a Stale Element Reference Exception on this line - page.click() Now, why is that? Its because the page WebElement is nothing but a member of the pages list of your elements which you identified before clicking once. Since after clicking the pagination button once, the DOM has changed ,the reference to the element you earlier located no longer holds significance. To solve this, you need to keep finding the pagination button again and again everytime the DOM changes i.e. everytime you click on the pagination buttons. A simple solution would be to use your counter variable to iterate through your list. Here is the complete code - from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome(executable_path=r'//path to driver') driver.get("google url") driver.find_element_by_id("lst-ib").send_keys("search") driver.find_element_by_id("lst-ib").send_keys(Keys.ENTER) driver.maximize_window() pages=driver.find_elements_by_xpath("//*[@id='nav']/tbody/tr/td/a") counter=1 for page in pages: pages=driver.find_elements_by_xpath("//*[@id='nav']/tbody/tr/td/a") counter+=1 pages[counter].click() An alternate (and better) solution would be to identify the pagination buttons by their text - pages=driver.find_elements_by_xpath("//*[@id='nav']/tbody/tr/td/a") counter=2 #starting from 2 for page in pages: driver.find_element_by_xpath("//a[text() = '" + str(counter) + "']").click() counter+=1 You could also, try to press the 'Next' button: pages=driver.find_elements_by_xpath("//*[@id='nav']/tbody/tr/td/a") counter=2 #starting from 2 for page in pages: driver.find_element_by_xpath("//span[text()='Next']").click() counter+=1 EDIT - I fixed your final code. I renamed some variables so that you don't get confused and replaced your implicit waits with explicit waits. import unittest from selenium import webdriver from selenium.webdriver.s…
has comment: http://stackoverflow.com/comment/90098709
has comment: http://stackoverflow.com/comment/90096345
score: 4

http://stackoverflow.com/a/73289145
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51635873
has body: You have just put | book_title.title |, but it should be | book_title.title() |. I guess it will work when you put the parenthesis...
score: 2

http://stackoverflow.com/a/51597803
answers question: http://stackoverflow.com/q/51597604
upvote count: 0
type: Answer
has body: Use OrderedDict from collections import OrderedDict a = {'40,70': 'AAAAAA', '0,12': 'XXXXXXXX', '20,38': 'YYYYY'} b = OrderedDict(sorted(a.items()))
downvote count: 2
has comment: http://stackoverflow.com/comment/90161837
score: -2

http://stackoverflow.com/q/51636330
tagged with: python
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51649191
score: 8
upvote count: 9
type: UnansweredQuestion
tagged with: scikit-learn
has title: Classification report for regression (sklearn)
favorite count: 0
has comment: http://stackoverflow.com/comment/90237708
type: Question
has comment: http://stackoverflow.com/comment/90237378
has body: When you try to predict if something belongs to a certain class you can use the classification report from sklearn. However, this only works when the classes are categorical. Does anyone happen to figure out how to use the classification report from sklearn when you try to predict a value instead, like with a support vector regression machine or linear regression? I get the following error: ValueError: Unknown label type: (123 13.409091 760 16.593333 748 13.646667 334 13.828571) When trying: print("Classification report: ", classification_report(y_test, y_pred)) Here y_test is a column of a pandas DataFrame and y_pred is a numpy array. I tried converting the column into a numpy array, but then it gives the same error, but with the array. Does any know how to make the classification work to check the auc, precision/recall and f1-score for the prediction of a value (if there is a better way than sklearn, please do not hesitate to say so.)

http://stackoverflow.com/q/51490600
answer count: 0
score: 0
type: Question
has title: UnboundLocalError: local variable 'features' referenced before assignment
duplicate of: http://stackoverflow.com/q/423379
tagged with: dataframe
linked to: http://stackoverflow.com/q/9264763
tagged with: pandas
has comment: http://stackoverflow.com/comment/89949966
has comment: http://stackoverflow.com/comment/89949770
has comment: http://stackoverflow.com/comment/89949847
has body: I wanted to add a row to my dataframe using a function features = pd.read_csv("Work.csv") here is the function : def classify(Res,O,S,R,Rear,F,L,B): features = pd.DataFrame(np.array(Res,O,S,R,Rear,F,L,B), columns=['Resolution','OS','Storage','RAM', 'RearCamera','FrontCamera','LoudSpeaker','Battery'])\ .append(features, ignore_index=True) when I call the function as : classify(19283,"lolipop","fr","gg","ff",0,0,0) I get the following error : --------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) &lt;ipython-input-4-7c16987ef1b2&gt; in &lt;module&gt;() ----&gt; 1 classify(19283,"lolipop","fr","gg","ff",0,0,0) &lt;ipython-input-3-c620ec52544a&gt; in classify(Res, O, S, R, Rear, F, L, B) 1 def classify(Res,O,S,R,Rear,F,L,B): 2 ----&gt; 3 features = pd.DataFrame(np.array(Res,O,S,R,Rear,F,L,B), columns=['Resolution','OS','Storage','RAM','RearCamera','FrontCamera','LoudSpeaker','Battery']).append(features, ignore_index=True) UnboundLocalError: local variable 'features' referenced before assignment How do I fix it ?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89949889

http://stackoverflow.com/a/51635698
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51611327
has body: pxssh.login has an optional parameter original_prompt, which depending on your release is probably the pattern [#$], namely a hash or a dollar. This is described in the documentation as very optimistic and easily fooled. You should try setting one that is closer to your expected prompt, eg: if not session.login(ip, "username", "password", original_prompt=r'@[^:]+:.*?/#?'):
answers question: http://stackoverflow.com/q/51611327
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90365618
has comment: http://stackoverflow.com/comment/90363395
score: 1

http://stackoverflow.com/comment/90050141
comment on: http://stackoverflow.com/q/51541164
score: 0
type: QuestionComment
type: Comment
has text: Sure . I’ll add it

http://stackoverflow.com/q/51506508
has title: Python Kernel Died when using triple for loop containing requires_grad=True parameters (Pytorch)
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90011046
tagged with: spyder
tagged with: python
tagged with: kernel
has comment: http://stackoverflow.com/comment/90077737
has comment: http://stackoverflow.com/comment/89986999
answer count: 0
tagged with: pytorch
has body: I just want to store para_k in every position of COV matrix, where: para_k=torch.tensor([2.0],requires_grad=True). And because I want to update parameters by optimising a loss function later(omitted here), I have to add another for loop. Therefore, the whole code is as follows: import torch para_k=torch.tensor([2.0],requires_grad=True) for t in range(5): num_row=300 num_col=300 COV = torch.zeros((num_row,num_col)) for i in range(num_row): for j in range(num_col): COV[i,j]=para_k print('i= %d ,j= %d' % (i,j) ) This simple computation cannot be finished by Spyder!! Things can go well if I change nrow and ncol to be smaller than 100. If I use number larger than 100, it will send error message (sometimes even one iteration cannot be finished) that Kernel died and restarting: Spyder Kernel Died I even uninstall and install again my Anaconda and reinstall pytorch. I also tried to run Spyder as administrator, still got the error. I check the event of my system, the error is: ntdll.dll regarding to pythonw.exe. I listed pythonw.exe as exception of firewall, but still cannot solve the problem.
has comment: http://stackoverflow.com/comment/89993583
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/90085610
type: Question

django-rest-framework
tags question: http://stackoverflow.com/q/51532283
tags question: http://stackoverflow.com/q/51637070
tags question: http://stackoverflow.com/q/51549471
tags question: http://stackoverflow.com/q/51574998
tags question: http://stackoverflow.com/q/51636423
tags question: http://stackoverflow.com/q/51498016
tags question: http://stackoverflow.com/q/51578636
tags question: http://stackoverflow.com/q/51501231
tags question: http://stackoverflow.com/q/51531543
tags question: http://stackoverflow.com/q/51551402
tags question: http://stackoverflow.com/q/51575053
tags question: http://stackoverflow.com/q/51528096
tags question: http://stackoverflow.com/q/51509833
type: Tag
tags question: http://stackoverflow.com/q/51588913
tags question: http://stackoverflow.com/q/51513455
tags question: http://stackoverflow.com/q/51583756
tags question: http://stackoverflow.com/q/51532492
tags question: http://stackoverflow.com/q/51593552
tags question: http://stackoverflow.com/q/51558745
tags question: http://stackoverflow.com/q/51549678
tags question: http://stackoverflow.com/q/51623878
tags question: http://stackoverflow.com/q/51510617
tags question: http://stackoverflow.com/q/51575972
tags question: http://stackoverflow.com/q/51518682
tags question: http://stackoverflow.com/q/51537874
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/51554553
tags question: http://stackoverflow.com/q/51533744
tags question: http://stackoverflow.com/q/51549124
tags question: http://stackoverflow.com/q/51530578
tags question: http://stackoverflow.com/q/51588325
tags question: http://stackoverflow.com/q/51526190
tags question: http://stackoverflow.com/q/51524441
tags question: http://stackoverflow.com/q/51524591
tags question: http://stackoverflow.com/q/51622311
tags question: http://stackoverflow.com/q/51549941
tags question: http://stackoverflow.com/q/51598930

http://stackoverflow.com/a/51575875
has comment: http://stackoverflow.com/comment/90137547
downvote count: 0
answers question: http://stackoverflow.com/q/51574829
type: Answer
has comment: http://stackoverflow.com/comment/90117586
has comment: http://stackoverflow.com/comment/90117454
upvote count: 1
has body: The optimal rectangle is such that it touches other rectangles on four sides (otherwise you can enlarge it). So you will restrict the search to the available coordinates. A brute-force solution can work as follows: list all abscissas and ordinates (including the outer limits) and sort them increasingly; for every (abscissa, ordinate) combination, find the largest rectangle having this point as its top-left corner, as follows: for every (abscissa', ordinate') combination such that abscissa' > abscissa and ordinate' > ordinate, use this point as the lower-right corner of the rectangle and test as follows: for every given rectangle, check if it overlaps the rectangle under test; if there is an overlap, ignore this candidate. if there were no overlaps, the candidate is accepted; compute its area and keep the largest so far. For N rectangles, this process can take O(N^5) operations, so it is only usable for very small N. You can speed up the process by replacing every abscissa, ordinate by its index and representing the rectangles in a bitmap. You paint every reduced rectangle in this bitmap. Then when you want to test a candidate rectangle, try the longest run of empty pixels to the right; then try the next row and find the longest run of empty pixels which is not longer than the previous; and so on to the bottom of the bitmap (this ensures that you try all possible rectangles). Every time you try a rectangle, retrieve the original coordinates and compute the true area. Below, the original rectangles, then the compressed bitmap representation and the pixels tried starting from the marked one (four rectangles are tried).
score: 1

http://stackoverflow.com/q/51564723
has title: Running Custom Shell Command from Python Script inside Docker Container
has answer: http://stackoverflow.com/a/51565158
has body: I am trying to run a custom shell command from a python script inside a docker container and capture the output for later use. My code is: def live_who_is(domain): live_data = subprocess.check_output('whois {}'.format(domain), shell=True, stderr=subprocess.STDOUT) print(live_data) and I get this error when I run it: Traceback (most recent call last): File "who_is_compare_script.py", line 158, in &lt;module&gt; live_who_is('google.com') File "who_is_compare_script.py", line 149, in live_who_is live_data = subprocess.check_output('whois {}'.format(domain), shell=True, stderr=subprocess.STDOUT) File "/usr/local/lib/python2.7/subprocess.py", line 223, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command 'whois google.com' returned non-zero exit status 1 If you replace the command with "ls -a" or even "ls {}".format("-a") it works.
upvote count: 1
has comment: http://stackoverflow.com/comment/90096464
type: Question
tagged with: docker
tagged with: bash
has comment: http://stackoverflow.com/comment/90096388
answer count: 1
downvote count: 0
score: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90096476

http://stackoverflow.com/comment/89978797
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51504938
has text: yeah, one thing for sure - don't change the collection while you are iterating over it

http://stackoverflow.com/a/51605230
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51605154
has body: Just a guess: if isinstance(line_value, str): row.append('{0}'.format(line_value.encode('utf-8'))) If the value is str you don't need to encode it in Python 3 - all strings in Python 3 are unicode. You probably should check if the value is an instance of bytes instead. if isinstance(line_value, bytes): row.append('{0}'.format(line_value.decode('utf-8'))) [update] No, that line is checking if it is string versus number... so str is correct – Luluperam Are you sure? Lets say line_value is the string "foo": line_value = 'foo' Now try this: &gt;&gt;&gt; row = [] &gt;&gt;&gt; if isinstance(line_value, str): ... row.append('{0}'.format(line_value.encode('utf-8'))) &gt;&gt;&gt; print(row) ["b'foo'"] That is the source of your bytes literal in the CSV file. Now lets try the version I so kindly suggested before dismissing it: &gt;&gt;&gt; line_value = b'foo' &gt;&gt;&gt; row = [] &gt;&gt;&gt; if isinstance(line_value, bytes): ... row.append('{0}'.format(line_value.decode('utf-8'))) &gt;&gt;&gt; print(row) ['foo']
has comment: http://stackoverflow.com/comment/90176266
downvote count: 0
has comment: http://stackoverflow.com/comment/90176371
has comment: http://stackoverflow.com/comment/90175969

http://stackoverflow.com/comment/90074996
score: 1
has text: Did you change the `User` model? Since right now the Django `User` is pointing to the Django `Group`, the defined `Group`s here are not relevant (according to Django).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51554030

http://stackoverflow.com/comment/90220965
comment on: http://stackoverflow.com/q/51628114
type: Comment
type: QuestionComment
score: 0
has text: @WillemVanOnsem in any case my bigger problem is the for loop, which I'm not sure how to solve with faster methods.

http://stackoverflow.com/a/51603627
has comment: http://stackoverflow.com/comment/90215871
type: AcceptedAnswer
type: Answer
has body: Compilation of answers given in the comments Answers specific to my code: As vorticity mentioned my code in itself was not using the numpy, and scipy packages to the fullest extent. In regards to Bessel, function 'royvib' mentions using using .jo from scipy rather than .jv. Calling the special Bessel function jv. is much more computationally expensive, especially since I knew that I would be using a zeroth order bessel function for many of my declarations the minor change from jv -> j0 solved speed up the process. In addition, I declared variables outside the loop to prevent expensive calls to searching for my appropriate functions. Example below. Before for i in range(SomeLength): some_var = scipy.special.jv(1,coeff) After Bessel = scipy.special.jv for i in range(SomeLength): some_var = Bessel(1,coeff) Storing the function saved time by not using the dot ('.') the command to look through the libraries every single loop. However keep in mind this does make python less readable, which is the main reason I choose to do this project in python. I do not have an exact amount of time this step cut from my process. Fortran specific: Since I was able to improve my python code I did not go this route an lack of specifics, but the general answer as stated by 'High Performance Mark' is that yes there are libraries that have been made to handle Bessel functions in Fortran. If I do port my code over to Fortran or use f2py to mix Fortran and python I will update this answer accordingly.
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51565122
answers question: http://stackoverflow.com/q/51565122
has comment: http://stackoverflow.com/comment/90179688
upvote count: 1

http://stackoverflow.com/q/51526805
has comment: http://stackoverflow.com/comment/90023034
type: Question
has comment: http://stackoverflow.com/comment/90024767
has title: How to make this function using apply
tagged with: dataframe
tagged with: apply
has body: I am trying to eval the Herfindahl index using apply. I have done this by transforming the dataframe into a numpy matrix. In fact, the function evalHerfindahlIndex is working well and it evaluates the correct value of the Herfindahl index for each line. However, when I try to make the same function (evalHerfindahlIndexForDF) to use apply I get a very strange error: ValueError: ("No axis named 1 for object type &lt;class 'pandas.core.series.Series'&gt;", 'occurred at index A') The entire code is this: import pandas as pd import numpy as np import datetime def evalHerfindahlIndex(x): soma=np.sum(x,axis=1) y=np.empty(np.shape(x)) for line in range(len(soma)): y[line,:]=np.power(x[line,:]/soma[line],2.0) hhi=np.sum(y,axis=1) return hhi def evalHerfindahlIndexForDF(x): soma=x.sum(axis=1) def creatingDataFrame(): dateList=[] dateList.append(datetime.date(2002,1,1)) dateList.append(datetime.date(2002,2,1)) dateList.append(datetime.date(2002,1,1)) dateList.append(datetime.date(2002,1,1)) dateList.append(datetime.date(2002,2,1)) raw_data = {'Date': dateList, 'Company': ['A', 'B', 'B', 'C' , 'C'], 'var1': [10, 20, 30, 40 , 50]} df = pd.DataFrame(raw_data, columns = ['Date','Company', 'var1']) df.loc[1, 'var1'] = np.nan return df if __name__=="__main__": df=creatingDataFrame() print(df) dfPivot=df.pivot(index='Date', columns='Company', values='var1') #print(dfPivot) dfPivot=dfPivot.fillna(0) dfPivot['Date']=dfPivot.index listOfCompanies=list(set(df['Company'])) Pivot=dfPivot.as_matrix(columns=listOfCompanies) print(evalHerfindahlIndex(Pivot)) print(dfPivot) print(dfPivot[listOfCompanies].apply(evalHerfindahlIndexForDF)) The dataframe that I am using is dfPivot: Company A B C Date Date 2002-01-01 10.0 30.0 40.0 2002-01-01 2002-02-01 0.0 0.0 50.0 2002-02-01 The correct values of the Herfindahl index evaluated using evalHerfindahlIndex is: [0.40625 1. ] I would like to return this as an extra column of the dataframe dfPivot.
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/90023147
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51528115
downvote count: 0
score: 1

http://stackoverflow.com/comment/90175430
score: 1
has text: priority=-100 on server retry requests will put it at the end of the queue and process your other requests first - you want to check your server as rarely as possible and prioritise crawling instead, right? You can send something to your server using `POST` type requests, simply set `Request(url, method="POST", data='{"foo":"bar"}')` for example.
type: AnswerComment
comment on: http://stackoverflow.com/a/51586754
type: Comment

http://stackoverflow.com/q/51602859
answer count: 1
has answer: http://stackoverflow.com/a/51604629
accepted answer: http://stackoverflow.com/a/51604629
tagged with: python
type: AnsweredQuestion
tagged with: linear-regression
tagged with: machine-learning
has body: I've been working on Linear regression problem using Tensorflow. I get a curve pred_y as flat. How should I fit my curve with training examples of observations? Here is my tensorflow code: # coding: utf-8 # In[146]: import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import pandas as pd # In[147]: train_features = pd.read_csv("training_set_X.csv", delimiter=',').as_matrix() train_observations = pd.read_csv("training_set_Y.csv", delimiter=',').as_matrix() print("Training features: ") train_features # In[148]: print("Training observations: ") train_observations # In[149]: print("Shape of training features = ", train_features.shape) print("Shape of training observations = ", train_observations.shape) # In[150]: # Normalization of training data. train_features_stddev_arr = np.std(train_features, axis=0) train_features_mean_arr = np.mean(train_features, axis=0) normalized_train_features = (train_features - train_features_mean_arr) / train_features_stddev_arr # In[151]: print("Training features: Standard deviation....") train_features_stddev_arr # In[152]: print("Training featues: Mean....") train_features_mean_arr # In[153]: print("Normalized training features....") normalized_train_features # In[154]: # Layer parameters. n_nodes_h11 = 5 n_nodes_h12 = 5 n_nodes_h13 = 3 no_features = 17 learning_rate = 0.01 epochs = 200 # In[155]: cost_history = [] # In[156]: X = tf.placeholder(tf.float32, name='X') Y = tf.placeholder(tf.float32, name='Y') # In[157]: # Defining weights and biases. first_weight = tf.Variable(tf.random_normal([no_features, n_nodes_h11], stddev=np.sqrt(2/no_features))) second_weight = tf.Variable(tf.random_normal([n_nodes_h11, n_nodes_h12], stddev=np.sqrt(2/n_nodes_h11))) third_weight = tf.Variable(tf.random_normal([n_nodes_h12, n_nodes_h13], stddev=np.sqrt(2/n_nodes_h12))) output_weight = tf.Variable(tf.random_normal([n_nodes_h13, 1], stddev=np.sqrt(2/n_nodes_h13))) # In[158]: first_bias = tf.Variable(tf.random_uniform([n_nodes_h11], …
tagged with: tensorflow
type: Question
has title: Tensorflow - Linear Regression: Not proper able to do proper plotting
score: 0

http://stackoverflow.com/a/51577605
accepted answer of: http://stackoverflow.com/q/51576982
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51576982
type: Answer
upvote count: 1
has body: Here is main problem need previous mean value if multiple 0 per column, so realy problematic create vectorized solution: def f(x): for i, v in enumerate(x): if v == 0: x.iloc[i] = x.iloc[:i+1].mean() return x df1 = df.astype(float).apply(f) print (df1) A B C D E 0 1.0 2.00 3.000000 0.0 2.0 1 2.0 1.00 7.000000 1.0 1.0 2 3.0 4.00 3.333333 3.0 1.0 3 1.5 1.75 3.000000 4.0 3.0 Better solution: #create indices of zero values to helper DataFrame a, b = np.where(df.values == 0) df1 = pd.DataFrame({'rows':a, 'cols':b}) #for first row is not necessary count means df1 = df1[df1['rows'] != 0] print (df1) rows cols 1 1 1 2 2 2 3 2 4 4 3 0 5 3 1 #loop by each row of helper df and assign means for i in df1.itertuples(): df.iloc[i.rows, i.cols] = df.iloc[:i.rows+1, i.cols].mean() print (df) A B C D E 0 1.0 2.00 3.000000 0 2.0 1 2.0 1.00 7.000000 1 1.0 2 3.0 4.00 3.333333 3 1.0 3 1.5 1.75 3.000000 4 3.0 Another similar solution (with mean of all pairs): for i, j in zip(*np.where(df.values == 0)): df.iloc[i, j] = df.iloc[:i+1, j].mean() print (df) A B C D E 0 1.0 2.00 3.000000 0.0 2.0 1 2.0 1.00 7.000000 1.0 1.0 2 3.0 4.00 3.333333 3.0 1.0 3 1.5 1.75 3.000000 4.0 3.0
score: 1
has comment: http://stackoverflow.com/comment/90121189

http://stackoverflow.com/comment/90027154
type: Comment
has text: @aydow it still returns error
type: QuestionComment
comment on: http://stackoverflow.com/q/51529415
score: 0

http://stackoverflow.com/q/51541302
has body: It should be a easy task, but I can't find a way how to pass a pointer of a scalar value to a CFFI function within a Numba function. Passing a pointer to an array works without problems using ffi.from_buffer. Example function import cffi ffi = cffi.FFI() defs="void foo_f(int a,double *b);" ffi.cdef(defs, override=True) source=""" #include &lt;stdio.h&gt;; void foo_f(int a,double *b){ printf("%i",a); printf(" "); printf("%f",b[0]); } """ ffi.set_source(module_name="foo",source=source) ffi.compile() Passing a pointer to an array import numpy as np import numba as nb import cffi ffi = cffi.FFI() import numpy as np import ctypes import foo nb.cffi_support.register_module(foo) foo_f = foo.lib.foo_f @nb.njit() def Test(a,b): a_wrap=np.int32(a) #This works for an array b_wrap=ffi.from_buffer(b.astype(np.float64)) foo_f(a_wrap,b_wrap) a=64. b=np.ones(5) Test(a,b) This works without problems, but how can I modify the Test function to take a scalar value b=5. without modifying the CFFI-function itself?
has title: How to wrap a CFFI function in Numba taking Pointers
tagged with: performance
upvote count: 5
has answer: http://stackoverflow.com/a/59538114
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
score: 5
tagged with: numba
tagged with: python
accepted answer: http://stackoverflow.com/a/59538114
tagged with: python-cffi
answer count: 1
tagged with: numpy

http://stackoverflow.com/a/51582935
score: 0
answers question: http://stackoverflow.com/q/51582048
type: Answer
has body: I explain what I know, Suppose you are running the Django server. you requested the Django server from the browser, The first Django request goes to urls.py -> views.py -> models.py.

http://stackoverflow.com/q/51603430
tagged with: regex
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: parameters
has comment: http://stackoverflow.com/comment/90172928
type: Question
has title: django how to pass parameter from url to view
answer count: 1
has body: I'm trying to append a parameter no_rep at the end of my question url as a signal to show different views. I'm using Django 1.8 and following the url pattern from askbot. This is the url.py: url( (r'^%s(?P&lt;id&gt;\d+)/' % QUESTION_PAGE_BASE_URL.strip('/') + r'(%s)?' % r'/no-rep:(?P&lt;no_rep&gt;\w+)'), views.readers.question, name='question' ), I'm trying to show different displays depending on the value of no_rep in my url. This is the view: def question(request, id, no_rep): if no_rep == '1': request.session['no_rep'] = True else: request.session['no_rep'] = False I couldn't find information on what the +,%,? do, which is probably where the problem is. Could someone explain how the regex work with the base url? When I enter the url http://localhost:8000/question6/test-question/no_rep:1, request.session['no_rep'] should be set to true, but it's not. What am I missing?
has comment: http://stackoverflow.com/comment/90172864
has answer: http://stackoverflow.com/a/51603698
score: 0
tagged with: url

http://stackoverflow.com/comment/90184258
score: 0
type: AnswerComment
has text: Can you get the trace of `pip show pandas`? and check `which python` too.
type: Comment
comment on: http://stackoverflow.com/a/51609145

http://stackoverflow.com/a/51675571
answers question: http://stackoverflow.com/q/51632468
type: Answer
accepted answer of: http://stackoverflow.com/q/51632468
has comment: http://stackoverflow.com/comment/90377648
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90323428
upvote count: 2
has comment: http://stackoverflow.com/comment/90366060
type: AcceptedAnswer
has body: I am not too familiar with how xlwings works but due to the intricacies of how the logging module works, I would recommend not creating loggers in the global scope of your modules, but instead lazy-create them as needed. In many cases, logs created in the global scope are created before any code is run. Then, some other code re-configures logging which causes per-existing logs to be removed and their configuration to be forgotten. This is why the disable_existing_loggers=False argument exists for logging.config functions (e.g. https://docs.python.org/2/library/logging.config.html#logging.config.fileConfig). To see if this is the case, I would recommend moving your log definition code to a function, and calling it as needed, for example: import logging # app.py _logger = None def get_logger(): global _logger if _logger is None: _logger = logging.getLogger('app') _logger.setLevel(logging.DEBUG) # ... continue to define your logger ... return _logger Then in your function: from app import get_logger import xlwings as xw @xw.sub def test(): logger = get_logger() logger.debug('test') logger.info('test') logger.warning('test') It should be noted that this is not the "cleanest" way to use logging (usually this should not be required) but if the problem is really some other module messing with the logging configuration, it might be difficult to work around.

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

http://stackoverflow.com/comment/90075769
has text: Awesome... that's what i expected. Really thankful for understanding my problem and helping with correct solution.
score: 0
comment on: http://stackoverflow.com/a/51541718
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90292461
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51588199
type: Comment
has text: Or use itertools `[len(list(b)) for a, b in itertools.groupby(l)]`

http://stackoverflow.com/q/51567356
score: 8
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90101274
tagged with: python
has answer: http://stackoverflow.com/a/51567392
has comment: http://stackoverflow.com/comment/90101225
tagged with: isinstance
downvote count: 0
has title: List of classinfo Types
has comment: http://stackoverflow.com/comment/90101493
upvote count: 8
has comment: http://stackoverflow.com/comment/90101242
type: Question
has body: All I'm looking for is a list of possible values of classinfo since the documentation doesn't provide one and I can't seem to find one anywhere else online, let alone SO.
tagged with: class
tagged with: types
answer count: 1

http://stackoverflow.com/comment/90147699
comment on: http://stackoverflow.com/q/51589897
has text: Currently only for email notifications into views.py. I will have to recode it to make code reusable. Thank you for your help, I'm glad the `models.py` approach made sense :-)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51571565
type: Answer
has body: You way to easily fill nans is to use fillna function. In your case, if you have the dfs as (notice the indexes) unique_col Measure 0 944537 NaN 1 7811403 NaN 2 8901242114307 1.0 unique_col Measure 0 944537 18.0 1 7811403 12.0 2 8901242114307 17.5 You can simply &gt;&gt;&gt; df.fillna(df2) unique_col Measure 0 944537 18.0 1 7811403 12.0 2 8901242114307 1.0 If indexes are not the same as the above, you can set them to be the same and use the same function df = df.set_index('unique_col') df.fillna(df2.set_index('unique_col'))
answers question: http://stackoverflow.com/q/51571350
upvote count: 20
score: 20
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51571350

http://stackoverflow.com/comment/90260863
comment on: http://stackoverflow.com/q/51630427
type: Comment
type: QuestionComment
score: 0
has text: @ImportanceOfBeingErnest first code is partially working in the sense that it is able to generate plots. But currently I am looking for ways to make matplotlib to output images of the same size (pixels width by pixels height)

http://stackoverflow.com/comment/89950049
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51490738
has text: @abarnert, unfortunately OP is not doing with integer, so OP can't use 3 args `pow`.
score: 0

http://stackoverflow.com/comment/90109863
type: QuestionComment
has text: Cool thanks for your help.
score: 0
comment on: http://stackoverflow.com/q/51558747
type: Comment

jenkins-pipeline
tags question: http://stackoverflow.com/q/51637438
tags question: http://stackoverflow.com/q/51595630
type: Tag
tag name: jenkins-pipeline

http://stackoverflow.com/a/51620767
has comment: http://stackoverflow.com/comment/90207124
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51620658
upvote count: 2
has body: You are looking for a left_only merge. merged = pd.merge(df_a,df_b, how='outer', indicator=True) merged.loc[merged['_merge'] == 'left_only']'Animal', 'Name' Output Animal Name 1 dog henry 7 lion lima Explanation: merged = pd.merge(df_a,df_b, how='outer', indicator=True) Gives: Animal Name _merge 0 dog john both 1 dog henry left_only 2 dog betty both 3 dog smith both 4 cat charlie both 5 fish tango both 6 lion foxtrot both 7 lion lima left_only The extra animals are in df_a only, which is denoted by left_only.
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90207289
accepted answer of: http://stackoverflow.com/q/51620658
has comment: http://stackoverflow.com/comment/90207554

http://stackoverflow.com/comment/90056472
type: Comment
type: QuestionComment
score: 0
has text: https://stackoverflow.com/questions/50421287/pip-cannot-uninstall-ipython-it-is-a-distutils-installed-project-and-thus-w
comment on: http://stackoverflow.com/q/51544141

http://stackoverflow.com/comment/90217916
comment on: http://stackoverflow.com/a/51605292
type: AnswerComment
score: 0
has text: still can't do it :) 11 hrs remain
type: Comment

http://stackoverflow.com/comment/90210771
type: AnswerComment
comment on: http://stackoverflow.com/a/51621144
score: 0
type: Comment
has text: When I try to apply this solution, I keep getting an `IndexError: list index out of range.` This is more of a horizontal approach, whereas I am reading through a spreadsheet and my `i` = a row and `j` is more of a vertical column index value. Also my spreadsheet cell values will be like `sheet.cell_value(row, 1)` and `sheet.cell_value(row, 1)`. I'll have to work with this a bit, but I think this is on the right track. It seems like an indexing issue on my end.

http://stackoverflow.com/comment/108710703
comment on: http://stackoverflow.com/a/51808972
type: Comment
has text: @Alec is correct. gspread has been using google-auth since version 3.4.0.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51638891
answers question: http://stackoverflow.com/q/51638837
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/51638837
has body: Change mode='max' to mode='min' in ModelCheckpoint since you are minimizing loss and not maximizing it. See documentation in https://keras.io/callbacks/

http://stackoverflow.com/q/51624039
has comment: http://stackoverflow.com/comment/90213237
has title: Playing sound and a program
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51624148
accepted answer: http://stackoverflow.com/a/51624148
has comment: http://stackoverflow.com/comment/90213168
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90213199
tagged with: winsound
downvote count: 3
linked to: http://stackoverflow.com/q/8804830
type: Question
has comment: http://stackoverflow.com/comment/90213398
has body: What I want to do is get an audio file to play while a def (function) is running. I've looked it up and seen that threading works but it is wayyyy to complicated for me to work out. Is there a way you guys can explain it to me? I was using winsound to play the audio file, and SND_FILENAME.
score: -2
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90213369
upvote count: 1
answer count: 1

thread-safety
tags question: http://stackoverflow.com/q/51547183
tag name: thread-safety
type: Tag

http://stackoverflow.com/q/51503458
answer count: 1
linked to: http://stackoverflow.com/q/8686225
has body: I am calling a method on dynamodb's query command, and the property FilterExpression is optional, or it takes a non-empty string. Is there a way for me to only pass FilterExpression as a parameter only when the length of filter &gt; 0? def select(filter='') response = self.dynamodbConnection.query( FilterExpression=filter # Other arguments here )
duplicate of: http://stackoverflow.com/q/8686225
has answer: http://stackoverflow.com/a/51503515
type: AnsweredQuestion
has title: Pass argument only when length is greater than zero
tagged with: boto3
type: Question
accepted answer: http://stackoverflow.com/a/51503515
tagged with: python
score: 0
tagged with: amazon-dynamodb

http://stackoverflow.com/a/51636974
answers question: http://stackoverflow.com/q/51635552
has body: We need two functions from the os module from os import walk from os.path import join We need a starting point dir = '/your/top/directory' walk returns a generator, iterating on it at each step we have the path of the current directory, the list of directories and the list of files BUT we don't want to iterate and are interested only in the list of directories in the current directory, hence dirs_l1 = next(walk(dir))[1] note that, having to deal with a generator, the above is not too wasteful... Now we have an inner loop on the subdirectories of level 1 (l1 sd, the sd contained in the root) to create a list of sets of directories of level 2, to be unpacked and passed to set.intersection, so that in dirs_l2 we eventually have a set of all the directories of level 2 that are present in every directory of level 1 dirs_l2 = set.intersection(*[set(next(walk(join(dir, d)))[1]) for d in dirs_l1]) We make a loop on these inner directories, present in every l1 sd, and using the all builtin we check that, for every l1 sd all the l2 sd are empty, in that case we print the name of the l2 subdirectory that is always empty for d2 in dirs_l2: if all(next(walk(join(dir, d1, d2)))[1:] == ([],[]) for d1 in dirs_l1): print(d2) An example $ cat A.py from os import walk from os.path import join dir = './A' dirs_l1 = next(walk(dir))[1] dirs_l2 = set.intersection(*[set(next(walk(join(dir, d)))[1]) for d in dirs_l1]) for d2 in dirs_l2: if all(next(walk(join(dir, d1, d2)))[1:] == ([], []) for d1 in dirs_l1): print(d2) $ tree A A ├── A │ ├── 1 │ │ └── a │ ├── 2 │ │ └── b │ └── 3 ├── B │ ├── 1 │ │ └── a │ ├── 2 │ │ └── b │ └── 3 ├── C │ ├── 1 │ │ └── a │ ├── 2 │ │ └── b │ └── 3 └── D ├── 1 │ └── a ├── 2 │ └── b └── 3 $ python A.py 3 $
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51635552

http://stackoverflow.com/comment/89988692
score: 0
type: Comment
type: QuestionComment
has text: Did you verify, that on Nasdaq for Tesla are valid data? I tried it and I have the suspicion, that for mmm there are valid data but for Tesla, there aren't. So there is nothing for downloading. Look at Tesla manually and check it up.
comment on: http://stackoverflow.com/q/51509600

http://stackoverflow.com/comment/90157331
has text: This is not a specific enough question. What kind of data is your input formatted as, and what kind of format would you want from your output
type: Comment
comment on: http://stackoverflow.com/q/51595736
type: QuestionComment
score: 1

http://stackoverflow.com/q/51617433
linked to: http://stackoverflow.com/q/27256070
tagged with: pycharm
score: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/51618308
has body: Iam new to Robot framework . I have installed below. Python 3.7.0 Pycharm 2018.1.4 community edition Robot framework 3.0.4 robotframework==3.0.4 robotframework-selenium2library==3.0.0 robotframework-seleniumlibrary==3.1.1 I also set the environment variable --> path as "C:\Python37-32\Scripts;C:\Python37-32 " In pycharm Created a new Demo.robot file . In Pycharm --> tools-->External tools--> set the 'program' as 'C:\Python37-32\Scripts\robot.bat' and 'working directory' as 'C:\Python37-32\Scripts' . In Pycharm 'Run/debug configuration'-->'Script path' set as 'C:\Users\inmj\PycharmProjects\PycharmProject1\Demo.robot' 'Python Interpreter' as 'Python 3.7 (PycharmProject1)' Tried running below script in Pycharm *** Settings *** Documentation sample Library SeleniumLibrary It gives me error as below C:\Python37-32\python.exe C:/Users/inmj/PycharmProjects/PycharmProject1/Demo.robot File "C:/Users/inmj/PycharmProjects/PycharmProject1/Demo.robot", line 1 *** Settings *** ^ SyntaxError: invalid syntax Could anyone please help me ?
upvote count: 1
type: Question
tagged with: robotframework
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: Unable to Run .Robot file in Pycharm windows
has comment: http://stackoverflow.com/comment/90228732
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90354626
type: Comment
has text: Yest, I'm looking to pass parameters to onTimeoutCancel Function
comment on: http://stackoverflow.com/a/51561744
type: AnswerComment
score: 0

http://stackoverflow.com/q/51562377
linked to: http://stackoverflow.com/q/26473681
has comment: http://stackoverflow.com/comment/90093070
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/90096696
accepted answer: http://stackoverflow.com/a/51688068
upvote count: 2
has comment: http://stackoverflow.com/comment/90093060
has comment: http://stackoverflow.com/comment/90093400
has comment: http://stackoverflow.com/comment/90094359
has comment: http://stackoverflow.com/comment/90094017
type: Question
has body: I am trying to install awsebcli in a virtualenv like this: pip install awsebcli --upgrade --user Installation fails with the following error: Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-dpxu8m6m/awsebcli/setup.py", line 48, in <module> long_description=open('README.rst').read() + open('CHANGES.rst').read(), File "/home/rashik/Documents/Bhalo/python/lib/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 7198: ordinal not in range(128) ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-dpxu8m6m/awsebcli/ I am using arch linux. I have these packages installed in my virtualenv: awscli 1.15.66 blessed 1.15.0 botocore 1.10.65 cement 2.10.12 certifi 2018.4.16 chardet 3.0.4 colorama 0.3.9 docker-py 1.10.6 docker-pycreds 0.3.0 dockerpty 0.4.1 docopt 0.6.2 docutils 0.14 idna 2.7 jmespath 0.9.3 pathspec 0.5.6 pip 18.0 pyasn1 0.4.4 python-dateutil 2.7.3 PyYAML 3.13 requests 2.19.1 rsa 3.4.2 s3transfer 0.1.13 semantic-version 2.6.0 setuptools 40.0.0 six 1.11.0 texttable 1.4.0 urllib3 1.23 wcwidth 0.1.7 websocket-client 0.48.0 wheel 0.31.1 Note: None of the answers for this question-PIP Install Numpy throws an error "ascii codec can't decode byte 0xe2" works for me.
has comment: http://stackoverflow.com/comment/90093998
has answer: http://stackoverflow.com/a/51688068
has title: AWS EB CLI installation fails with "python setup.py egg_info" failed with error code 1"
tagged with: ebcli
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/90093612
has comment: http://stackoverflow.com/comment/90092841
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90097173
has comment: http://stackoverflow.com/comment/90097400
tagged with: amazon-elastic-beanstalk
favorite count: 0
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/90097267

http://stackoverflow.com/comment/90161837
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51597803
type: AnswerComment
has text: it doesn't sort numerically

http://stackoverflow.com/a/51639184
type: Answer
answers question: http://stackoverflow.com/q/51638870
has comment: http://stackoverflow.com/comment/90247955
accepted answer of: http://stackoverflow.com/q/51638870
has body: There is a simple way to do that if you're using numpy: variance = tensors.var(axis=3)
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90248210

http://stackoverflow.com/q/51509537
has body: I am trying out a locust tutorial. I am having an error Objects/dictobject.c:1439: bad argument to internal function when I am trying to run locust -f locustfile.py --host=http://localhost:8080 . Server is running already. Error snippet: ... [2018-07-25 08:55:06,330] CRMs-iMac/INFO/locust.main: Starting web monitor at *:8089 [2018-07-25 08:55:06,330] CRMs-iMac/ERROR/stderr: Traceback (most recent call last): [2018-07-25 08:55:06,330] CRMs-iMac/ERROR/stderr: File "/Users/crmonlinegraph/.virtualenvs/venvpy3.7/bin/locust", line 11, in &lt;module&gt; [2018-07-25 08:55:06,331] CRMs-iMac/ERROR/stderr: [2018-07-25 08:55:06,331] CRMs-iMac/ERROR/stderr: sys.exit(main()) [2018-07-25 08:55:06,331] CRMs-iMac/ERROR/stderr: [2018-07-25 08:55:06,331] CRMs-iMac/ERROR/stderr: File "/Users/crmonlinegraph/.virtualenvs/venvpy3.7/lib/python3.7/site-packages/locust/main.py", line 430, in main [2018-07-25 08:55:06,331] CRMs-iMac/ERROR/stderr: [2018-07-25 08:55:06,331] CRMs-iMac/ERROR/stderr: main_greenlet = gevent.spawn(web.start, locust_classes, options) [2018-07-25 08:55:06,331] CRMs-iMac/ERROR/stderr: [2018-07-25 08:55:06,331] CRMs-iMac/ERROR/stderr: File "src/gevent/greenlet.py", line 538, in gevent._greenlet.Greenlet.spawn [2018-07-25 08:55:06,332] CRMs-iMac/ERROR/stderr: File "src/gevent/greenlet.py", line 213, in gevent._greenlet.Greenlet.__init__ [2018-07-25 08:55:06,332] CRMs-iMac/ERROR/stderr: File "src/gevent/_hub_local.py", line 80, in gevent.__hub_local.get_hub_noargs [2018-07-25 08:55:06,332] CRMs-iMac/ERROR/stderr: File "/Users/crmonlinegraph/.virtualenvs/venvpy3.7/lib/python3.7/site-packages/gevent/hub.py", line 390, in __init__ [2018-07-25 08:55:06,332] CRMs-iMac/ERROR/stderr: [2018-07-25 08:55:06,332] CRMs-iMac/ERROR/stderr: WaitOperationsGreenlet.__init__(self, None, None) [2018-07-25 08:55:06,332] CRMs-iMac/ERROR/stderr: [2018-07-25 08:55:06,333] CRMs-iMac/ERROR/stderr: File "src/gevent/_greenlet_primitives.py", line 42, in gevent.__greenlet_primitives.TrackedRawGreenl…
has comment: http://stackoverflow.com/comment/90007964
type: Question
score: 0
has title: locust bad argument to internal function
tagged with: python
tagged with: locust
has comment: http://stackoverflow.com/comment/90026615
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90107997
type: AnswerComment
comment on: http://stackoverflow.com/a/51566601
score: 0
type: Comment
has text: Thank you for your help. :ref: does not exactly what I would like to have, but it provides a link to the documentation and that is at the moment sufficient for me. You are right, the style is different: The theme I use (sphinxdoc) renders :ref: a "just another link" and :py:class: as "external link", they have different colors. Modifying the docs? Good idea, I will think about it.

http://stackoverflow.com/a/51628208
has comment: http://stackoverflow.com/comment/90226264
upvote count: 1
has comment: http://stackoverflow.com/comment/90225546
score: 1
answers question: http://stackoverflow.com/q/51628055
has body: Well it looks like your file does not exists on given path You can verify either file exists before opening it via this way: import os.path os.path.exists('C:/Users/p.de.falco/Desktop/images/numArEx.txt') it will return True if file exists there else false hope this helps! Cheers!
has comment: http://stackoverflow.com/comment/90225377
downvote count: 0
has comment: http://stackoverflow.com/comment/90225391
has comment: http://stackoverflow.com/comment/90221043
type: Answer

http://stackoverflow.com/comment/90371673
comment on: http://stackoverflow.com/q/51623806
type: Comment
type: QuestionComment
has text: I'm attempting to reproduce the issue. Please can you provide the import lines your script is using?
score: 0

http://stackoverflow.com/comment/89975503
has text: Okay, thanks for your suggestion.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51502835
type: Comment

http://stackoverflow.com/comment/90105087
score: 0
comment on: http://stackoverflow.com/q/51569247
type: QuestionComment
type: Comment
has text: The `PATH` environment variable is different.

http://stackoverflow.com/comment/89965832
score: 1
comment on: http://stackoverflow.com/q/51497938
has text: not quite; I assume you mean using the token_pattern option with a suitable regex, as the default requires two or more char for a word token?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/73020716
has body: If someone comes across this question. Short answer: the features extractor that is defined in the training config is probably doing the preprocessing. If you are interested in a little more details, I answered it in a similar question. But when I added the link to the question my answer was transformed to a comment. So check out the comments of the original question.
score: 0
answers question: http://stackoverflow.com/q/51509083
type: Answer

http://stackoverflow.com/comment/135411079
has text: To make this work, I had to put `fooc_wrapper()` outside `foop_with_timeout()` - but then it worked like a charm in contrast to many other solutions I tried.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/76809740
type: AnswerComment

http://stackoverflow.com/q/51628094
linked to: http://stackoverflow.com/q/643699
type: Question
tagged with: periodicity
has comment: http://stackoverflow.com/comment/90221493
downvote count: 0
has comment: http://stackoverflow.com/comment/90220857
tagged with: pandas
tagged with: confidence-interval
answer count: 1
has comment: http://stackoverflow.com/comment/90221051
favorite count: 0
has comment: http://stackoverflow.com/comment/90221753
has title: How can I detect periodicity using auto-correlation automatically?
has answer: http://stackoverflow.com/a/69545315
type: UnansweredQuestion
tagged with: python
has body: This is my code: import matplotlib.pyplot as plt import numpy as np from pandas.plotting import autocorrelation_plot y = np.sin(np.arange(1,6*3.14,0.1)) autocorrelation_plot(y) plt.show() And this is the output of the auto-correlation plot: auto-correlation plot of y I would like to figure out a way to classify whether the function is periodic or not automatically (without using the bare-eye to look at the autocorrelation plot). I read that it is related to the confidence interval which is the line shown in the attached plot, but still have doubt on what I should do with it to better decide. So is there an automated way for using auto-correlation to decide the perdiodicity of the data? Though, this is my try for an automated way: result = np.correlate(y, y, mode = "full") ACF = result[np.round(result.size/2).astype(int):] ACF = ACF/ACF[0] acceptedVar = [] for i in range(len(ACF)): if ACF[i] &gt; 0.05: acceptedVar = np.append(acceptedVar, ACF[i]) percent = len(acceptedVar)/len(ACF) * 100 I just made a threshold of 0.05 to detect the points for which the confidence interval is 95%. Don't know if this is right or wrong statistically and logically. I then see if percent is bigger than 95% for a periodic pattern. I'm not sure of that as well. Credit to: the first answer to How can I use numpy.correlate to do autocorrelation?
score: 1
upvote count: 1

http://stackoverflow.com/q/51567572
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51567588
answer count: 2
tagged with: xlrd
downvote count: 0
has answer: http://stackoverflow.com/a/51567972
favorite count: 0
has body: I need to take a csv file as a function argument and as an example code I have: import openpyxl from openpyxl import load_workbook import csv import xlrd def supermarket(filename): dictionary = {} with open(filename, newline='') as filename: read_csv = csv.reader(filename, delimiter=',') for row in read_csv: dictionary += row[0] dictionary[row[0]] = row[1] return dictionary print(supermarket(prices1.csv)) However, when I debug the code, the traceback error says it is a NameError for which prices1 is not defined. My professor is telling me that my argument should be able to take prices1.csv as an argument but I don't see how that's possible.
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: How can my function take csv files as an input?

http://stackoverflow.com/comment/90121744
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51578040
has text: Its 1µs times N which can be huge. But ARMAN solution is actually is good as yours if you make `s.split('.')` in a different line. Just like `In [264]`
type: Comment

global
type: Tag
tags question: http://stackoverflow.com/q/51552597
tags question: http://stackoverflow.com/q/51528778
tag name: global
tags question: http://stackoverflow.com/q/51548166
tags question: http://stackoverflow.com/q/51502479
tags question: http://stackoverflow.com/q/51488941

http://stackoverflow.com/comment/90222649
has text: it is giving below TypeError: ("variable() missing 1 required positional argument: 'y'", 'occurred at index Volume')
comment on: http://stackoverflow.com/q/51629123
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90071812
comment on: http://stackoverflow.com/a/51550676
type: AnswerComment
score: 0
type: Comment
has text: I'll give it a shot.. It seems like the Q Filter isn't working properly. Even if I try something like `A.objects.annotate(Y=Count('b__bags', filter=Q(b__id=99999999)))` I still get 1.

http://stackoverflow.com/q/51504684
tagged with: bz2
tagged with: extract
type: Question
has answer: http://stackoverflow.com/a/51504727
tagged with: python
has body: as the title says, I have several folders, several .ppm.bz2 files and I want to extract them exactly where they are using python. Directory structure image I am traversing in the folders as this: import tarfile import os path = '/Users/ankitkumar/Downloads/colorferet/dvd1/data/images/' folders = os.listdir(path) for folder in folders: #the folders starting like 00001 if not folder.startswith("0"): pass path2 = path + folder zips = os.listdir(path2) for zip in zips: if not zip.startswith("0"): pass path3 = path2+"/"+zip fh = tarfile.open(path3, 'r:bz2') outpath = path2+"/" fh.extractall(outpath) fh.close ` then I get this error ` Traceback (most recent call last): File "ZIP.py", line 16, in &lt;module&gt; fh = tarfile.open(path3, 'r:bz2') File "/anaconda2/lib/python2.7/tarfile.py", line 1693, in open return func(name, filemode, fileobj, **kwargs) File "/anaconda2/lib/python2.7/tarfile.py", line 1778, in bz2open t = cls.taropen(name, mode, fileobj, **kwargs) File "/anaconda2/lib/python2.7/tarfile.py", line 1723, in taropen return cls(name, mode, fileobj, **kwargs) File "/anaconda2/lib/python2.7/tarfile.py", line 1587, in __init__ self.firstmember = self.next() File "/anaconda2/lib/python2.7/tarfile.py", line 2370, in next raise ReadError(str(e)) tarfile.ReadError: invalid header `
tagged with: bzip2
upvote count: 1
answer count: 1
has title: extracting a .ppm.bz2 from a custom path to a custom path
accepted answer: http://stackoverflow.com/a/51504727
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: tarfile

http://stackoverflow.com/a/51577845
type: Answer
upvote count: 2
has body: first list comprehension is read as mat = [[1,2],[4,6]] a = [] for i in mat: for j in i: a.append(j) print(a) second list comprehension is read as b = [] for j in i: for i in mat: b.append(j) print(b)
score: 2
has comment: http://stackoverflow.com/comment/90121461
has comment: http://stackoverflow.com/comment/90121070
answers question: http://stackoverflow.com/q/51577748
downvote count: 0
has comment: http://stackoverflow.com/comment/90121073

http://stackoverflow.com/q/51499385
favorite count: 0
has title: How to add values to a new column in pandas dataframe?
tagged with: python
upvote count: 7
possible better answer: http://stackoverflow.com/a/51499579
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51499563
has answer: http://stackoverflow.com/a/51499579
score: 7
tagged with: dataframe
linked to: http://stackoverflow.com/q/12555323
type: Question
has answer: http://stackoverflow.com/a/66735551
linked to: http://stackoverflow.com/q/24870953
downvote count: 0
has body: I want to create a new named column in a Pandas dataframe, insert first value into it, and then add another values to the same column: Something like: import pandas df = pandas.DataFrame() df['New column'].append('a') df['New column'].append('b') df['New column'].append('c') etc. How do I do that?
has comment: http://stackoverflow.com/comment/89967236
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51499563

http://stackoverflow.com/comment/90105897
type: Comment
has text: yeah, Thankyou @PM2Ring I'll remember it
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51569543

http://stackoverflow.com/comment/90172864
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51603430
has text: have you tried `http://localhost:8000/question6/test-question?no_rep=1`?

http://stackoverflow.com/comment/89972158
has text: @Ali: I'm afraid the assignment is not correct. This could be done in eg, C or java. But in python there is no such thing. There is only one integer type, and it can have infinitely large or small values.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51500779
type: Comment

http://stackoverflow.com/q/51537834
upvote count: 2
answer count: 3
has title: Pandas - check to see if all elements in a list are in a column
favorite count: 0
has comment: http://stackoverflow.com/comment/90043240
tagged with: pandas
has answer: http://stackoverflow.com/a/51537944
tagged with: python
has body: I have a data frame with 3 columns - 'sport' 'age' 'name' I have a list with different sports in, declared like this: sports = ['tennis','cricket','swimming'] I want to check to see if all 3 of the sports are in the sport column. Currently, i have this: if (df['sport']!=sport).any(): print('no, the sports arent in the column') So if all the sports in the list arent in the column I want to print no. The issue with my current code is that the sport column has many more elements than the sport list so gives me an error.
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51537916
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51537900
type: Question

http://stackoverflow.com/comment/90140780
comment on: http://stackoverflow.com/a/51585911
type: AnswerComment
has text: @user2896120, add your code to the original post so i can better understand
score: 0
type: Comment

http://stackoverflow.com/comment/90093488
type: AnswerComment
comment on: http://stackoverflow.com/a/51562807
type: Comment
has text: @GauravBansal since your var is always 1 , then pct_change=(df['pct_change']+df['Var']), change this
score: 1

http://stackoverflow.com/q/51581364
has body: I'm trying to create a grid of numbers from two 1D arrays like as follows: EXAMPLE a = [10,11,12,13,14,15] b = [1,2,3,4,5,6] [10] [11] [12] [13] [14] [15] [1] 11 12 13 14 15 16 [2] 12 13 14 15 16 17 [3] 13 14 15 16 17 18 [4] 14 15 16 17 18 19 [5] 15 16 17 18 19 20 [6] 16 17 18 19 20 21 So the operator between each combination of values is '+'. Kind of the cross product between two vectors but using addition. Are there any methods in numpy or similar to do this or do I need to write my own function? Speed is of concern, memory not so much. Ultimately I'd have 8 dimensions in my addition matrix, the example above is just to explain my problem.
has title: Creating a 2D matrix in Python from the addition of every combination of 2 1D arrays
type: Question
tagged with: numpy
score: 0
answer count: 2
tagged with: matrix
has answer: http://stackoverflow.com/a/51581596
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51581538

http://stackoverflow.com/comment/89968559
type: AnswerComment
has text: The user did not post any code that indicated they might have attempted the problem, and their profile indicates they are a student. Unless users understand what the code is doing and/or they go and read the documentation, I am dubious that they learn more than that SO makes it easy to get someone else to do your work for you.
comment on: http://stackoverflow.com/a/51498959
type: Comment
score: 2

http://stackoverflow.com/a/51655116
has body: Yes, that is how the step size is calculated for vectors -- for relative finite difference stepping, the stepsize is scaled by the norm of the vector. However, you bring up a good point that a vector may have wildly different magnitudes in its elements, so maybe we need to add support for specifying a vector of fd step sizes.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51630972
accepted answer of: http://stackoverflow.com/q/51630972
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90281617

http://stackoverflow.com/a/51546071
has body: The eval function evaluates a string as if it were source code.1 For example, eval("f(*args)") would do the same thing as calling f(*args) directly. But you don't have source code, you have a function. To call a function, all you have to do is: return f(*args) It doesn't matter that you got the function as a parameter, f, instead of directly from a def statement or lambda expression. Function values are just objects, like anything else in Python, and you can pass them around the same as any other values, and then call them whenever you want. But really, there's no need for this function at all. Instead of this: feval(f, x0) … you could just call it directly: f(x0) The only reason you'd ever need something like your feval is if someone else has passed you a function and a bunch of arguments separately, and you need to put them together into a function call. Python used to have a function for this, apply, but it was removed long ago because it's almost never necessary, and a one-liner if it ever is necessary. I also read that using eval() is bad practice. It usually is. That's because it's about treating strings as code: If the string comes out of your source code, you probably didn't need eval and could just run the code. That's why you don't want to use it here. If, on the other hand, the string comes from user input or the internet or something, it can be dangerous—something like "__import__('os').system('mr -rf /')" is just one typo away from being a really bad idea to evaluate. 1. It can also evaluate compiled code objects, which is why the error message is a bit more complicated than you might expect, but don't worry about that.
type: AcceptedAnswer
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51545986
type: Answer
answers question: http://stackoverflow.com/q/51545986
score: 2

http://stackoverflow.com/comment/90064874
comment on: http://stackoverflow.com/q/51547267
score: 0
type: Comment
type: QuestionComment
has text: it's `import dash_core_components` with `_` not `-`, also that's not a dash app, it's only using flask.

http://stackoverflow.com/q/51577694
type: UnansweredQuestion
has body: I'm currently working with raspberry pi and using DHT11 to read temperature and humidity values every second. I have to send the notification to the user through email. Here's my code that showing sensor data every second, I don't know how to send email to the user. I only need to send a notification when the humidity below 40. import RPi.GPIO as GPIO import dht11 import time import datetime import os # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() instance = dht11.DHT11(pin=dht11_pin) while True: cnt += 1 if cnt%limit_sec == 0 or cnt == 1: result = instance.read() if result.is_valid(): if previous_temperature != result.temperature or previous_humidity != result.humidity: previous_temperature = result.temperature previous_humidity = result.humidity counter += 1 rightnow = datetime.datetime.now() if result.humidity&gt;=40: print(str(counter)+". Last valid input: " ) print("Date: " + rightnow.strftime("%d/%m/%Y")) print("Time: " + rightnow.strftime("%H:%M:%S")) print("Status: Your plant is on the good condition.") print("Temperature: %d C" % result.temperature) print("Humidity: %d %%" % result.humidity) else: print(str(counter)+". Last valid input: " ) print("Date: " + rightnow.strftime("%d/%m/%Y")) print("Time: " + rightnow.strftime("%H:%M:%S")) print("Status: Your plant is on the bad condition. Please open the water supply.") print("Temperature: %d C" % result.temperature) print("Humidity: %d %%" % result.humidity) else: print "Invalid result!" pass time.sleep(sleep_time)
type: Question
has title: how to send sensor data to the user using email
answer count: 1
score: 0
tagged with: notifications
has answer: http://stackoverflow.com/a/51577895
tagged with: sensors
tagged with: email
tagged with: python
tagged with: python-3.x

word2vec
tags question: http://stackoverflow.com/q/51639415
tags question: http://stackoverflow.com/q/51616074
tags question: http://stackoverflow.com/q/51512064
tags question: http://stackoverflow.com/q/51566257
tags question: http://stackoverflow.com/q/51590459
tags question: http://stackoverflow.com/q/51514825
tags question: http://stackoverflow.com/q/51523248
tags question: http://stackoverflow.com/q/51564639
type: Tag
tags question: http://stackoverflow.com/q/51492778
tag name: word2vec
tags question: http://stackoverflow.com/q/51594165

http://stackoverflow.com/comment/89975264
type: QuestionComment
comment on: http://stackoverflow.com/q/51503271
has text: This might help: https://www.codecademy.com/en/forum_questions/551c137f51b887bbc4001b73
score: 0
type: Comment

http://stackoverflow.com/q/51534731
has body: So I am trying to create a form of encryption program with a GUI. Here is the code: import sys from PyQt4 import QtGui, QtCore import os from Crypto.Hash import SHA256 from Crypto import Random from Crypto.Cipher import AES class Window(QtGui.QMainWindow): def __init__(self): super(Window, self).__init__() self.setGeometry(50, 50, 500, 300) self.setWindowTitle("Encryptionprogram") self.setWindowIcon(QtGui.QIcon('pythonicon.png')) self.container = QtGui.QWidget() self.setCentralWidget(self.container) self.container_lay = QtGui.QVBoxLayout() self.container.setLayout(self.container_lay) extractAction = QtGui.QAction("Leave", self) extractAction.setShortcut("Ctrl+Q") extractAction.setStatusTip("Leave the app") extractAction.triggered.connect(self.close_application) mainMenu = self.menuBar() fileMenu = mainMenu.addMenu('&amp;File') fileMenu.addAction(extractAction) #Inputs self.Input = QtGui.QLineEdit("Filname", self) self.Input.setFixedWidth(200) self.Input.setFixedHeight(25) self.Input.move(20, 200) self.Input.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) self.Input2 = QtGui.QLineEdit("password", self) self.Input2.setFixedWidth(200) self.Input2.setFixedHeight(25) self.Input2.move(220, 200) self.Input2.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) self.home() def home(self): #Enter self.enter_btn = QtGui.QPushButton("Enter") self.container_lay.addWidget(self.enter_btn) self.enter_btn.clicked.connect(self.run1) self.checkBox = QtGui.QCheckBox('Krypter?', self) self.checkBox.move(0, 60) self.checkBox2 = QtGui.QCheckBox('Decrypt', self) self.checkBox2.move(100, 60) extractAction = QtGui.QAction(QtGui.QIcon('CloseIcon.png'), 'Close Program', self) extractAction.triggered.connect(self.close_application) self.toolBar = self.addToolBar("Extraction") self.toolBar.addAction(extractAction) self.show() def enlarge_window(self, state): if state == QtCore.Qt.Checked: self.setGeometry(50, 50, 1250, 600) else: self.setGeometry(50, 50, 500, 300) def …
type: Question
possible better answer: http://stackoverflow.com/a/51534956
has title: TypeError: expected str, bytes or os.PathLike object, not tuple
upvote count: 4
score: 0
answer count: 2
downvote count: 4
tagged with: pyqt
has comment: http://stackoverflow.com/comment/90037263
has answer: http://stackoverflow.com/a/51534775
accepted answer: http://stackoverflow.com/a/51534775
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51534956
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90037234

localtime
tags question: http://stackoverflow.com/q/51575657
type: Tag
tag name: localtime

http://stackoverflow.com/comment/90301735
comment on: http://stackoverflow.com/q/51591677
has text: Ohk. Will check it out. Thanks @Val
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90129236
type: AnswerComment
comment on: http://stackoverflow.com/a/51581487
score: 0
type: Comment
has text: Thanks, amazing answer! Can you just explain why does searching elemnt require "//" at the start and also what exactly does WebDriverWait do? shouldn't it wait automatically and thus not requiring the try, finally?

http://stackoverflow.com/q/51591659
tagged with: python
has comment: http://stackoverflow.com/comment/90148654
has comment: http://stackoverflow.com/comment/90148560
score: 3
downvote count: 1
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/51594842
has answer: http://stackoverflow.com/a/51593922
answer count: 3
has answer: http://stackoverflow.com/a/51594542
has body: (y) xlm@d8cb8a102c73:~/workspace/y-server/y$ ./manage.py run_algorithm --settings=y.settings.local Traceback (most recent call last): File "./manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/xlm/.virtualenvs/y/lib/python3.5/site- packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/xlm/.virtualenvs/y/lib/python3.5/site- packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/xlm/.virtualenvs/y/lib/python3.5/site- packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/home/xlm/.virtualenvs/y/lib/python3.5/site- packages/django/core/management/base.py", line 454, in execute self.stdout.write(output) File "/home/xlm/.virtualenvs/y/lib/python3.5/site- packages/django/core/management/base.py", line 111, in write if ending and not msg.endswith(ending): AttributeError: 'dict' object has no attribute 'endswith' I am trying to run the file algorithm.py with the command file run_algorithm.py (below) on a django framework. However I get the above attribute error, and I am unsure why. import logging from django.conf import settings from django.core.management.base import BaseCommand from ...algorithm import engagement_level_mapping logger = logging.getLogger(settings.LOGGER_NAME) class Command(BaseCommand): help = "TODO: describe" def handle(self, *args, **options): result = engagement_level_mapping() return result However, when printing the result, rather than returning, the file executes correctly. import logging from django.conf import settings from django.core.management.base import BaseCommand from ...algorithm import engagement_level_mapping logger = logging.getLogger(settings.LOGGER_NAME) class Command(BaseCommand): help = "TODO: describe" def handle(self, *args, **options): result = engagement_level_mapping() print(result) The command file…
has title: Attribute Error: 'dict' object has no attribute 'endswith'
favorite count: 0
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/q/51602700
has body: My goals is to locate IP address inside a text. Using grep, I was able to do it with the regular expression ([0-9]+\.){3}[0-9]+. With re from Python, I don't understand why it doesn't work unless I precede the expression inside the parentheses with ?: I understand that the use of ?: will prevent the creation of a group, but I can't explain the result when this prefix is deleted. &gt;&gt;&gt; s '64 bytes from 10.11.1.5: icmp_seq=2 ttl=128 time=215 ms' &gt;&gt;&gt; p=re.compile(r"(?:[0-9]+\.){3}") &gt;&gt;&gt; p.findall(s) ['10.11.1.'] &gt;&gt;&gt; p=re.compile(r"([0-9]+\.){3}") &gt;&gt;&gt; p.findall(s) ['1.']
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51602868
possible better answer: http://stackoverflow.com/a/51602868
downvote count: 1
type: Question
upvote count: 5
score: 4
has comment: http://stackoverflow.com/comment/90171826
has answer: http://stackoverflow.com/a/51602835
has answer: http://stackoverflow.com/a/51603314
answer count: 3
favorite count: 0
has title: non-capturing version of regular parentheses Python
accepted answer: http://stackoverflow.com/a/51602835
tagged with: python
tagged with: regex

http://stackoverflow.com/q/51508104
tagged with: python
has body: I'm trying to improve a little program I've made as it's currently got a lot of copied variables with just amended numbers. Is there a possibility to make variables that do a specific calculation where the name of the variable depends on the key and the way it is calculated depends on the value? Here is a piece of the code: #Product Retail Price product_retail_price = float(input("Valor do produto na loja em Reais (Formato 00.00): ")) #Costs product_cost = float(input("Valor do produto no fornecedor em Reais (Formato 00.00): ")) cpa = float(input("Custo por aquisição (Formato 00.00): ")) rrp_divided = product_retail_price / 100 fee_shopify = rrp_divided*2 fee_mercadopago = rrp_divided*4.99 fee_dictionary = {2:2.03,3:4.06,4:6.09,5:7.64,6:8.92,7:10.06,8:10.62,9:11.23,10:12.41,11:13.60,12:14.80,15:18.47,18:22.23,24:23.83} # for keys, values in fee_dictionary.values(): """ fee_finance_2 = rrp_divided*2.03 fee_finance_3 = rrp_divided*4.06 fee_finance_4 = rrp_divided*6.09 fee_finance_5 = rrp_divided*7.64 fee_finance_6 = rrp_divided*8.92 fee_finance_7 = rrp_divided*10.06 fee_finance_8 = rrp_divided*10.62 fee_finance_9 = rrp_divided*11.23 fee_finance_10 = rrp_divided*12.41 fee_finance_11 = rrp_divided*13.60 fee_finance_12 = rrp_divided*14.80 fee_finance_15 = rrp_divided*18.47 fee_finance_18 = rrp_divided*22.23 fee_finance_24 = rrp_divided*23.83 """ What I would like to do is to create multiple variables like the ones at the bottom but without actually copying and pasting them and changing the numbers. I've assigned the key as the number that's supposed to be at the end of each variable, while the value is the number the calculation inside the variable should be divided by. The latter portion of the code also needs improving and I'd like to use a similar principle. Can any of you suggest the best way? #Calculations parcelas = int(input("Número de parcelas sem juros (Formato: 0-24): ")) base_profit = round(product_retail_price - product_cost - fee_shopify - fee_mercadopago - …
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51509089
accepted answer: http://stackoverflow.com/a/51509089
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89985868
has comment: http://stackoverflow.com/comment/89985383
type: Question
has comment: http://stackoverflow.com/comment/89985331
has comment: http://stackoverflow.com/comment/89985313
has comment: http://stackoverflow.com/comment/89988369
has comment: http://stackoverflow.com/comment/89988166
score: 0
has comment: http://stackoverflow.com/comment/89985818
has comment: http://stackoverflow.com/comment/89988739
has title: Create variables using a dictionary in Python
answer count: 1
has comment: http://stackoverflow.com/comment/89985311
favorite count: 0
has comment: http://stackoverflow.com/comment/89988272

deep-learning
tags question: http://stackoverflow.com/q/51515232
tags question: http://stackoverflow.com/q/51537837
tags question: http://stackoverflow.com/q/51591550
tags question: http://stackoverflow.com/q/51621706
tags question: http://stackoverflow.com/q/51583539
tags question: http://stackoverflow.com/q/51518585
tags question: http://stackoverflow.com/q/51503274
tags question: http://stackoverflow.com/q/51611512
tags question: http://stackoverflow.com/q/51514021
tags question: http://stackoverflow.com/q/51549799
tags question: http://stackoverflow.com/q/51541385
tags question: http://stackoverflow.com/q/51585339
tags question: http://stackoverflow.com/q/51576642
tags question: http://stackoverflow.com/q/51621474
tags question: http://stackoverflow.com/q/51572083
tags question: http://stackoverflow.com/q/51553000
tags question: http://stackoverflow.com/q/51575771
tags question: http://stackoverflow.com/q/51548765
tags question: http://stackoverflow.com/q/51604912
tags question: http://stackoverflow.com/q/51529785
tags question: http://stackoverflow.com/q/51602088
tags question: http://stackoverflow.com/q/51569005
tags question: http://stackoverflow.com/q/51605893
tags question: http://stackoverflow.com/q/51594082
tags question: http://stackoverflow.com/q/51490254
tags question: http://stackoverflow.com/q/51526952
tags question: http://stackoverflow.com/q/51625811
tags question: http://stackoverflow.com/q/51541610
tags question: http://stackoverflow.com/q/51518631
tags question: http://stackoverflow.com/q/51533663
tags question: http://stackoverflow.com/q/51638785
type: Tag
tags question: http://stackoverflow.com/q/51487339
tags question: http://stackoverflow.com/q/51492312
tags question: http://stackoverflow.com/q/51577885
tags question: http://stackoverflow.com/q/51559118
tags question: http://stackoverflow.com/q/51621107
tags question: http://stackoverflow.com/q/51586072
tags question: http://stackoverflow.com/q/51599531
tags question: http://stackoverflow.com/q/51591069
tags question: http://stackoverflow.com/q/51544666
tags question: http://stackoverflow.com/q/51524143
tags question: http://stackoverflow.com/q/51530864
tag name: deep-learning
tags question: http://stackoverflow.com/q/51531532
tags question: http://stackoverflow.com/q/51499154
tags question: http://stackoverflow.com/q/51526179
tags question: http://stackoverflow.com/q/51558339
tags question: http://stackoverflow.com/q/51585875
tags question: http://stackoverflow.com/q/51593126

http://stackoverflow.com/a/51578066
answers question: http://stackoverflow.com/q/51577527
has comment: http://stackoverflow.com/comment/90121679
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90121557
upvote count: 1
type: Answer
has body: var obj = [{ "evt.category": "file", "evt.cpu": 0, "evt.num": 10078507, "evt.res": "SUCCESS", "evt.time": 1532841047277584400, "evt.type": "read", "fd.filename": "libnss_files.so.2", "fd.name": "/lib/x86_64-linux-gnu/libnss_files.so.2", "fd.num": 13, "fd.type": "file", "fd.uid": "1996913", "proc.loginshellid": 19968, "proc.name": "last", "proc.pid": 19969, "thread.ismain": true, "thread.tid": 19969 }, { "evt.buffer": "1000", "evt.category": "file", "evt.cpu": 0, "evt.num": 10078564, "evt.res": "SUCCESS", "evt.time": 1532841047277731300, "evt.type": "read", "fd.filename": "loginuid", "fd.name": "/proc/16009/loginuid", "fd.num": 13, "fd.type": "file", "fd.uid": "1996913", "proc.loginshellid": 19968, "proc.name": "last", "proc.pid": 19969, "thread.ismain": true, "thread.tid": 19969 }, { "evt.buffer": "", "evt.category": "file", "evt.cpu": 0, "evt.num": 10078566, "evt.res": "SUCCESS", "evt.time": 1532841047277733400, "evt.type": "read", "fd.filename": "loginuid", "fd.name": "/proc/16009/loginuid", "fd.num": 13, "fd.type": "file", "fd.uid": "1996913", "proc.loginshellid": 19968, "proc.name": "last", "proc.pid": 19969, "thread.ismain": true, "thread.tid": 19969 } ]; function convertObj(obj) { var resultArray = []; obj.forEach(item =&gt; { var resultObj = {}; for (var property in item) { var array = property.split('.'); var reference = resultObj; for (var i = 0; i &lt; array.length-1; i++) { if (!reference[array[i]]){ reference[array[i]] = {}; } reference = reference[array[i]]; } reference[array[array.length-1]] = item[property]; } resultArray.push(resultObj); }); return resultArray; } console.log(convertObj(obj));

http://stackoverflow.com/a/51517826
has body: del data.database['school'] modifies the data in memory, but does not modify the source code. Modifying a source code to manage the persistence of your data is not a good practice IMHO. You could use a database, a csv file, a json file ...
accepted answer of: http://stackoverflow.com/q/51517759
answers question: http://stackoverflow.com/q/51517759
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90100289
has text: So you have no idea where the file is? You _could_ solve that by walking the entire filesystem in Python, but that's probably a bad idea. (It will be slow, you may not have access to every directory you need to traverse to get there without having multiple roots to start from, etc.) Depending on your platform, you probably have something like Spotlight or Windows Desktop Search or Dash or Beagle, or at least locate.
comment on: http://stackoverflow.com/q/51566759
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51605520
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51607734
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Django variable handling-why does this work?
has answer: http://stackoverflow.com/a/51606716
type: Question
has body: I'm pretty new to django and came across something that confuses me in this views.py file I've created. I just played around with it a little and came up with something that works, but I don't get why it does. The class Draft_Order (which I have in another file) requests the NBA stats page, performs some calculations on the backend, and spits out draft lottery odds (for the new draft). The methods initialize, sim draft, and get standings all do things on the backend (which works perfectly). Now, my question is that I don't get why I can create an instance "f" of the class DraftOrder outside all of the functions, but yet still be able to reference it within most of my functions as they are getting called from my urls.py file, so it doesnt seem like they should be working at all. Also, for some reason, the update function can only reference "f" if I don't have an assignment to f in the function-e.g. if I add the line f = temp Then all of a sudden it gives me an "unboundlocalerror", and says that f is referenced before assignment. I'd appreciate any help on this. Thanks. from django.shortcuts import render from django.http.response import HttpResponse from simulator.draft_simulator import Draft_Order from simulator.models import Order # Create your views here. f = Draft_Order() f.initialize() def index(request): return HttpResponse(' Hello World ') def init(request): return HttpResponse(f.initalodds.to_html()) def table(request): f.sim_draft() return HttpResponse(f.finaltable.to_html()) def update(request): temp = Draft_Order() temp.get_standings() if temp == f: return HttpResponse('Same!') else: return HttpResponse('updated!')
score: 0
answer count: 2

http://stackoverflow.com/comment/89993501
type: Comment
has text: Take the second 4 letter string.
comment on: http://stackoverflow.com/q/51510818
score: 0
type: QuestionComment

http://stackoverflow.com/q/51561421
answer count: 2
has comment: http://stackoverflow.com/comment/90092328
has comment: http://stackoverflow.com/comment/90092054
has title: Insertion error in MySQL database using python package pymysql
linked to: http://stackoverflow.com/q/10957238
favorite count: 0
linked to: http://stackoverflow.com/q/1168036
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51561459
has body: Here is my code for insertion. myCursor.execute("INSERT INTO news_table(news_title, news_source, news_link, news_img, news_date, news_view, news_text, news_hit) VALUES (%s,%s,%s,%s,%s,%s);",(nextntitle, nextnsource, nextnlink, nextnimg, nextndate, nextntext)) my database name is news_table which has 9 attributes, but when i am trying to insert the data with the code it gives me the following error Traceback (most recent call last): File "C:/Users/qasys/PycharmProjects/conda_main/pythonmysql/checkdb.py", line 82, in &lt;module&gt; myCursor.execute("INSERT INTO news_table(news_title, news_source, news_link, news_img, news_date, news_view, news_text, news_hit) VALUES (%s,%s,%s,%s,%s,%s);",(nextntitle, nextnsource, nextnlink, nextnimg, nextndate, nextntext)) File "C:\ProgramData\Anaconda3\envs\conda_main\lib\site-packages\pymysql\cursors.py", line 170, in execute result = self._query(query) File "C:\ProgramData\Anaconda3\envs\conda_main\lib\site-packages\pymysql\cursors.py", line 328, in _query conn.query(q) File "C:\ProgramData\Anaconda3\envs\conda_main\lib\site-packages\pymysql\connections.py", line 516, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "C:\ProgramData\Anaconda3\envs\conda_main\lib\site-packages\pymysql\connections.py", line 727, in _read_query_result result.read() File "C:\ProgramData\Anaconda3\envs\conda_main\lib\site-packages\pymysql\connections.py", line 1066, in read first_packet = self.connection._read_packet() File "C:\ProgramData\Anaconda3\envs\conda_main\lib\site-packages\pymysql\connections.py", line 683, in _read_packet packet.check_error() File "C:\ProgramData\Anaconda3\envs\conda_main\lib\site-packages\pymysql\protocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "C:\ProgramData\Anaconda3\envs\conda_main\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.InternalError: (1136, "Column count doesn't match value count a…
has answer: http://stackoverflow.com/a/51561466
tagged with: mysql
downvote count: 1
type: Question
upvote count: 0
tagged with: database
tagged with: pymysql
score: -1

http://stackoverflow.com/comment/90048089
type: QuestionComment
type: Comment
has text: @Marcus.Aurelianus I know that, but doesn't help solving the problem.
comment on: http://stackoverflow.com/q/51540141
score: 0

http://stackoverflow.com/q/51485265
has comment: http://stackoverflow.com/comment/89980839
answer count: 0
has title: Can't replace one body/shape with two body/shapes in pymunk
type: Question
tagged with: python
tagged with: chipmunk
score: 0
has body: I am working on a program with pymunk and pygame where I am trying to simulate objects growing and dividing. I have implemented this by stepping through the program and removing each body/shape at certain intervals and adding a new, slightly larger body/shape. I wrote separate functions for initializing the objects, growing the objects, and dividing the objects. I am trying to divide the objects by replacing each body/shape with two bodies/shapes. This appears to work okay with the "growing" phase, but when I get to the dividing function, all of the bodies disappear from the screen! I can tell from print statements that there are twice as many shapes in the space as before and that they then double again after another interval, but they completely stop showing up. My functions for growing the objects and dividing the objects are very similar, so I'm not sure what the issue is. Any help you could provide would be much appreciated. My program is very long, so I haven't included my code, but I can try and include some if you feel that would be helpful.
has comment: http://stackoverflow.com/comment/89980917
type: UnansweredQuestion
tagged with: pymunk
has comment: http://stackoverflow.com/comment/89985480

http://stackoverflow.com/comment/89972533
has text: What line is the error on? How many items does `df[(df['date_rank'] == next_home_fixture) & (df['localteam_id'] == df.at[index,'localteam_id'])].index` return for the iterations where there's an error?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51501255

http://stackoverflow.com/comment/90903744
comment on: http://stackoverflow.com/q/51498991
score: 0
type: QuestionComment
has text: @Paul I have seen your code and it didn't work for me, only after adding chrome cookies to the request (when I was logged in to FB/manuscript) I could download attachment. Does this code from your answer still work for you?
type: Comment

http://stackoverflow.com/comment/90209655
comment on: http://stackoverflow.com/q/51621842
has text: Sorry. I have no idea how to do it.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/51543288
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51542035
has comment: http://stackoverflow.com/comment/90093094
downvote count: 0
has body: So, you want conditional aggregation : SELECT name, SUM(CASE WHEN activity = 'tv' THEN 1 ELSE 0 END) AS tv, SUM(CASE WHEN activity = 'football' THEN 1 ELSE 0 END) AS football, SUM(CASE WHEN activity = 'cooking' THEN 1 ELSE 0 END) AS cooking, . . . FROM dataset GROUP BY name;
type: Answer
has comment: http://stackoverflow.com/comment/90056729

http://stackoverflow.com/a/51594855
has comment: http://stackoverflow.com/comment/90157508
has comment: http://stackoverflow.com/comment/90157091
type: Answer
has comment: http://stackoverflow.com/comment/90157028
has comment: http://stackoverflow.com/comment/90155807
downvote count: 0
score: 1
has body: You can use the os module to perform this manipulation. The benefit of using this module is the correct separator will be used for your platform. import os x = r'C:\Users\user\Desktop\SHAPE\45554\INS\INS.shp' def get_folder(fp, k=5): return os.path.split(fp)[0].split(os.sep)[k] x_folder = get_folder(x) # '45554' Then just apply within your loop via pd.DataFrame.assign: for fil in glob.iglob('**/Desktop/SHAPE/**/' ,recursive = True): files.append(pd.read_table(fil).assign(col=get_folder(fil)))
has comment: http://stackoverflow.com/comment/90157275
accepted answer of: http://stackoverflow.com/q/51594725
answers question: http://stackoverflow.com/q/51594725
has comment: http://stackoverflow.com/comment/90157715
has comment: http://stackoverflow.com/comment/90155562
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90156699

http://stackoverflow.com/comment/90018329
type: QuestionComment
type: Comment
has text: The interactivity is actually only a side effect, but plotly seems nicer, somehow I didn't find too much about Gantt Charts with matplotlib or they looked super ugly. [I got some results with plotly and try to adapt the layout now.](https://stackoverflow.com/questions/51524712/edit-layout-of-plotly-gantt-chart-with-dataframe-and-timedelta)
comment on: http://stackoverflow.com/q/51514840
score: 0

http://stackoverflow.com/comment/90085208
score: 1
comment on: http://stackoverflow.com/q/51559201
has text: Please provide a [mcve].
type: QuestionComment
type: Comment

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

http://stackoverflow.com/comment/89946026
type: Comment
comment on: http://stackoverflow.com/q/51487971
type: QuestionComment
score: 1
has text: It's custom `__getitem__` accesss, which selects a specific overload (i.e. signature) of the `actionTriggered` signal. Without it, the default overload is selected.

http://stackoverflow.com/a/51579243
score: 0
has body: You can use Pandas for an efficient, vectorised solution. The disadvantages of itertools.groupby here are it requires sorting [additional complexity] and does not implement vectorised calculations [inefficient summing]. If you want to go down the loopy route, I recommend collections.defaultdict to make sure you still have O(n) complexity. import pandas as pd df = pd.DataFrame(x) res = df.groupby(['id', 'var1', 'var2']).agg({'var3': 'sum', 'var4': 'sum'}).reset_index() print(res.to_dict('records')) [{'id': 1, 'var1': 'a', 'var2': 'left', 'var3': 0.1, 'var4': 1}, {'id': 2, 'var1': 'a', 'var2': 'right', 'var3': 0.3, 'var4': 4}, {'id': 4, 'var1': 'b', 'var2': 'left', 'var3': 0.4, 'var4': 4}, {'id': 5, 'var1': 'b', 'var2': 'right', 'var3': 0.5, 'var4': 7}]
type: Answer
answers question: http://stackoverflow.com/q/51579184

http://stackoverflow.com/q/51619618
score: 1
upvote count: 1
has body: For some reason that I do not see, this code is throwing an error: AttributeError: __exit__ The code is simple: import re, string, math, numpy, time, os.path, itertools, matplotlib, subprocess, shutil, sys, scipy.spatial.distance, multiprocessing, threading, ctypes from functools import partial from multiprocessing.sharedctypes import Value, Array from multiprocessing import Process, Lock def main(): with multiprocessing.Pool(8) as myPool: print("1") if __name__ == '__main__': main() The various import lines are for other things I've been using with other code I'm working on multithreading. This however is the simple 'sample' code that I'm trying to analyze to learn the ropes. I assume it's having some sort of trouble opening the with block, but I don't understand why. Does Python 2.7 not implement multiprocessing this way? It's all the examples I've seen. Is there some other way I should be implementing something like this? I want to be able to throw a bunch of function calls with slightly different inputs to a set of threads and get them back, but that's a far way off if I can't start the threads.
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90235645
has title: Multiprocessing throws Attribute Error, why?
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90204956
has answer: http://stackoverflow.com/a/51752343
tagged with: multithreading
tagged with: python
tagged with: with-statement
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51752343

http://stackoverflow.com/q/51533996
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/51536156
accepted answer: http://stackoverflow.com/a/51536156
score: 1
has comment: http://stackoverflow.com/comment/90036163
has comment: http://stackoverflow.com/comment/90036682
upvote count: 1
has comment: http://stackoverflow.com/comment/90036012
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90036609
has body: I'm trying to generate text using PIL for a black and white image only, but the text has this gray outline that I'm trying to get rid off. image = np.zeros((600, 600), dtype=np.uint8) image[:] = 255 img = Image.fromarray(image, 'L') fnt = ImageFont.truetype('Arial.ttf', 50) draw = ImageDraw.Draw(img) draw.text((50,100), 'test , test', font=fnt) What do I need to do to get the text to appear only in black? No gray area around it?
tagged with: python
downvote count: 0
type: Question
type: AnsweredQuestion
has title: PIL draw text without gray outline

http://stackoverflow.com/comment/90056526
type: Comment
type: QuestionComment
has text: This is not an XY problem. I want to run N queries at the same time with SQLAlchemy.
comment on: http://stackoverflow.com/q/51543936
score: 0

http://stackoverflow.com/comment/90204328
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51619099
has text: @ user3483203 I think the issue is that in my real case that these are actually not clean and complete time series, so I cannot use shift and need to use datetime index.

http://stackoverflow.com/comment/90056142
score: 0
type: Comment
type: QuestionComment
has text: Thanks man! Will give it a look asap
comment on: http://stackoverflow.com/q/51517235

http://stackoverflow.com/a/54396620
score: 1
answers question: http://stackoverflow.com/q/51599431
has comment: http://stackoverflow.com/comment/95604443
has comment: http://stackoverflow.com/comment/95604656
upvote count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/95604716
has comment: http://stackoverflow.com/comment/95604377
type: Answer
has body: This Expection means you should use dialect-specific ARRAY type to instead the base ARRAY type. So in your models definition, Use sqlalchemy.dialects.postgresql.ARRAY to instead ARRAY from sqlalchemy.dialects.postgresql import ARRAY class table(db.Model): ... languages = db.Column(ARRAY) # notice this ARRAY import from sqlalchemy.dialects.postgresql Now, you can use db.session.query(table).filter(table.languages.contains([language])).limit(200).

http://stackoverflow.com/comment/90039767
has text: a file-like class. Like Bytes-IO or String-IO. I Don't want the output to be an actual file. I want it to come out as a string so I could upload it directly to my AWS S3 Bucket. Uploading the actual file instead of a file that is stored in memory creates an unnecessary throughput in a very time critical environment.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51507820
score: 0

http://stackoverflow.com/a/51601135
has comment: http://stackoverflow.com/comment/90171432
type: Answer
upvote count: 1
has body: If all you want to do is to swap the values below a certain threshold, meaning a permutation of those values, sample is your friend. swapFun &lt;- function(x, n = 10){ inx &lt;- which(x &lt; n) x[sample(inx)] &lt;- x[inx] x } toydata[toydata$x &lt; 10, 1] #[1] 3 9 9 7 which(toydata$x &lt; 10) #[1] 4 10 26 40 toy &lt;- toydata # Work with a copy toy[] &lt;- lapply(toydata, swapFun) toy[toy$x &lt; 10, 1] #[1] 9 7 3 9 which(toy$x &lt; 10) #[1] 4 10 26 40 Note that the order of the values less than 10 has changed but not where they can be found. If you want another threshold, say 25, just do toydata[] &lt;- lapply(toydata, swapFun, n = 25) To swap between columns, use another function. It starts by transforming the input data.frame into a vector. The swapping is done in the same way. Then back to data.frame. swapFun2 &lt;- function(DF, n = 10){ x &lt;- unlist(DF) inx &lt;- which(x &lt; n) x[sample(inx)] &lt;- x[inx] x &lt;- as.data.frame(matrix(x, ncol = ncol(DF))) names(x) &lt;- names(DF) x } toy2 &lt;- swapFun2(toydata)
has comment: http://stackoverflow.com/comment/90170567
answers question: http://stackoverflow.com/q/51601022
downvote count: 0
has comment: http://stackoverflow.com/comment/90169382
has comment: http://stackoverflow.com/comment/90169656
score: 1

http://stackoverflow.com/comment/90220446
has text: @Plasma row means to loop through every single row from the csv file to insert them into the postgres
comment on: http://stackoverflow.com/q/51626953
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51497324
has comment: http://stackoverflow.com/comment/89964087
has comment: http://stackoverflow.com/comment/89968612
has comment: http://stackoverflow.com/comment/89967664
answers question: http://stackoverflow.com/q/51497071
has comment: http://stackoverflow.com/comment/89968702
has comment: http://stackoverflow.com/comment/89964479
has comment: http://stackoverflow.com/comment/89964819
has comment: http://stackoverflow.com/comment/89968638
has comment: http://stackoverflow.com/comment/89968474
has comment: http://stackoverflow.com/comment/89968099
has body: In the function here - def newest_image(list_of_images): # list_of_images is passed here, which in your case is [] latest = None # latest is set to None here # Since list_of_images is empty, this for loop does not work for image in list_of_images: if not latest: latest = image continue if parser.parse(image['CreationDate']) &gt; parser.parse(latest['CreationDate']): latest = image # since for loop did not run, latest still is None return latest The reason why you get this error is because newest_image returned None and therefore source_image is None and by this - print(source_image['ImageId']) And you are trying to get an item out of None, therefore - TypeError: 'NoneType' object has no attribute '__getitem__' You could handle it like - try: print(source_image['ImageId']) except TypeError: print("Oops! Returned None") I hope that makes sense?
score: 0
has comment: http://stackoverflow.com/comment/89968108
has comment: http://stackoverflow.com/comment/89968746
type: Answer
has comment: http://stackoverflow.com/comment/89969122
has comment: http://stackoverflow.com/comment/89968279
has comment: http://stackoverflow.com/comment/89967889
has comment: http://stackoverflow.com/comment/89967924
has comment: http://stackoverflow.com/comment/89967962

http://stackoverflow.com/q/51622452
score: 0
has answer: http://stackoverflow.com/a/51622665
has comment: http://stackoverflow.com/comment/90210345
tagged with: function
answer count: 1
tagged with: data-science
has title: Apply a function in a dataframe's columns [Python]
tagged with: data-analysis
has body: I just wrote this function to calculated the age's person based in two columns in a Python DataFrame. Unfortunately, if a use the return the function return the same value for all rows, but if I use the print statement the function gives me the right values. Here is the code: def calc_age(dataset): index = dataset.index for element in index: year_nasc = train['DT_NASCIMENTO_BENEFICIARIO'][element][6:] year_insc = train['ANO_CONCESSAO_BOLSA'][element] age = int(year_insc) - int(year_nasc) print ('Age: ', age) #return age train['DT_NASCIMENTO_BENEFICIARIO'] = 03-02-1987 train['ANO_CONCESSAO_BOLSA'] = 2009 What am I doing wrong?!
tagged with: python
has comment: http://stackoverflow.com/comment/90210215
accepted answer: http://stackoverflow.com/a/51622665
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90210441
has comment: http://stackoverflow.com/comment/90210794
type: Question
has comment: http://stackoverflow.com/comment/90210456
has comment: http://stackoverflow.com/comment/90210526
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90210353

http://stackoverflow.com/comment/108796241
comment on: http://stackoverflow.com/a/51543225
type: Comment
has text: @user12379095 why are you using it then as the key of a keyword argument in `.filter()`? Maybe you want to do: `PriceItems.objects.filter(from_date__lte=ref_date, to_date__gte=ref_date)`? You should really first consult the docs on how to use queryset methods first. You seem to have many misconceptions about that.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90127718
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51581139
score: 0
has text: I've tried that too, but that still does not work

http://stackoverflow.com/comment/90193912
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51613748
has text: Why invisible all field, use domain
score: 0

http://stackoverflow.com/comment/106010963
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/59882495
type: Comment
has text: Brilliant! Didn't know you can still draw on the page after it's done.

http://stackoverflow.com/comment/90243997
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51639660
has text: Most times you not only don't need to manually call update, but also should not as it may adversely interfere with the queue of events.
type: AnswerComment

http://stackoverflow.com/comment/89984335
type: Comment
has text: You can probably use Selenium to download the CSV, but that might be a little too much of a good thing: https://stackoverflow.com/questions/18439851/how-can-i-download-a-file-on-a-click-event-using-selenium
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51487657

http://stackoverflow.com/comment/90181488
comment on: http://stackoverflow.com/q/51608018
score: 0
type: Comment
type: QuestionComment
has text: Update the question with your _code trials_ and _error stack trace_

http://stackoverflow.com/comment/90360334
type: QuestionComment
comment on: http://stackoverflow.com/q/51632287
score: 0
type: Comment
has text: Hi Dan, have you tried using conda? The easiest and best supported way is through conda http://www.zipline.io/install.html#windows as Zipline has several C dependencies.

http://stackoverflow.com/comment/89956410
comment on: http://stackoverflow.com/a/51493231
score: 0
type: AnswerComment
has text: That is what I meant, not really "separate" them but have two paragraphs with a title comment.
type: Comment

http://stackoverflow.com/q/51630009
favorite count: 0
has title: skimage.transform.PiecewiseAffineTransform, dstination points in example
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: In the skimage.transform.PiecewiseAffineTransform example, blue points come from tform.inverse(), from this line: ax.plot(tform.inverse(src)[:, 0], tform.inverse(src)[:, 1], '.b') I draw destination points in red, It looks like this : output image with inversed points in blue, and destination points in red. I have two questions about skimage.transform.PiecewiseAffineTransform. Destination points (red points) and output image is not coherent. Suppose the image and inversed points are changed by sin() waves. But the destination points are changed by 1-sin(). So what's the meaning of destination points? What is tform.inverse()? I looked up, and annotation says it apply inverse transformation. But Why the inverse transformation isn't between destination points(red points) and source points(source mesh)? In my view, mesh warp works like this (image from google) : mesh warp example from google. The man in the image should be warped follow the twisted mesh, which is the destination mesh. But the image in the astronaut example seems opposite from destination points. In other words, I think blue points in the the astronaut image should be destination points instead of inverse transformation. Thanks for all of you. Looking forward to your answer.
tagged with: python
score: 2
tagged with: scikit-image
tagged with: affinetransform
has comment: http://stackoverflow.com/comment/90504548
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91310696

http://stackoverflow.com/comment/90027386
comment on: http://stackoverflow.com/a/51528887
type: Comment
has text: @oryx Updated the answer.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90983146
has text: Could you please mark as solved? Or at least, explain why the answer is not what you were looking for.
comment on: http://stackoverflow.com/q/51614092
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89948469
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51489698
type: Comment
has text: for a number greater than 12. I guess you have to loop 1 from 12 then manually add in15,18,24. There are ways using a list to automate this, but the setup time is not worth taking rather than just manually put in 15,18,24,etc..

http://stackoverflow.com/q/51495728
answer count: 3
has comment: http://stackoverflow.com/comment/89964255
has title: Trouble in designing a game of guessing a list of numbers in python
has comment: http://stackoverflow.com/comment/89964086
downvote count: 1
accepted answer: http://stackoverflow.com/a/51496020
has body: Today I want to design a game to guess a list of number set by me. The player should print all the 5 numbers to win the game. And it is not allowed to print the repeated number. The code is as followed: def guess(): print "Please input a number smaller than 10, let's see if it is in my plan." print "You should figure out all the 5 numbers." n = int(raw_input('&gt;')) my_list = [1, 3, 5, 7, 9] your_list = [] count = 0 while count &lt; 5: if n in my_list: if n not in your_list: your_list.append(n) count = count + 1 print "Good job! You have got %d numbers!" % count n = int(raw_input('&gt;')) else: print "You have already typed that. Input again!" n = int(raw_input('&gt;')) else: print "That is not what I want." n = int(raw_input('&gt;')) print "Here you can see my plan:", my_list print "You are so smart to guess out, you win!" guess() when I tried to run it, I was very confused to see the result: Please input a number smaller than 10, let's see if it is in my plan You should figure out all the 5 numbers &gt;1 Good job! You have got 1 numbers &gt;2 That is not what I want &gt;3 Good job! You have got 2 numbers &gt;5 Good job! You have got 3 numbers &gt;7 Good job! You have got 4 numbers &gt;4 Here you can see my plan: [1, 3, 5, 7, 9] You are so smart to guess out, you win! When I type 4, it should print "That is not what I want" instead of indicating “win”. Why did it go wrong?
has comment: http://stackoverflow.com/comment/89964109
upvote count: 4
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51498338
tagged with: python-2.x
favorite count: 0
possible better answer: http://stackoverflow.com/a/51495937
has comment: http://stackoverflow.com/comment/89966901
has answer: http://stackoverflow.com/a/51495937
type: Question
has comment: http://stackoverflow.com/comment/89959482
has comment: http://stackoverflow.com/comment/89959723
tagged with: python
has comment: http://stackoverflow.com/comment/89959742
has answer: http://stackoverflow.com/a/51496020

http://stackoverflow.com/q/51497731
has answer: http://stackoverflow.com/a/51501438
accepted answer: http://stackoverflow.com/a/51501438
has comment: http://stackoverflow.com/comment/89970414
tagged with: python
has title: OpenPyXL: Is it possible to create a dropdown menu in an excel sheet?
has comment: http://stackoverflow.com/comment/89969231
type: AnsweredQuestion
upvote count: 19
tagged with: openpyxl
downvote count: 2
score: 17
possible better answer: http://stackoverflow.com/a/78109461
has comment: http://stackoverflow.com/comment/89969581
type: Question
has body: I'm attempting to store a list of valid ip addresses in a cell using openpyxl. At the moment the data is simply placed into a cell, and usually overflows into other cells. Using the code below: # Regex to return a tidy list of ip addresses in that block """ r = row to be checked s = source or destination columns iptc = ips to check """ def regex_ips(r, s): iptc = ['165.11.14.20', '166.22.24.0/24', '174.68.19.11', '165.211.20.0/23'] if r is not None: if s is not None: iptc = str(sheet.cell(r, s).value) san = re.sub('\n', ', ', iptc) sheet_report.cell(r, 8).value = san However, I would prefer if i could place these ip addresses into a dropdown list since that would be far easier to read - so my question is twofold, first, can this be done? because I couldn't find any info about it, And secondly, is there possibly a better way to display the data without it overflowing? Thanks for reading over this EDIT: added some example addresses and subnets to reflect what may be in a list.
has answer: http://stackoverflow.com/a/51498073
has comment: http://stackoverflow.com/comment/89971836
answer count: 3
has comment: http://stackoverflow.com/comment/89998312
has answer: http://stackoverflow.com/a/78109461
favorite count: 0

http://stackoverflow.com/q/51625529
has answer: http://stackoverflow.com/a/54504022
tagged with: tensorflow
upvote count: 5
type: Question
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/90226444
has body: All the official google tutorials use the one shot iterator for all the estimator api implementation, i couldnt find any documentation on how to use tf.data's initializable iterator and reinitializable interator instead of one shot iterator. Can someone kindly show me how to switch between train_data and test_data using tf.data's initializable iterator and reinitializable interator. We need to run a session to use feed dict and switch the dataset in the initializable iterator, its a low level api and its confusing how to use it part of estimator api architecture PS : I did find that google mentions "Note: Currently, one-shot iterators are the only type that is easily usable with an Estimator." But is there any work around within the community? or should we just stick with one shot iterator for some good reason
downvote count: 0
favorite count: 0
tagged with: tensorflow-datasets
tagged with: tensorflow-estimator
has title: How to use tf.data's initializable iterator and reinitializable interator and feed data to estimator api?
tagged with: python
has answer: http://stackoverflow.com/a/51633489
has comment: http://stackoverflow.com/comment/90216020
type: UnansweredQuestion

http://stackoverflow.com/comment/90120718
type: AnswerComment
type: Comment
has text: My question is basically, why Pandas developers make this behaviour different? Why can't a series always become row in DataFrame, irrespective of whether a list is provided or a single Series.
score: 0
comment on: http://stackoverflow.com/a/51577658

http://stackoverflow.com/comment/90065974
has text: You want `.objects`, not `.object`.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51549124

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

http://stackoverflow.com/a/51497042
type: Answer
score: 2
downvote count: 0
has body: As @taras said in the comments in this case you can work out an exact equation. If you substitute f[1] into f[0] and rearrange you get (if I didn't mess up my algebra) x^2(1+m^2) + x(-2*h + 2*m*y1 - 2*(m^2)*x1 - 2*m*k) + ((y1-m*x1 - k)^2 -r^2) = 0 You can use the standard equation x = (-b +- sqrt(b^2 - 4*a*c))/(2*a) where a is the coefficient of x^2, b is the coefficient of x^1 and c is the constant. It is worth noting that you are not guaranteed to get two real answers. You will get 2 complex answers if the line doesn't pass through the circle, two identical answers of the line touches the circle tangentially, or two real answers if the bisects the circle.
answers question: http://stackoverflow.com/q/51496051
upvote count: 2

http://stackoverflow.com/a/51567822
score: 1
has comment: http://stackoverflow.com/comment/90103611
upvote count: 1
has comment: http://stackoverflow.com/comment/90113865
has comment: http://stackoverflow.com/comment/90111807
has comment: http://stackoverflow.com/comment/90113716
has comment: http://stackoverflow.com/comment/90111943
has comment: http://stackoverflow.com/comment/90110570
has comment: http://stackoverflow.com/comment/90109708
downvote count: 0
has body: This sounds a lot like superoptimization (wikipedia). e.g. STOKE starts with a sequence of asm instructions and stochastically modifies it looking for shorter / faster sequences that do the same thing. (Or STOKE can start from scratch looking for an asm sequence that gives the desired result for a set of test-cases.) It's open source, so have a look at the algorithms they use to modify asm and test-run the code. Of course it's possible if you have data structures that represent operands and opcodes. See also Applying Genetic Programming to Bytecode and Assembly, an academic paper from 2014. I haven't read it, but hopefully it addresses ways to recombine code from different mutations and maybe get something useful more often than you get garbage that steps on the registers from the other code. (That's the major trick with random changes to code, especially in assembly where there are lots of non-useful instruction sequences.)
answers question: http://stackoverflow.com/q/51567447
type: Answer

deprecation-warning
tags question: http://stackoverflow.com/q/51617318
type: Tag
tag name: deprecation-warning

http://stackoverflow.com/comment/89977039
comment on: http://stackoverflow.com/q/51504087
has text: Please share the error you get, including the stack trace.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51504424
has comment: http://stackoverflow.com/comment/89977765
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
downvote count: 2
type: Question
has answer: http://stackoverflow.com/a/51504458
has title: Python pass by value
duplicate of: http://stackoverflow.com/q/986006
linked to: http://stackoverflow.com/q/845110
score: 0
duplicate of: http://stackoverflow.com/q/845110
answer count: 1
favorite count: 0
tagged with: python
has body: I'm a beginner for Python. I want to know some cases to pass by values instead of references. Assume we have the class: class myC(): def __init__(self, x): self.val = x and the functions: def myF1(myc): myc.val = 1 def myF2(myDict): myDict['a'] = 0 if we define the variable and call the function: a = myC(0) myDict = {} myF1(a) myF2(myDict) The value of the variable a and myDict will change since both user defined class and dictionary are mutable types. Is there ant method that just pass the value of the variable so that the variable itself won't change? If there are multiple ways, please let me know all of them. Thank you very much.

http://stackoverflow.com/comment/90084949
has text: @WillemVanOnsem do you mind reworking your example to work like `python3 manage.py run myscript.py`
comment on: http://stackoverflow.com/a/51536416
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51546935
score: 1
has answer: http://stackoverflow.com/a/51547022
downvote count: 0
possible better answer: http://stackoverflow.com/a/51547013
favorite count: 0
has answer: http://stackoverflow.com/a/51547016
has answer: http://stackoverflow.com/a/51547013
has title: How do I add multiple versions of a list (meaning I'm updating the list) to a list, without having all the lists within the list be exactly the same?
answer count: 3
has comment: http://stackoverflow.com/comment/90061631
linked to: http://stackoverflow.com/q/240178
tagged with: python
accepted answer: http://stackoverflow.com/a/51547022
duplicate of: http://stackoverflow.com/q/240178
upvote count: 1
has body: I'm having trouble getting the output I want. I want to create a list and have the first element of a new list be that initial list. Then I want to modify the first list, and have the new modified version of that list be the second element of the new list. Right now, this outputs [[2,3,4,5,5],[2,3,4,5,5]]. How would I modify it so that the output is [[1,2,3,4,5], [2,3,4,5,5]]? noChange = [1,2,3,4,5] lotsOfLists = [] lotsOfLists += [noChange] for i in range(4): noChange[i] += 1 lotsOfLists += [noChange] print(lotsOfLists) # current output: [[2, 3, 4, 5, 5], [2, 3, 4, 5, 5]] # WANT: [[1,2,3,4,5], [2,3,4,5,5]]
type: Question
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/90061670

http://stackoverflow.com/comment/90088818
comment on: http://stackoverflow.com/a/51560908
score: 0
type: AnswerComment
type: Comment
has text: my bad I am new here

http://stackoverflow.com/comment/90139611
comment on: http://stackoverflow.com/q/51585989
has text: Also, what does `im.point` do with negative `x`, `y` values?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51491948
upvote count: 2
answer count: 2
has title: Python how to align Python dataframe output to centre
tagged with: python
has answer: http://stackoverflow.com/a/51493740
tagged with: dataframe
type: UnansweredQuestion
has body: I want to align Python dataframe output to center of console or output file. I have tried below code: import pandas as pd import os cols = ('Employee Name','Employee AGE') df = pd.read_csv("C:/Pawni/Desktop/test.csv",names = cols) print(df.center(os.get_terminal_size().columns)) But it is giving error : AttributeError: 'DataFrame' object has no attribute 'center' So, it seems Center is not a attribute of dataframe. What other options available to print dataframe output to center of console.
tagged with: pandas
score: 2
has answer: http://stackoverflow.com/a/51492073
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/90083435
type: Comment
comment on: http://stackoverflow.com/a/51557328
type: AnswerComment
has text: Not really a question of masking a `NaN` - your code works fine with `toolz.compose()`, but if you put `lambda x: str(int(x))` as suggested in side comment - your are getting ValueError on import.
score: 0

http://stackoverflow.com/q/51541532
favorite count: 0
accepted answer: http://stackoverflow.com/a/51543880
has body: Surprisingly I have not found an answer to this question after looking around the internet. I am specifically interested in a 3d tensor. From doing my own experiments, I have found that when I create a tensor: h=torch.randn(5,12,5) And then put a convolutional layer on it defined as follows: conv=torch.nn.Conv1d(12,48,3,padding=1) The output is a (5,48,5) tensor. So, am I correct in assuming that for a 3d tensor in pytorch the middle number represents the number of channels? Edit: It seems that when running a conv2d, the input dimension is the first entry in the tensor, and I need to make it a 4d tensor (1,48,5,5) for example. Now I am very confused... Any help is much appreciated!
score: 10
tagged with: tensor
tagged with: pytorch
tagged with: python
tagged with: dimension
type: AnsweredQuestion
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/51543880
upvote count: 10
type: Question
has title: Which part of Pytorch tensor represents channels?
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51611743
has body: Try to implement below code to get the values of "Commodity Code" as output: for desc_list in driver.find_elements_by_class_name("dl"): print(desc_list.find_element_by_xpath("./dt[.='Commodity Code']/following-sibling::dd").text)
has comment: http://stackoverflow.com/comment/90189878
has comment: http://stackoverflow.com/comment/90188248
score: 0
accepted answer of: http://stackoverflow.com/q/51611689
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51611689
type: Answer

http://stackoverflow.com/a/51501437
has comment: http://stackoverflow.com/comment/89972080
has comment: http://stackoverflow.com/comment/89971614
has comment: http://stackoverflow.com/comment/89971351
type: Answer
has comment: http://stackoverflow.com/comment/89971451
upvote count: 2
has comment: http://stackoverflow.com/comment/89971316
downvote count: 1
has body: You can achieve it by: for i, current_d in enumerate(d): current_l = c[i::2] for e in current_l: current_d.update(e) d will contain the information that you want.
score: 1
answers question: http://stackoverflow.com/q/51501402

http://stackoverflow.com/comment/90001854
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51516510
type: Comment
has text: You should have something in the URL, e.g. `home/photo-edit/{image_pk}` to identify the image from the request.

http://stackoverflow.com/q/51499529
upvote count: 1
has body: How do I make a single large file of 8 GB accessible by all other worker nodes in dask? I have tried pd.read_csv() with chunksize and client.scatter but it is taking quite long. I am running it on macOS. This is my code: import time import pandas as pd import dask as dask import dask.distributed as distributed import dask.dataframe as dd import dask.delayed as delayed from dask.distributed import Client, progress client = Client(IP:PORT) print client print client.scheduler_info() f = [] chunksize = 10 ** 6 for chunk in pd.read_csv('file.csv', chunksize=chunksize): f_in = client.scatter(chunk) f.append(f_in) print "read" ddf = dd.from_delayed(f) ddf = ddf.groupby(['col1'])'col2'.sum() future = client.compute(ddf) print future progress(future) result = client.gather(future) print result Stuck with it. Thanks in advance!
score: 1
type: Question
answer count: 2
downvote count: 0
tagged with: dask-distributed
has title: Load a single large file from client to dask workers
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51504499
tagged with: dask
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51507077

http://stackoverflow.com/q/51558164
has comment: http://stackoverflow.com/comment/90083283
has answer: http://stackoverflow.com/a/51558464
favorite count: 0
has comment: http://stackoverflow.com/comment/90083330
type: Question
has comment: http://stackoverflow.com/comment/90083320
tagged with: python
answer count: 1
has body: I have two Python scripts. One is a properties file with a dictionary of key-value pairs. The other is my main Python script where I import the first file so that I can access the values to use as variables in my database connection string. The files are set up as follows: config.py db_config = {'DRIVER' : '{SQL SERVER}', 'server' : 'myserver1', 'database' : 'jira', 'Trusted_Connection' : 'yes'} main.py import pyodbc #properties file import config #Database setup conStr = ('DRIVER=' + str(config.db_config['DRIVER']) + ';server=' + str(config.db_config['server']) + ';database=' + str(config.db_config['database']) + ';Trusted_Connection=' + str(config.db_config['Trusted_Connection']) + ';') con = pyodbc.connect(conStr) cur = con.cursor() When I run this, I am getting this error: Traceback (most recent call last): File "C:\Users\deidle\Python\misplacedFields.py", line 9, in &lt;module&gt; ';Trusted_Connection=' + str(config.db_config['Trusted_Connection']) + ';') AttributeError: module 'config' has no attribute 'db_config' It was working at one point and then I went to run it again and started getting the error. I tried changing the name of the dictionary and made sure I had correct spelling of everything in the main file. I have tried researching to see if there is anything else that I need to do in order to work with the config.py file, but all posts and articles I've read have the format that I have now. Both files are in the same folder in my directory so there shouldn't be any issues with accessing the files.
score: 0
accepted answer: http://stackoverflow.com/a/51558464
upvote count: 1
downvote count: 1
has title: Unable to access Python dictionary in a properties file from the main file
has comment: http://stackoverflow.com/comment/90084366
type: AnsweredQuestion

http://stackoverflow.com/q/51496412
downvote count: 0
score: 1
tagged with: tensorflow
type: Question
has title: Distributed Tensorflow Estimator execution does not trigger evaluation or export
has answer: http://stackoverflow.com/a/51986843
tagged with: tensorflow-estimator
upvote count: 1
answer count: 1
tagged with: distributed-computing
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am testing distributed training with tensorflow Estimators. In my example I fit a simple sinus function with a custom estimator using tf.estimator.train_and_evaluation. After training and evaluation I want to export the model to have it ready for tensorflow serving. However the evaluation and export is only triggered when executing the estimator in non-distributed way. The model and Estimators are defined as follows: def my_model(features, labels, mode): # define simple dense network net = tf.layers.dense(features['x'], units=8, activation=tf.nn.tanh) net = tf.layers.dense(net, units=8, activation=tf.nn.tanh) net = tf.layers.dense(net, units=8, activation=tf.nn.tanh) net = tf.layers.dense(net, units=8, activation=tf.nn.tanh) net = tf.layers.dense(net, units=8, activation=tf.nn.tanh) net = tf.layers.dense(net, units=8, activation=tf.nn.tanh) net = tf.layers.dense(net, units=8, activation=tf.nn.tanh) net = tf.layers.dense(net, units=8, activation=tf.nn.tanh) # output layer predictions = tf.layers.dense(net, units=1, activation=tf.nn.tanh) if mode == tf.estimator.ModeKeys.PREDICT: # define output message for tensorflow serving export_outputs = {'predict_output': tf.estimator.export.PredictOutput({"predictions": predictions})} return tf.estimator.EstimatorSpec(mode=mode, predictions={'predictions': predictions}, export_outputs=export_outputs) elif mode == tf.estimator.ModeKeys.EVAL: # for evaluation simply use mean squared error loss = tf.losses.mean_squared_error(labels=labels, predictions=predictions) metrics = {'mse': tf.metrics.mean_squared_error(labels, predictions)} return tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops=metrics) elif mode == tf.estimator.ModeKeys.TRAIN: # train on mse with Adagrad optimizer loss = tf.losses.mean_squared_error(labels=labels, predictions=predictions) optimizer = tf.train.AdagradOptimizer(learning_rate=0.1) train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec(mode…

http://stackoverflow.com/comment/90216486
type: Comment
comment on: http://stackoverflow.com/q/51625776
type: QuestionComment
has text: Could you add expected output vs. actual output? That would be very helpful, though not strictly necessary.
score: 0

http://stackoverflow.com/comment/90273280
comment on: http://stackoverflow.com/q/51634251
has text: There is no such thing as a "linear dataset"...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51552104
has comment: http://stackoverflow.com/comment/90071269
type: Answer
answers question: http://stackoverflow.com/q/51552079
has comment: http://stackoverflow.com/comment/90071577
accepted answer of: http://stackoverflow.com/q/51552079
has comment: http://stackoverflow.com/comment/90071449
upvote count: 1
has body: There is no date column in sample data, but it seems need dt.hour: rng = pd.date_range('2017-04-03 10:10:12', periods=100, freq='120T') df = pd.DataFrame({'date': rng, 'requests': range(100)}) #print (df) df1 = df.groupby([df.date.dt.minute.rename('min'), df.date.dt.hour.rename('hour')])['requests'].count() print (df1) min hour 10 0 8 2 8 4 8 6 8 8 8 10 9 12 9 14 9 16 9 18 8 20 8 22 8 Name: requests, dtype: int64
has comment: http://stackoverflow.com/comment/90071416
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/q/51540305
has body: I want to create the following image, where the x-axis contains blocks of 1 month each. If the users monthly value is 1, the block should show green, if NaN (or 0) it will be red (or preferably blank). How can I achieve this with matplotlib, or any other package that could achieve this? Image: Data: Date chris.germany carol.clair ... dana.davis Jan-01 1 NaN 1 Feb-01 1 NaN NaN Mar-01 1 1 NaN Apr-01 1 1 1 May-01 1 1 NaN ... Dec-02 1 NaN NaN
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51505291
has comment: http://stackoverflow.com/comment/90049192
has comment: http://stackoverflow.com/comment/90049509
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51542365
answer count: 1
score: 0
tagged with: python
has title: Matplotlib - Stacked bar-chart for time-series, with blank spaces for NaNs
has answer: http://stackoverflow.com/a/51542365

http://stackoverflow.com/comment/90095659
has text: I thought it was installed with python, as when i searched it that was what it said
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51564332

http://stackoverflow.com/comment/89946840
comment on: http://stackoverflow.com/q/51488975
score: 0
has text: I am running it from terminal like "argument.py hello"
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51599075
answers question: http://stackoverflow.com/q/51598916
upvote count: 2
score: 2
has body: You can use set() operations, this will print elements common to the vowels and word: vowels = ['a','e','i','o','u'] word ="Milliwaysaaa" print(set(vowels) &amp; set(word)) Prints: {'i', 'a'}
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90008792
score: 1
has text: I assume `df1` is printed out wrong? Because seems like "Precipitation" is one of the values of the column `New Station`
comment on: http://stackoverflow.com/q/51520033
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51608087
downvote count: 1
has body: You need: temp = temp[temp['UID'].notna()]
answers question: http://stackoverflow.com/q/51607953
score: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/51520189
answer count: 2
has answer: http://stackoverflow.com/a/51520283
linked to: http://stackoverflow.com/q/46752347
downvote count: 0
score: 18
has title: Zero occurrences/frequency using value_counts() in PANDAS
possible better answer: http://stackoverflow.com/a/60836577
has body: I have a table containing dates and the various cars sold on each dates in the following format (These are only 2 of many columns): DATE CAR 2012/01/01 BMW 2012/01/01 Mercedes Benz 2012/01/01 BMW 2012/01/02 Volvo 2012/01/02 BMW 2012/01/03 Mercedes Benz ... 2012/09/01 BMW 2012/09/02 Volvo I perform the following operation to find the number of BMW cars sold everyday df[df.CAR=='BMW']['DATE'].value_counts() The result is something like this : 2012/07/04 15 2012/07/08 8 ... 2012/01/02 1 But there are some days when no BMW car was sold. In the result, along with the above I want the days where there are zero occurrences of BMW. Therefore, the desired result is : 2012/07/04 15 2012/07/08 8 ... 2012/01/02 1 2012/01/09 0 2012/08/11 0 What can I do to attain such a result?
tagged with: pandas
favorite count: 0
accepted answer: http://stackoverflow.com/a/51520283
tagged with: python
type: AnsweredQuestion
upvote count: 18
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/60836577

http://stackoverflow.com/q/51526531
answer count: 1
has answer: http://stackoverflow.com/a/51526578
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51526578
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90024089
tagged with: prettytable
has body: When I run: from prettytable import PrettyTable as PTable accounts = { 'user1': 'pass1', 'user2': 'pass2' } table = PTable(['Day', [*accounts.keys()]]) # creates empty table with headings print(table) My table looks like this: +-----+--------------------+ | Day | ['user1', 'user2'] | +-----+--------------------+ +-----+--------------------+ You can see that 'user1' and 'user2' are in the same column. How can I make it so that they are in separate columns? Thank you.
tagged with: python
has comment: http://stackoverflow.com/comment/90021758
has title: Python: How to unpack dictionary keys as separate items rather than one item
score: 0
has comment: http://stackoverflow.com/comment/90021840
upvote count: 1
tagged with: dictionary
downvote count: 1

http://stackoverflow.com/a/51571784
accepted answer of: http://stackoverflow.com/q/51571724
downvote count: 0
has comment: http://stackoverflow.com/comment/90109490
score: 4
answers question: http://stackoverflow.com/q/51571724
type: Answer
has comment: http://stackoverflow.com/comment/90109610
has body: os.getcwd() returns a current working directory, which means that any part of the script or other module may perform actions, that will make it's value change. Depending on your purpose you can use value of __file__ (along with helpers provided by os.path) to determine path to your module/test in the filesystem.
upvote count: 4
has comment: http://stackoverflow.com/comment/90109567
type: AcceptedAnswer

http://stackoverflow.com/q/51634576
tagged with: email
has title: Extract outlook email body and recipient email address using python
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90233891
has comment: http://stackoverflow.com/comment/90233771
downvote count: 0
has comment: http://stackoverflow.com/comment/90233677
has answer: http://stackoverflow.com/a/51654302
has comment: http://stackoverflow.com/comment/90262868
has answer: http://stackoverflow.com/a/60609619
type: Question
upvote count: 2
tagged with: outlook
has body: I am trying to extract outlook email body, recipient address, subject and received date. I was able to extract subject and received date but unable to extract body and recipient address: Below is my code for subject and received date: outlook = win32com.client.Dispatch('Outlook.Application').GetNamespace('MAPI') namespace = outlook.Session recipient = namespace.CreateRecipient("abc@xyz.com") inbox = outlook.GetSharedDefaultFolder(recipient, 6) messages = inbox.Items email_subject = [] email_date = [] email_date_time = [] for x in messages: sub = x.Subject received_date = x.senton.date() received_date_time = str(x.ReceivedTime) email_subject.append(sub) email_date.append(received_date) email_date_time.append(received_date_time) For body i am trying: for x in messages: body = x.Body print(body) but this is not working and i am getting the error below: Traceback (most recent call last): File "&lt;ipython-input-85-d79967933b99&gt;", line 2, in &lt;module&gt; sub = x.Body File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 516, in __getattr__ ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1) com_error: (-2147467259, 'Unspecified error', None, None)
tagged with: win32com
has answer: http://stackoverflow.com/a/52644849
has comment: http://stackoverflow.com/comment/90271474
has comment: http://stackoverflow.com/comment/90233598
answer count: 3

http://stackoverflow.com/q/51508274
linked to: http://stackoverflow.com/q/3906137
score: 0
has body: I want to open and read file Mappe1.csv but it is not working. I am using Python 3.6.5 Anaconda. I do not know what I am doing wrong. Any ideas? File Mappe1.csv contains: A;B;C 1;4;7 2;5;8 3;6;9 The python code for opening Mappe1.csv looks like the following: import csv class CSVAdapter: def read_csv(self): with open("C:/Users/User/PycharmProjects/General/DesignUploader/Mappe1.csv") as file: dialect = csv.Sniffer().sniff(file.read(1024)) csv_file = csv.reader(file.readlines(), dialect, quotechar='"') print("A") csv_file_list = [] for row in file: print("B") for row in csv_file: print("C") csv_file_list.append(row) return csv_file_list The printout is "A" only. "B" and "C" does not get printed which leads me to the conclusion that the file was not read correctly. Are there any python/windows settings required to allow Python to read a file? Thank you for your help!
has title: Reading a csv file in python
duplicate of: http://stackoverflow.com/q/10255273
has answer: http://stackoverflow.com/a/51508342
duplicate of: http://stackoverflow.com/q/11150155
duplicate of: http://stackoverflow.com/q/3906137
has answer: http://stackoverflow.com/a/51508428
has answer: http://stackoverflow.com/a/51508312
tagged with: http://stackoverflow.com/tag/csv
tagged with: windows
possible better answer: http://stackoverflow.com/a/51508428
tagged with: python
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89986086
duplicate of: http://stackoverflow.com/q/36561963
tagged with: file
has answer: http://stackoverflow.com/a/51508447
accepted answer: http://stackoverflow.com/a/51508312
type: Question
duplicate of: http://stackoverflow.com/q/36572993

http://stackoverflow.com/comment/89999706
comment on: http://stackoverflow.com/q/51515491
has text: The code you posted works fine (contrary to what I thought previously)
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/90191116
type: AnswerComment
has text: Well, `plt_z = np.abs( plt_z)` results in all positive values of `plt_z` which includes each value twice. So basically there is no negative `z` value in `plt_z`. You can print it to see for yourself. So basically in the second answer, you are just plotting everything twice on the positive x axis.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/51612886

http://stackoverflow.com/comment/90009536
comment on: http://stackoverflow.com/q/51520137
score: 0
type: QuestionComment
has text: But @GreenMatt I need to input only comma separated inputs and if I don't do so it gives a presentation error .
type: Comment

http://stackoverflow.com/comment/90077682
has text: all the picture is 28x28. But however the numbers of the picture is not correct,which caused this error.Thank you for giving me a hand.
comment on: http://stackoverflow.com/a/51552011
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89994358
type: Comment
type: QuestionComment
score: 0
has text: @WiktorStribiżew have updated the message with the text
comment on: http://stackoverflow.com/q/51512892

http://stackoverflow.com/comment/90060264
comment on: http://stackoverflow.com/q/51546235
type: QuestionComment
score: 0
has text: Possible duplicate of [How to unpack multiple dictionary objects inside list within a row of dataframe?](https://stackoverflow.com/questions/51528643/how-to-unpack-multiple-dictionary-objects-inside-list-within-a-row-of-dataframe)
type: Comment

http://stackoverflow.com/q/51554602
has answer: http://stackoverflow.com/a/78274449
type: Question
downvote count: 0
favorite count: 0
answer count: 3
tagged with: python
tagged with: pyproj
upvote count: 13
has body: I have the GeoJSON { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [[13.65374516425911, 52.38533382814119], [13.65239769133293, 52.38675829106993], [13.64970274383571, 52.38675829106993], [13.64835527090953, 52.38533382814119], [13.64970274383571, 52.38390931824483], [13.65239769133293, 52.38390931824483], [13.65374516425911, 52.38533382814119]] ] } } ] } which http://geojson.io displays as I would like to calculate its area (87106.33m^2) with Python. How do I do that? What I tried # core modules from functools import partial # 3rd pary modules from shapely.geometry import Polygon from shapely.ops import transform import pyproj l = [[13.65374516425911, 52.38533382814119, 0.0], [13.65239769133293, 52.38675829106993, 0.0], [13.64970274383571, 52.38675829106993, 0.0], [13.64835527090953, 52.38533382814119, 0.0], [13.64970274383571, 52.38390931824483, 0.0], [13.65239769133293, 52.38390931824483, 0.0], [13.65374516425911, 52.38533382814119, 0.0]] polygon = Polygon(l) print(polygon.area) proj = partial(pyproj.transform, pyproj.Proj(init='epsg:4326'), pyproj.Proj(init='epsg:3857')) print(transform(proj, polygon).area) It gives 1.1516745933889345e-05 and 233827.03300877335 - that the first one doesn't make any sense was expected, but how do I fix the second one? (I have no idea how to set the pyproj.Proj init parameter) I guess epsg:4326 makes sense at it is WGS84 (source), but for epsg:3857 I'm uncertain. Better results The following is a lot closer: # core modules from functools import partial # 3rd pary modules import pyproj from shapely.geometry import Polygon import shapely.ops as ops l = [[13.65374516425911, 52.38533382814119, 0], [13.65239769133293, 52.38675829106993, 0], [13.64970274383571, 52.38675829106993, 0], [13.64835527090953, 52.38533382814119, 0], [13.64970274383571, 52.38390931824483, 0], [13.65239769133293, 52.38390931824483, 0], [13.65374516425911, 52.38533382814119, 0]]…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90092869
has answer: http://stackoverflow.com/a/75590072
has answer: http://stackoverflow.com/a/51556743
score: 13
tagged with: geojson
has title: How do I get the area of a GeoJSON polygon with Python
has comment: http://stackoverflow.com/comment/124085144

http://stackoverflow.com/comment/90017661
has text: This is a neat function, but how do I further segment those values that are strictly AFTER the min value? I recieved this : id, value, condition 2, 1, 3, True 6, 1, 3, True 10, 2, 3, True however, index 2 should be false because its before the min(index 4). index 10 should be false because it too is before the min(index 12).
comment on: http://stackoverflow.com/a/51524262
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51617318
upvote count: 3
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: floating-point
has body: My code snippet is as follows: data,l = make_moons(100000) s = np.random.permutation(100000); temp1 = data[s[0:200],:] # Random Sampling of 200 columns temp2 = cdist(data,temp1) # Pairwise distance between two sets of observations C = np.exp(-temp2/sig) W = C[s[0:200],:] where make_moons is defined as: from math import pi def make_moons(n): """Create a 'two moons' dataset with n feature vectors, and 2 features per vector.""" assert n%2==0, 'n must be even' # create upper moon theta = np.linspace(-pi / 2, pi / 2, n/2) # create lower moon x = np.r_[np.sin(theta) - pi / 4, np.sin(theta)] y = np.r_[np.cos(theta), -np.cos(theta) + .5] data = np.c_[x, y] # Add some noise data = data + 0.03 * np.random.standard_normal(data.shape) # create labels labels = np.r_[np.ones((n//2, 1)), -np.ones((n//2, 1))] labels = labels.ravel().astype(np.int32) return data,labels I want to get some insight into the captioned warning. As I see, the arrays are floating type but why are they interpreted (or need to be) as integer?
has comment: http://stackoverflow.com/comment/90230512
score: 3
tagged with: deprecation-warning
has title: DeprecationWarning: object of type <class 'float'> cannot be safely interpreted as an integer
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90281398
downvote count: 0

http://stackoverflow.com/a/51501478
has comment: http://stackoverflow.com/comment/90045731
accepted answer of: http://stackoverflow.com/q/51499962
has comment: http://stackoverflow.com/comment/90044762
has comment: http://stackoverflow.com/comment/90347271
has comment: http://stackoverflow.com/comment/90316526
score: 4
answers question: http://stackoverflow.com/q/51499962
has comment: http://stackoverflow.com/comment/89975927
upvote count: 4
has comment: http://stackoverflow.com/comment/90044962
has comment: http://stackoverflow.com/comment/89978480
has comment: http://stackoverflow.com/comment/89975299
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90044297
has comment: http://stackoverflow.com/comment/90316481
has body: Instead of using Selenium, try to get required data with direct HTTP-requests: import requests import json s = requests.session() headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0"} r = s.get("https://www.flightradar24.com/data/airlines/kl-klm/routes", headers=headers) Data for each airport can be found in script node that looks like To get JSON from arrRoutes variable: my_json = json.loads(r.text.split("arrRoutes=")[-1].split(", arrDates=")[0]) You need to get abbreviation (value for "iata" key) for each airport: abbs_list = [] for route in my_json: if route["airport1"]["country"] == "Netherlands": abbs_list.append(route["airport2"]["iata"]) Output of print(abbs_list) should be like ['AAL', 'ABZ'...] Now we can request data for each airport: url = "https://www.flightradar24.com/data/airlines/kl-klm/routes?get-airport-arr-dep={}" for abbr in abbs_list: cookie = r.cookies.get_dict() headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0", "Content-Type": "application/json", "x-fetch": "true"} response = s.get(url.format(abbr), cookies=cookie, headers=headers).json() print(abbr, ": ", response["arrivals"]["Netherlands"]["number"]["flights"])
type: Answer

http://stackoverflow.com/comment/90172980
type: Comment
has text: By the way, why don't you just use `scan.select('PK','merchantInKey')`, as the API for [`aerospike.Scan.select`](https://www.aerospike.com/apidocs/python/scan.html#aerospike.Scan.select) actually suggests you do?
type: QuestionComment
comment on: http://stackoverflow.com/q/51599240
score: 0

http://stackoverflow.com/q/51497938
tagged with: python
has comment: http://stackoverflow.com/comment/90007781
score: 4
has comment: http://stackoverflow.com/comment/89965084
has comment: http://stackoverflow.com/comment/89964584
has answer: http://stackoverflow.com/a/51499147
upvote count: 4
has comment: http://stackoverflow.com/comment/89965832
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89963946
downvote count: 0
tagged with: scikit-learn
tagged with: countvectorizer
has answer: http://stackoverflow.com/a/63673390
has title: Python: CountVectorizer ignores one letter word "I"
favorite count: 0
has comment: http://stackoverflow.com/comment/89994454
type: Question
has body: I have a list called dictionary1. I use the following code to get sparse count matrices of texts: cv1 = sklearn.feature_extraction.text.CountVectorizer(stop_words=None) cv1.fit_transform(dictionary1) I notice however that list(set(dictionary1)-set(cv1.get_feature_names())) results in ['i']. So "i" is in my dictionary but CountVectorizer ignores it (presumably some default setting discards one-char words). In the documentation I could not find such an option. Can someone point me to the problem? Indeed I would like to keep "i" in my analysis, as it could refer to more personal language.
answer count: 2

http://stackoverflow.com/a/51519011
upvote count: 2
type: Answer
has body: You shouldn't do this. eval and exec are almost always to be avoided. In this case, we can build up a dictionary of keyword arguments and then use parameter expansion to pass them to the query. kwargs = {} params = qsearch.split(',') for item in params: b = item.split(':') kw = b[0].upper() val = b[1].strip() if kw == 'ID': kwargs['id__contains'] = val elif kw == 'TEST NAME': kwargs['id_test__test_main__descr__contains'] = val elif kw == 'TEST TYPE': kwargs['thread_ttype__contains'] = val elif kw == 'TEST GROUP': kwargs['thread_tgroup__contains'] = val ... activeThreads = t_threads.objects.filter(~Q(thread_status='DEAD'),**kwargs).select_related().distinct('thread_stag') (Note, there were a couple of other things in your code that I've changed: use descriptive variable names, only do the strip/upper once, and never iterate over range(len(something)) but over the thing itself.)
score: 2
accepted answer of: http://stackoverflow.com/q/51518894
answers question: http://stackoverflow.com/q/51518894
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/112493869
has text: Thanks for your advice. In that case was not appropriate. The problem was solved by migration to PyQt =)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/63578199
type: AnswerComment

bulkinsert
type: Tag
tag name: bulkinsert
tags question: http://stackoverflow.com/q/51549529

http://stackoverflow.com/comment/90134578
type: AnswerComment
score: 0
type: Comment
has text: @abarnert, i love your answer, but OP also mentioned "Is there some method of itertools that can do this". So, my answer is pointed towards that
comment on: http://stackoverflow.com/a/51584327

http://stackoverflow.com/comment/90118348
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51514373
type: Comment
has text: I got the xpath using inspect elements, then go to the element that you want, check the parent class/div and use it to get the webelement.

http://stackoverflow.com/comment/90112791
comment on: http://stackoverflow.com/q/51573410
has text: Do you intend to leave the program running indefinitely? A better idea would be to use a scheduler such as crontab.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90127788
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51581232
score: 0
has text: it doesnt work. it has this error TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'str'. perhaps it should work something like this ? not sure. i event tried your code with "US/Pacific"

http://stackoverflow.com/a/51583925
has comment: http://stackoverflow.com/comment/90134445
has comment: http://stackoverflow.com/comment/90134614
downvote count: 0
has comment: http://stackoverflow.com/comment/90134355
score: 4
accepted answer of: http://stackoverflow.com/q/51583908
answers question: http://stackoverflow.com/q/51583908
type: AcceptedAnswer
has body: Using idxmax df['Newcol']=0 df.loc[df.Value.ne(0).groupby(df['Group']).idxmax(),'Newcol']=1 df Out[41]: Group Value Target_Column Newcol 0 1 0 0 0 1 1 0 0 0 2 1 1 1 1 3 1 2 0 0 4 2 0 0 0 5 2 1 1 1 6 2 0 0 0 7 2 1 0 0
type: Answer
upvote count: 4

http://stackoverflow.com/a/51618093
answers question: http://stackoverflow.com/q/51612463
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90205562
has comment: http://stackoverflow.com/comment/90228222
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/90228660
has comment: http://stackoverflow.com/comment/90241093
has body: If you have the list of files ordered by class, you can interleave the datasets: import tensorflow as tf N = 4 record_files = ['class1.tfrecord', 'class5.tfrecord', 'class2.tfrecord'] M = len(record_files) dataset = tf.data.Dataset.from_tensor_slices(record_files) # Consider tf.contrib.data.parallel_interleave for parallelization dataset = dataset.interleave(tf.data.TFRecordDataset, cycle_length=M, block_length=N) # Consider passing num_parallel_calls or using tf.contrib.data.map_and_batch for performance dataset = dataset.map(parse_function) dataset = dataset.batch(N * M) EDIT: If you need also shuffling you can add it in the interleaving step: import tensorflow as tf N = 4 record_files = ['class1.tfrecord', 'class5.tfrecord', 'class2.tfrecord'] M = len(record_files) SHUFFLE_BUFFER_SIZE = 1000 dataset = tf.data.Dataset.from_tensor_slices(record_files) dataset = dataset.interleave( lambda record_file: tf.data.TFRecordDataset(record_file).shuffle(SHUFFLE_BUFFER_SIZE), cycle_length=M, block_length=N) dataset = dataset.map(parse_function) dataset = dataset.batch(N * M) NOTE: Both interleave and batch will produce "partial" outputs if there are no more remaining elements (see docs). So you would have to take special care if it is important for you that every batch has the same shape and structure. As for batching, you can use tf.contrib.data.batch_and_drop_remainder, but as far as I know there is not a similar alternative for interleaving, so you would either have to make sure that all of your files have the same number of examples or just add repeat to the interleaving transformation. EDIT 2: I got a proof of concept of something like what I think you want: import tensorflow as tf NUM_EXAMPLES = 12 NUM_CLASSES = 9 records = [[str(i)] * NUM_EXAMPLES for i in range(NUM_CLASSES)] M = 3 N = 4 dataset = tf.data.Dataset.from_tensor_slices(records) dataset = dataset.interleave(tf.data.Dataset.from_tensor_slices, cycle_length=NUM_CLASSES, block_length=N) dataset = dataset.appl…
score: 3
accepted answer of: http://stackoverflow.com/q/51612463

http://stackoverflow.com/q/51598114
has comment: http://stackoverflow.com/comment/90163943
has title: Converting doc files to text files
tagged with: converters
answer count: 1
tagged with: ms-word
favorite count: 0
has comment: http://stackoverflow.com/comment/90163148
has body: I have a list of MS word doc files in a directory. The directory also contains sub folders. I'm trying to convert all the document files in the directory to text files. Is there any way that I can do that without going much deeper into programming. Any shortcut or something like that?
accepted answer: http://stackoverflow.com/a/51601084
tagged with: python
tagged with: text
type: AnsweredQuestion
tagged with: document
downvote count: 1
has comment: http://stackoverflow.com/comment/90163034
type: Question
has comment: http://stackoverflow.com/comment/90166552
upvote count: 0
has comment: http://stackoverflow.com/comment/90163064
has answer: http://stackoverflow.com/a/51601084
score: -1

http://stackoverflow.com/comment/90135448
type: Comment
score: 0
has text: Thank you for helping me, i can javascript it.
type: AnswerComment
comment on: http://stackoverflow.com/a/51584949

http://stackoverflow.com/a/51676450
has comment: http://stackoverflow.com/comment/95412842
has body: Okay, so I've found a way to do it. I use the optimized graph (unquantized) and run the following command: tflite_convert --graph_def_file=optimized_graph.pb \ --output_file=output/optimized_graph_quantized.tflite \ --output_format=TFLITE \ --input_shape=1,299,299,3 \ --input_array=Mul \ --output_array=final_result \ --inference_type=QUANTIZED_UINT8 \ --std_dev_values=128 --mean_values=128 \ --default_ranges_min=-6 --default_ranges_max=6 \ --quantize_weights=true My main concern with the above is that when I don't specify min/max ranges I get the following message: "Array conv, which is an input to the Conv operator producing the output array conv_1, is lacking min/max data, which is necessary for quantization. Either target a non-quantized output format, or change the input graph to contain min/max information, or pass --default_ranges_min= and --default_ranges_max= if you do not care about the accuracy of results." I've changed the tf-for-poets android code to allow me to use the quantized tflite graph (basically the reverse of this - https://github.com/tensorflow/tensorflow/issues/14719) and I seem to be getting results that are as good as the original, unquantized graph.
accepted answer of: http://stackoverflow.com/q/51502539
answers question: http://stackoverflow.com/q/51502539
has comment: http://stackoverflow.com/comment/92306778
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/95398444
upvote count: 1
has comment: http://stackoverflow.com/comment/92405549
type: AcceptedAnswer

http://stackoverflow.com/q/51550899
answer count: 1
tagged with: calculator
has body: I'm working through Python Programming: An Introduction to Computer Science (2nd edition). At the end of the second chapter, one of the exercises is to design a calculator. Prior to this, he has been using eval() to do calculations. I know that using eval is bad for security, but I dont know how to get around using it. I could always use it now and worry about it later, but I want to build good habits. I want the user to enter their desired calculation as one line, like this: &gt;&gt;&gt; input('Input your expression: ') Input your expression: 4 * 5 / 2 I've already looked at this post Pros and Cons on designing a calculator with eval . The answer gave him a link that showed how you could get around it. The way he did it seemed quite convoluted, and I don't understand how he did it. I think I need eval() for this. My code for the calculator is below. Thank you for the help! # Calculator.py # This program will allow the user to input a mathematical expression (using python syntax) # it will then evaluate the expression and print the result. It will unfortunately use eval # but I dont know how to get around this problem. The program will loop to allow for # multiple calculations. expression = 'blank' print('Calculator') print(' ') print('Welcome! Please input your desired expression, using python syntax.') print('When you are finished, input end, and the program will finish.') # Until the user inputs end, the calculator will continue to repeat. while expression != 'end': print('') expression= input('Input your expression: ') # Checks if the last digit of expression is a digit. I think this is fairly foolproof. # I used last digit instead of first, bc a negative sign could have been in the first digit. if expression[len(expression)-1].isdigit(): print('= ', eval(expression)) # A way to distinguish between 'end' and other strings. After this prints and loops back, # program should end. elif expression == 'end': print('Shutting down... ') # If the user inputs something w…
type: UnansweredQuestion
tagged with: python
type: Question
linked to: http://stackoverflow.com/q/14515472
has answer: http://stackoverflow.com/a/51551017
has comment: http://stackoverflow.com/comment/90069137
score: 0
has title: Python 3 Calculator, how to get around eval
tagged with: eval

http://stackoverflow.com/q/51576863
has comment: http://stackoverflow.com/comment/90119329
type: AnsweredQuestion
tagged with: python-unicode
has body: I got a string and I want to re.sub this string in Python2, so I tried the following statement, it worked &gt;&gt;&gt; import re &gt;&gt;&gt; re.sub(u"[™®]", "", u"a™b®c") 'abc' But when I tried the following statement, it just failed on both Windows 10 (Python 2.7.15 |Anaconda, Inc.| (default, May 1 2018, 18:37:09) [MSC v.1500 64 bit (AMD64)] on win32). &gt;&gt;&gt; re.sub(ur"[\u2122\u00ae]", "", u"a™b®c") u'a?b?c' I've tried the the solution from Python and regular expression with Unicode, but it didn't work neither. &gt;&gt;&gt; myre = re.compile(ur'[\u2122\u00ae]', re.UNICODE) &gt;&gt;&gt; print myre.sub('', u"a™b®c") So why this happen and how can I fix this?
has comment: http://stackoverflow.com/comment/90119388
has comment: http://stackoverflow.com/comment/90177078
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90119307
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51576965
has comment: http://stackoverflow.com/comment/90176983
has comment: http://stackoverflow.com/comment/90119255
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/90176911
tagged with: regex
has comment: http://stackoverflow.com/comment/90119341
linked to: http://stackoverflow.com/q/393843
has title: why python2's re module can't identify the u'®' character
score: 1
possible better answer: http://stackoverflow.com/a/51576883
upvote count: 1
accepted answer: http://stackoverflow.com/a/51576965
has answer: http://stackoverflow.com/a/51576883
has comment: http://stackoverflow.com/comment/90119230
type: Question

http://stackoverflow.com/comment/90092701
has text: Sure. I will edit my question to include a minimal complete and verifiable example.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51562302
score: 0

http://stackoverflow.com/comment/90209898
type: Comment
comment on: http://stackoverflow.com/a/51601885
has text: Regarding `setuptools`: setuptools is great at building compartmentalized Python modules that go into PYTHON_PATH, not so great at installing system-wide configuration to go with a standalone application. (And it doesn't do much to help with build-time configuration). Whereas most Python programs are simple in terms of outside dependencies, this one adds several bits and pieces, so, we should be using a build tool that ensures those all go in the right place depending on what platform we're building from.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51507882
type: UnansweredQuestion
has title: Scrapy CrawlSpider not joining
tagged with: web-scraping
tagged with: python
tagged with: scrapy
has comment: http://stackoverflow.com/comment/89986597
type: Question
has body: I've been reading a lot here and other webs about scrapy and I can't fix this problem so I ask you :P Hope someone could help me. I want to authenticate a login in the main client page and then parse all the categories and then all the products and save the title of the product, its category, its quantity and its price. My code: # -*- coding: utf-8 -*- import scrapy from scrapy.item import Item, Field from scrapy.spiders import CrawlSpider from scrapy.spiders import Rule from scrapy.linkextractors import LinkExtractor from scrapy.loader.processors import Join from scrapy.contrib.spiders.init import InitSpider from scrapy.http import Request, FormRequest import logging class article(Item): category = Field() title = Field() quantity = Field() price = Field() class combatzone_spider(CrawlSpider): name = 'combatzone_spider' allowed_domains = ['www.combatzone.es'] start_urls = ['http://www.combatzone.es/areadeclientes/'] rules = ( Rule(LinkExtractor(allow=r'/category.php?id=\d+'),follow=True), Rule(LinkExtractor(allow=r'&amp;page=\d+'),follow=True), Rule(LinkExtractor(allow=r'goods.php?id=\d+'),follow=True,callback='parse_items'), ) def init_request(self): logging.info("You are in initRequest") return Request(url=self,callback=self.login) def login(self,response): logging.info("You are in login") return scrapy.FormRequest.from_response(response,formname='ECS_LOGINFORM',formdata={'username':'XXXX','password':'YYYY'},callback=self.check_login_response) def check_login_response(self,response): logging.info("You are in checkLogin") if "Hola，XXXX" in response.body: self.log("Succesfully logged in.") return self.initialized() else: self.log("Something wrong in login.") def parse_items(self,response): logging.info("You are in item") item = scrapy.loader.ItemLoader(article(),response) item.add_xpath('category','/html/body/div[3]/div[2]/div[2]/a[2]/text()') item.add_xpath('title','/html/body/div[3]/div[2]/div[2]/div/div[2]/h1/text()') item.add_xpath('quantity','//*[@id="ECS_FORM…
has answer: http://stackoverflow.com/a/51510155
score: 0
answer count: 1

http://stackoverflow.com/q/51635940
accepted answer: http://stackoverflow.com/a/51671782
tagged with: ponyorm
type: AnsweredQuestion
has title: Python Pony Orm Test if table is empty
downvote count: 0
has comment: http://stackoverflow.com/comment/90237944
score: 1
tagged with: database
has answer: http://stackoverflow.com/a/51671782
type: Question
has body: I would like to test if a table is empty using pony orm. At first I connect to the database and say generate mappings. I'm using the 'Names' table as an example here and connect to a postgres database from pony.orm import * class Names(db.Entity): name = Required(str) @db_session def populate_names(name_list): for name_element in name_list: db.insert("Names", name=name_element) @db_session def test_empty(): temp = False # if Names is empty, set temp = True if Names ... : temp = True return temp if __name__ == "__main__": characters = ['James', 'Elisabeth', 'Paul', ...] db = Database() db.bind(provider='postgres', user='', password='', host='', database='') # generate_mappings already creates empty tables db.generate_mapping(create_tables=True) empty = test_empty() if empty is True: populate_names(characters) I couldn't find anything in the Pony Docs about checking if a table is empty. if Names is None: The line above gives me 'False' because the table already exists. Does anyone know a solution to that?
has comment: http://stackoverflow.com/comment/90238433
upvote count: 1
has comment: http://stackoverflow.com/comment/90240519
has comment: http://stackoverflow.com/comment/90238315
answer count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/89968322
type: Comment
type: QuestionComment
has text: Possible duplicate of [Python: is isalnum() the same as isalpha with isdigit?](https://stackoverflow.com/questions/37762230/python-is-isalnum-the-same-as-isalpha-with-isdigit)
comment on: http://stackoverflow.com/q/51499207
score: 0

http://stackoverflow.com/comment/90130209
comment on: http://stackoverflow.com/a/51582135
type: AnswerComment
has text: Awesome! Learned something new myself ;)
score: 0
type: Comment

http://stackoverflow.com/q/51581677
tagged with: mixed-integer-programming
has body: Am trying to solve an optimization problem with Python pulp. Following is my basic LP model. prob = LpProblem("Minimizing cost", LpMinimize) A = LpVariable("A", lowBound=0, cat='Integer') B = LpVariable("B", lowBound=0, cat='Integer') C = LpVariable("C", lowBound=0, cat='Integer') prob += 1*A + 1.58*B + 2.98*C, "Objective function" prob += 2*A + 4*B + 8*C &gt;= content_requirement, "Content requirement" prob += A+B+C &lt;= 50 To this model, how can I add one more constraint to specify 45% of total content should be more than one largest item's content in the solution. Following are the few example cases. case1: Solver gives the solution A=5, B=0, C=0. (Here, A is the item with largest content as B and C are zeros). so the condition 45%(2*5 + 4*0 + 8*0) &gt;= 2 should be true. case2: Solver gives the solution A=3, B=2, C=0. (Here, B is the item with largest content as C is zero). so the condition 45%(2*3 + 4*2 + 8*0) &gt;= 4 should be true. case3: Solver gives the solution A=1, B=1, C=2. (Here, C is the item with largest content). so the condition 45%(2*1 + 4*1 + 8*2) &gt;= 8 should be true.
type: UnansweredQuestion
tagged with: pulp
tagged with: python
has title: How to write the condition in between some part of total content and single largest item's content in Linear Programming
has answer: http://stackoverflow.com/a/51632079
tagged with: mathematical-optimization
type: Question
score: 0
answer count: 1
tagged with: linear-programming

http://stackoverflow.com/q/51609688
has comment: http://stackoverflow.com/comment/90184147
downvote count: 1
type: Question
tagged with: ordereddictionary
possible better answer: http://stackoverflow.com/a/51610080
accepted answer: http://stackoverflow.com/a/51610026
has body: I have a dictionary of like: {'A': [0, 2, 5], 'B': [1], 'C': [3, 6, 9], 'D': [4, 7, 10], 'E': [8, 11, 13], 'F': [12]} and I would like to split it into multiple dictionaries (say 2), based on the differences of consecutive elements in the values lists. For example, above: dict_2 = {'A': [0, 2], 'E': [11, 13]} dict_3 = {'A': [2, 5], 'C': [3, 6, 9], 'D': [4, 7, 10], 'E': [8, 11]} So I compare consecutive values in each list, if the difference (i+1) - i is 2, I put it in dict_2, if it is 3, I put it in dict_3. I ignore the ones where there is only one element per list or the differences are other than 2 or 3. I am trying a rather cumbersome approach: def construct_dicts(init_dict, no_jumps=[2,3]): dct_2, dct_3 = {}, {} for key in init_dict.keys(): for index in range(len(init_dict[key])): if init_dict[key][index+1] - init_dict[key][index] = no_jumps[0]: dct_2[key] = [index, index + 1] elif init_dict[key][index+1] - init_dict[key][index] = no_jumps[1]: dct_3[key] = [index, index + 1] This however is cumbersome and ugly (and does not yet work). Is there a more pythonic way to do this?
has title: How to split a python dictionary into multiple dictionaries based on values
has comment: http://stackoverflow.com/comment/90184415
answer count: 2
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90184349
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51610026
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90184316
upvote count: 2
has answer: http://stackoverflow.com/a/51610080
has comment: http://stackoverflow.com/comment/90184664

http://stackoverflow.com/a/51540257
downvote count: 0
answers question: http://stackoverflow.com/q/51538818
upvote count: 2
type: Answer
score: 2
has body: I would say that the best solution is to use bind_all. Within the bound function you first need to figure out which canvas the mouse is over (and/or, which canvas has the focus), and then you can scroll that canvas.

http://stackoverflow.com/a/51601490
has comment: http://stackoverflow.com/comment/90169197
answers question: http://stackoverflow.com/q/51601393
has body: A verbose version with generator: a=[4, 5, 6, 7, 9,2, 6,8,9] def iterate(iterable): stop = False for i in iterable: if i == 6: if stop == False: stop = True continue elif i == 9: if stop == True: stop = False continue if stop == False: yield i print(sum(iterate(a))) # will sum 4, 5 and 2 Prints: 11
type: Answer
has comment: http://stackoverflow.com/comment/90169610
score: 0
has comment: http://stackoverflow.com/comment/90172652

http://stackoverflow.com/q/51489901
has answer: http://stackoverflow.com/a/51490012
has title: List and Maximum Numbers without using built in functions
downvote count: 3
type: Question
score: -2
has comment: http://stackoverflow.com/comment/89948550
possible better answer: http://stackoverflow.com/a/51489959
has body: I need some help with my assignment: Using a for loop, write a function called getMax4 that takes in a list of numbers. It determines and returns the maximum number that is divisible by 4. The function returns -999 if the argument is an empty list The function returns 0 if no number in the argument list is divisible by 4. The following shows sample outputs when the function is called: I've managed to do the following in my code: def getMax4(list): highest = 0 if len(list) == 0: return -999 else: for number in list: if number % 4 == 0: if number &lt; highest: highest = number else: highest = 0 return number print(getMax4([])) print(getMax4([1, 3, 9])) print(getMax4([-4, 3, -12, -8, 13])) print(getMax4([1, 16, 18, 12])) The Output for me was as follows: I don't understand why the value was determined as None, when it should be 0.
has answer: http://stackoverflow.com/a/51489978
answer count: 3
favorite count: 0
accepted answer: http://stackoverflow.com/a/51490012
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51489959
type: AnsweredQuestion

http://stackoverflow.com/a/51607694
type: Answer
has body: You can define your function: def myFun(row): if row['Size']&lt;2: return 'V1' elif row['Size']==2: return 'V2' else: return 'V3' and apply your function: df.loc[:, 'attribute']=df.apply(myFun, axis=1) Then: print(df) Output: Size attribute 0 2 V2 1 3 V3 2 1 V1 3 4 V3
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51607574

http://stackoverflow.com/comment/90056001
comment on: http://stackoverflow.com/q/51522356
score: 0
type: Comment
type: QuestionComment
has text: okay. Thank you!

http://stackoverflow.com/q/51621611
type: Question
has body: I have this view: class DamageListCriteria(TemplateView): template_name = "damage/damagelist_criteria.html" def get(self, request): form = DamageListCriteriaForm() general = General.objects.get(pk=1) args = { 'form': form, 'general': general } return render(request, self.template_name, args) def post(self, request): general = General.objects.get(pk=1) form = DamageListCriteriaForm(request.POST) form.non_field_errors() if form.is_valid(): fromdate = request.POST.get('fromdate') fdate = datetime.strptime(fromdate, '%d/%m/%Y') fdate = datetime.combine(fdate, datetime.min.time(), tzinfo=pytz.UTC) print('fdate ', fdate) todate = form.cleaned_data['todate'] #tdate = datetime.strptime(todate, '%d/%m/%Y') + timedelta(days=1) tdate = datetime.strptime(todate, '%d/%m/%Y') tdate = datetime.combine(tdate, datetime.max.time(), tzinfo=pytz.UTC) print('tdate ', tdate) d_list = Damage.objects.filter(entry_date__range=(fdate, tdate)) paginator = Paginator(d_list, 1) page = request.GET.get('page') try: damage_list = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. damage_list = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. damage_list = paginator.page(paginator.num_pages) template = "damage/damagelist_table.html" form = DamageListForm() general = General.objects.get(pk=1) fromdatetext = fdate.strftime('%d/%m/%Y') todatetext = tdate.strftime('%d/%m/%Y') args = { 'form': form, 'damage_list': damage_list, 'general': general, 'fromdate': fromdatetext, 'todate': todatetext } return render(request, template, args) else: print('form is not valid') print(form.errors) # form = DamageEntryForm() args = {'form': form, 'general': general } return render(request, self.template_name, args) I want to get some criteria to make a filtering listing of my database. It worked this way , until the moment i tried to add pagination. The url is http://127.0.0.1:8000/damage/damage/list/criteria/ url(r'dam…
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Django : view calls an other template (Pagination )
has answer: http://stackoverflow.com/a/51621757

http://stackoverflow.com/comment/90016055
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51523209
has text: @JonClements okay, tried to provide some input and output (updated my question).
score: 0

http://stackoverflow.com/comment/90064534
has text: I could have used `int(factorial(ilength - 1))` instead of the `//` division sub-expression.
comment on: http://stackoverflow.com/a/51548329
type: AnswerComment
score: 0
type: Comment

vader
tags question: http://stackoverflow.com/q/51565311
tag name: vader
tags question: http://stackoverflow.com/q/51502634
type: Tag

http://stackoverflow.com/q/51545033
has comment: http://stackoverflow.com/comment/90059361
has title: Java reading HTTP response (using StringBuilder) much slower than in python
has comment: http://stackoverflow.com/comment/90095547
has comment: http://stackoverflow.com/comment/90058846
has comment: http://stackoverflow.com/comment/90088706
has body: I'm calling a webservice that returns a large response, about 59 megabytes of data. This is how I read it from Java: BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); result = result.concat(this.getResponseText(in)); private String getResponseText(BufferedReader in) throws IOException { StringBuilder response = new StringBuilder(Integer.MAX_VALUE/2); System.out.println("Started reading"); String line = ""; while((line = in.readLine()) != null) { response.append(line); response.append("\n"); } in.close(); System.out.println("Done"); String r = response.toString(); System.out.println("Built r"); return r; } In Windows Resource manager during the reading I can see a throughput of about 100000 Bytes per second. However when I read exactly the same data from the same webservice in python, i.e.: response = requests.request("POST", url, headers=headers, verify=False, json=json) I can see throughput up to 700000 Bytes per second (about 7 times faster). And also the code is finished 7 times faster. The question is - Am I missing something that can make the reads in Java faster? Is this way really the fastest way how I can read HTTP response in Java? Update - even after I'm not reading, just going through the response, I'm still at at most 100000 bytes / seconds, so I believe that the bottleneck is somewhere in the way how Java reads: private List&lt;String&gt; getResponseTextAsList(BufferedReader in) throws IOException { System.out.println("Started reading"); List&lt;String&gt; l = new ArrayList&lt;String&gt;(); int i = 0; long q = 0; String line = ""; while((line = in.readLine()) != null) { //l.add(line); i++; q = q+line.length(); } in.close(); System.out.println("Done" + i + " " + q); return l; }
has comment: http://stackoverflow.com/comment/90090858
has comment: http://stackoverflow.com/comment/90095630
has comment: http://stackoverflow.com/comment/90094843
has comment: http://stackoverflow.com/comment/90058147
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90101117
has comment: http://stackoverflow.com/comment/90088092
tagged with: python
has comment: http://stackoverflow.com/comment/90058440
has comment: http://stackoverflow.com/comment/90099592
has comment: http://stackoverflow.com/comment/90058376
answer count: 0
linked to: http://stackoverflow.com/q/9105505
score: 0
tagged with: java
tagged with: http
type: Question
tagged with: stringbuilder
tagged with: performance
has comment: http://stackoverflow.com/comment/90088345
has comment: http://stackoverflow.com/comment/90101067

http://stackoverflow.com/comment/90209414
has text: Cool, this seems to work well! I'm going do so some profiling to see if it can be improved performance-wise, but I think this will work for now. Thanks!
comment on: http://stackoverflow.com/a/51620653
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51623561
has body: First constructing the full string and only then setting it as the line_a text should do the trick: text = '\n'.join("%s %.2f" % (x.name, average([d[x] for d in dataset])) for x in dataset.domain.attributes) self.line_a.setText(text)
accepted answer of: http://stackoverflow.com/q/51616145
answers question: http://stackoverflow.com/q/51616145
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/90225973
type: AcceptedAnswer
downvote count: 0

string
tags question: http://stackoverflow.com/q/51582546
tags question: http://stackoverflow.com/q/51590677
tags question: http://stackoverflow.com/q/51615174
tags question: http://stackoverflow.com/q/51541895
tags question: http://stackoverflow.com/q/51632275
tags question: http://stackoverflow.com/q/51513861
tags question: http://stackoverflow.com/q/51573309
tags question: http://stackoverflow.com/q/51551868
tags question: http://stackoverflow.com/q/51509915
tags question: http://stackoverflow.com/q/51482640
tags question: http://stackoverflow.com/q/51595920
tags question: http://stackoverflow.com/q/51610468
tags question: http://stackoverflow.com/q/51595492
tags question: http://stackoverflow.com/q/51530981
tags question: http://stackoverflow.com/q/51546348
tags question: http://stackoverflow.com/q/51584994
tags question: http://stackoverflow.com/q/51489309
tags question: http://stackoverflow.com/q/51553439
tags question: http://stackoverflow.com/q/51505796
tags question: http://stackoverflow.com/q/51541431
tags question: http://stackoverflow.com/q/51611027
tags question: http://stackoverflow.com/q/51601146
tags question: http://stackoverflow.com/q/51571981
tags question: http://stackoverflow.com/q/51624790
tags question: http://stackoverflow.com/q/51544451
tags question: http://stackoverflow.com/q/51528097
tags question: http://stackoverflow.com/q/51523063
tags question: http://stackoverflow.com/q/51488861
tags question: http://stackoverflow.com/q/51587502
tags question: http://stackoverflow.com/q/51571362
tag name: string
tags question: http://stackoverflow.com/q/51485167
tags question: http://stackoverflow.com/q/51543140
tags question: http://stackoverflow.com/q/51487677
tags question: http://stackoverflow.com/q/51534769
tags question: http://stackoverflow.com/q/51538192
tags question: http://stackoverflow.com/q/51625669
tags question: http://stackoverflow.com/q/51502947
tags question: http://stackoverflow.com/q/51598770
tags question: http://stackoverflow.com/q/51614375
tags question: http://stackoverflow.com/q/51603751
tags question: http://stackoverflow.com/q/51544427
tags question: http://stackoverflow.com/q/51570953
tags question: http://stackoverflow.com/q/51568874
type: Tag
tags question: http://stackoverflow.com/q/51617221
tags question: http://stackoverflow.com/q/51493313
tags question: http://stackoverflow.com/q/51521555
tags question: http://stackoverflow.com/q/51506177
tags question: http://stackoverflow.com/q/51539728
tags question: http://stackoverflow.com/q/51554088
tags question: http://stackoverflow.com/q/51612652
tags question: http://stackoverflow.com/q/51495909
tags question: http://stackoverflow.com/q/51545714
tags question: http://stackoverflow.com/q/51595370
tags question: http://stackoverflow.com/q/51561426
tags question: http://stackoverflow.com/q/51515720
tags question: http://stackoverflow.com/q/51601256
tags question: http://stackoverflow.com/q/51572720
tags question: http://stackoverflow.com/q/51602523
tags question: http://stackoverflow.com/q/51621069
tags question: http://stackoverflow.com/q/51528820
tags question: http://stackoverflow.com/q/51494604
tags question: http://stackoverflow.com/q/51625861
tags question: http://stackoverflow.com/q/51509206
tags question: http://stackoverflow.com/q/51592945
tags question: http://stackoverflow.com/q/51605270
tags question: http://stackoverflow.com/q/51598340
tags question: http://stackoverflow.com/q/51528213
tags question: http://stackoverflow.com/q/51636166
tags question: http://stackoverflow.com/q/51599280
tags question: http://stackoverflow.com/q/51492868
tags question: http://stackoverflow.com/q/51530899
tags question: http://stackoverflow.com/q/51484967
tags question: http://stackoverflow.com/q/51487012
tags question: http://stackoverflow.com/q/51612273

http://stackoverflow.com/comment/90091394
comment on: http://stackoverflow.com/q/51549352
has text: the-lay, I already do this blob detection through the ORB algorithm, but thanks for the suggestion. I really wanted to find the diameter of these blobs found.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90294020
type: QuestionComment
has text: See my updated answer... would have been much faster if you had posted the error in the original post, because it's immediately obvious that there's only 1 element in the array's 2nd axis
comment on: http://stackoverflow.com/q/51626747
score: 0
type: Comment

http://stackoverflow.com/q/51569850
has body: import random lotto = [] while True: a = random.randint(1, 45) lotto.append(a) if lotto.count(a) == 2: continue if len(lotto) == 7: break lotto.sort() print(lotto) I want to extract numbers of 1 to 45 without duplicates but sometimes two or three of the random numbers overlap. thanks to help.
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51569976
downvote count: 0
score: 1
has title: python - lottonum duplicate on extractor
type: Question
has answer: http://stackoverflow.com/a/51569919
answer count: 2
upvote count: 1

http://stackoverflow.com/comment/90195922
type: Comment
type: QuestionComment
has text: There is another way to parse - similar to SAX-parsing for xml. You can make tokenizer and then processor that calls functions according to tokens encoutered. You need to keep parsing context in one place available to each token function. It can be more effective if you like FSM stuff, but it's way more complicated code if you should fully parse message.
comment on: http://stackoverflow.com/q/51612985
score: 0

http://stackoverflow.com/comment/90239268
comment on: http://stackoverflow.com/a/51632717
has text: It seems that you also didn't read well enough the documentation because the 'o' do not work but the 'O' yes! So, correct your answer and I'll mark it as solved ;)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90026465
type: QuestionComment
has text: Unlike find_element, find_elements will not throw an exception and return an empty list if the elements cannot be located. Can you try using explicit wait and wait for the elements to appear? Is the elements inside an iframe?
score: 2
comment on: http://stackoverflow.com/q/51528985
type: Comment

http://stackoverflow.com/q/51584778
has comment: http://stackoverflow.com/comment/90136360
tagged with: eclipse
score: 0
accepted answer: http://stackoverflow.com/a/51592628
answer count: 1
has body: I'm new to Python (I used MATLAB before). What I want is showing all defined variables within an interactive console in real time, just like what MATLAB does. My system: Windows 10 64-bits with python 3.6.6. My IDE is Eclipse photon 4.8.0 with Pydev 6.4.3 For example, variable aaa is defined in the PyDev console [33], but the variable panel shows nothing. (please see the figure) But when I run the debugger and it holds at a breakpoint, variables are shown. So my question is: is there a way to show all variables defined in this interactive console all the time, not just during debugging? In short, I want an interface closed to MATLAB, so I can track variables constantly. Thanks for any help.
has title: How to see variables defined in a Python interactive console in real time in Pydev, Eclipse?
has answer: http://stackoverflow.com/a/51592628
tagged with: python
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90151253
tagged with: pydev
has comment: http://stackoverflow.com/comment/90150598
has comment: http://stackoverflow.com/comment/90154367

stock
tags question: http://stackoverflow.com/q/51494942
tags question: http://stackoverflow.com/q/51604425
tag name: stock
type: Tag

http://stackoverflow.com/a/51609453
score: 0
accepted answer of: http://stackoverflow.com/q/51609156
type: Answer
type: AcceptedAnswer
has body: You can make 2 lists. One for "INB" and one for "INS": INB = [], INS = [] for fil in glob.iglob('**/Desktop/SHAPE/**/' ,recursive = True): df = pd.read_table(fil).assign(col = get_folder(fil)) if fil.endswith('INS.shp'): INS.append(df) else: INB.append(df) INB_df = pd.concat(INB).to_csv('INB.csv') INS_df = pd.concat(INS).to_csv('INS.csv') For multiple categories, use a dictionary. For example: import os from collections import defaultdict d = defaultdict(list) for fil in glob.iglob('**/Desktop/SHAPE/**/' ,recursive = True): df = pd.read_table(fil).assign(col = get_folder(fil)) d[os.path.basename(fil)].append(df) for cat, lst in d.items(): pd.concat(lst).to_csv(cat)
answers question: http://stackoverflow.com/q/51609156

http://stackoverflow.com/comment/90216618
comment on: http://stackoverflow.com/q/51625716
score: 1
has text: It may be possible that you are writing the same frame multiple times, hence giving an illusion of low FPS. I would recommend you to attach a code snippet.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51548928
type: Question
has answer: http://stackoverflow.com/a/51549127
answer count: 2
has comment: http://stackoverflow.com/comment/90065875
downvote count: 0
has comment: http://stackoverflow.com/comment/90065698
tagged with: bash
tagged with: jupyter
accepted answer: http://stackoverflow.com/a/51549127
favorite count: 0
tagged with: jupyter-notebook
has body: I'm trying to invoke the gsutil command from a cell in a Jupyter notebook, using the bash cell magic %%bash, as such: %%bash gsutil However I am receiving the following output: bash: line 1: gsutil: command not found On the other hand, using the exclamation mark syntax gives me the expected result: !gsutil Gives... Usage: gsutil [-D] [-DD] [-h header]... [-m] [-o] [-q] [command [opts...] args...] Available commands: acl Get, set, or change bucket and/or object ACLs cat Concatenate object content to stdout...... The ! syntax doesn't support multi-line commands, and even if it did, as I am collaborating with others, I need the %%bash syntax to work for me. Can anyone enlighten me as to what the reason behind this is and how I can go about solving it? Thanks in advance.
possible better answer: http://stackoverflow.com/a/51831533
tagged with: python
has answer: http://stackoverflow.com/a/51831533
has comment: http://stackoverflow.com/comment/90065664
type: AnsweredQuestion
score: 1
has title: Bash cell magic (%%) giving "command not found" error in Jupyter notebook (Windows 7)
upvote count: 1

http://stackoverflow.com/comment/90054522
type: QuestionComment
score: 0
has text: I do not understand. Do you want the text to be centered in the polygon area? Or do you want the text to be rotated at an angle along one or more sides. You can draw angled text in ImageMagick using -annotate. See https://www.imagemagick.org/Usage/text/#annotate and https://www.imagemagick.org/script/command-line-options.php#annotate
comment on: http://stackoverflow.com/q/51541655
type: Comment

http://stackoverflow.com/comment/92499181
score: 0
comment on: http://stackoverflow.com/a/51524323
type: Comment
type: AnswerComment
has text: For combined importance the usual approach is F-test.

http://stackoverflow.com/q/51548211
tagged with: python
has comment: http://stackoverflow.com/comment/90093484
answer count: 0
score: 1
upvote count: 1
type: Question
tagged with: api
has title: Programming a flow in Twilio Programmable Number
tagged with: twilio-api
has comment: http://stackoverflow.com/comment/90168280
has body: I want to program a simple flow using Twilio's programmable number using voice. I want to ask user 4 questions and based on the 1st question (either yes or no) ask a different question and based on 2nd question (either yes or no) ask a different question and so on. So far, I've the following: from flask import Flask, request from twilio.twiml.voice_response import VoiceResponse, Gather import twilio app = Flask(__name__) @app.route("/voice", methods=['GET', 'POST']) def voice(): """Respond to incoming phone calls with a 'Hello world' message""" # Start our TwiML response resp = VoiceResponse() # Read a message aloud to the caller resp.say("Welcome to chatbot!", voice='alice') # Start our &lt;Gather&gt; verb with resp.gather(numDigits=1, action="/handle-key", method="POST") as g: g.say("""For sales, press 1. For marketing, press 2. """) print (resp) return str(resp) @app.route("/handle-key", methods=['GET', 'POST']) def handle_key(): """Handle key press from a user.""" digit_pressed = request.values.get('Digits', None) resp = VoiceResponse() print (digit_pressed) resp.say("You pressed " + str(digit_pressed)) return str(resp) @app.route('/sales', methods = ['GET', 'POST']) def sales(): pass @app.route('/marketing', methods = ['GET', 'POST']) def marketing(): pass if __name__ == "__main__": app.run(debug=True) My question is do I've to make new functions for each gather action or I can collect the digit pressed/ text (from speech of what user said) in the initial view (function voice) I've spent considerable time on this question and have not been able to come up with a definite answer.
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90164471
tagged with: twilio
type: UnansweredQuestion

http://stackoverflow.com/q/51535558
downvote count: 0
has comment: http://stackoverflow.com/comment/90042396
has comment: http://stackoverflow.com/comment/90043092
tagged with: pyinstaller
tagged with: python
tagged with: dependencies
favorite count: 0
has comment: http://stackoverflow.com/comment/90038886
type: UnansweredQuestion
has body: I am using pyinstaller for the first time. I used examples from youtube and stackoverflow too see if I would replicate the same results. However in my case it might seem that pyinstaller does not load the dependencies. For example I have the code: import time, request def main(): print('hello world!') time.sleep(5) if __name__ == '__main__': main() In the original example the person running it did not have to create hooks or anything extra. But I get ImportError: No module named request. Which makes me think something is wrong with my pyinstaller. It is version 3.3.1 and I am using python 2.7. It should be correct according to the documentation of pyinstaller. However it is not working :( Any help is really appreciated! :)
upvote count: 1
has title: pyinstaller not loading any dependencies
has answer: http://stackoverflow.com/a/51535668
score: 1
tagged with: executable
tagged with: import
type: Question
has comment: http://stackoverflow.com/comment/90042027
answer count: 1

http://stackoverflow.com/comment/89959644
type: Comment
comment on: http://stackoverflow.com/q/51495003
type: QuestionComment
score: 1
has text: At the moment you're just using standard DOM functions, not xpaths. Have a look at the docs at https://docs.python.org/3/library/xml.etree.elementtree.html#xpath-support and then try recreating your query as an xpath.

http://stackoverflow.com/comment/90015405
score: 0
comment on: http://stackoverflow.com/q/51523063
type: Comment
type: QuestionComment
has text: `i` is a separate reference to an object. Assigning new results to that name will not update any other references, including the indices in the original list. `i = i.split(',')` creates a new list and assigns the reference to `i`. Whatever `i` referenced before is not going to be affected.

http://stackoverflow.com/a/55336191
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51616637
upvote count: 1
score: 1
has body: I am late in replying to you but i hope this will help some one else. I was trying to have a two way communication where i can send and receive string data from both sides and here is what i did:- Arduino side:- void setup() { Serial.begin(9600); // begin transmission } void loop() { String val; while (Serial.available() &gt; 0) { val = val + (char)Serial.read(); // read data byte by byte and store it } Serial.print(val); // send the received data back to raspberry pi } On the raspberry side i have(python):- import serial port = "/dev/ttyACM0"#put your port here baudrate = 9600 ser = serial.Serial(port, baudrate) def tell(msg): msg = msg + '\n' x = msg.encode('ascii') # encode n send ser.write(x) def hear(): msg = ser.read_until() # read until a new line mystring = msg.decode('ascii') # decode n return return mystring while True: val = input() # take user input tell(val) # send it to arduino var = hear() # listen to arduino print(var) #print what arduino sent I hope it is clear that Arduino receives message from raspberry pi and sends the same thing back to Arduino. Similarly, you could do some other stuff with it.

http://stackoverflow.com/q/51631021
tagged with: statsmodels
score: 0
tagged with: pandas
answer count: 1
has body: I need the values of the autocorrelation coefficients coming from the autocorrelation_plot(). The problem is that the output coming from this function is not accessible, so I need another function to get such values. That's why I used acf() from statsmodels but it didn't get the same plot as autocorrelation_plot() does. Here is my code: from statsmodels.tsa.stattools import acf from pandas.plotting import autocorrelation_plot import matplotlib.pyplot as plt import numpy as np y = np.sin(np.arange(1,6*np.pi,0.1)) plt.plot(acf(y)) plt.show() So the result is not the same as this: autocorrelation_plot(y) plt.show()
has answer: http://stackoverflow.com/a/51632207
tagged with: python
type: AnsweredQuestion
has title: python - What produces the same plot as autocorrelation_plot()?
accepted answer: http://stackoverflow.com/a/51632207
type: Question

http://stackoverflow.com/q/51613004
accepted answer: http://stackoverflow.com/a/51613141
score: 8
has answer: http://stackoverflow.com/a/51613269
has body: In scikit learn I have a model (in my case a Linear model) clf = linear_model.LinearRegression() I can train this model with some data clf.fit(x1,y1) But if I call again fit it will continue training the model. clf.fit(x2,y2) Now clf is a model trained with both (x1,y1) and (x2,y2) If I want to start training from 0, I can create again the model by redefining clf clf = linear_model.LinearRegression() clf.fit(x1,y1) # save the model # ... clf = linear_model.LinearRegression() clf.fit(x2,y2) However I don't want to define clf again: Basically the type of regressor is chosen before, something like: if params.linear_algorithm == 'least_squares': clf = linear_model.LinearRegression() elif params.linear_algorithm == 'ridge': clf = linear_model.Ridge() elif params.linear_algorithm == 'lasso': clf = linear_model.Lasso() So I don't want inside my train function to redefine clf with all the conditional block, instead I just want to take clf, clean it from previous trainings and reuse it to train another set of data. Does clf have a method to clean what has learned so far, so when I call clf.fit(x2,y2) is only trained on this data? EDIT: You guys are right, the training is overwriten everytime. My problem is that I'm saving the model in a dictionary, and it just take the reference to clf, so each time clf is retrained all previous saves are changed. Redefining clf everytime creates a new object so each save points now so a different model Example for i in range(3): # get the x and y # ... clf.fit(x,y) model[i] = clf Any idea how to save every time a different model instead of pointing all model[i] to the same clf?
upvote count: 8
has title: Scikit learn: forget previous train data
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90191637
type: Question
has answer: http://stackoverflow.com/a/51613141
linked to: http://stackoverflow.com/q/32916255
answer count: 2
has comment: http://stackoverflow.com/comment/90191168
downvote count: 0
tagged with: scikit-learn
possible better answer: http://stackoverflow.com/a/51613269
favorite count: 0

lambda
tags question: http://stackoverflow.com/q/51637323
tags question: http://stackoverflow.com/q/51512367
tags question: http://stackoverflow.com/q/51548873
tags question: http://stackoverflow.com/q/51564120
tag name: lambda
tags question: http://stackoverflow.com/q/51626124
tags question: http://stackoverflow.com/q/51524430
type: Tag
tags question: http://stackoverflow.com/q/51588578
tags question: http://stackoverflow.com/q/51553634
tags question: http://stackoverflow.com/q/51630564
tags question: http://stackoverflow.com/q/51558378

http://stackoverflow.com/comment/89974393
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51502943
score: 3
has text: `sorted(list, key=lambda k: k['data']['price']) `

http://stackoverflow.com/comment/90219543
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51613686
has text: Thank you it worked

http://stackoverflow.com/q/51570181
has comment: http://stackoverflow.com/comment/90106535
accepted answer: http://stackoverflow.com/a/51570329
has comment: http://stackoverflow.com/comment/90106569
favorite count: 0
possible better answer: http://stackoverflow.com/a/51570327
has comment: http://stackoverflow.com/comment/90106648
tagged with: python
has answer: http://stackoverflow.com/a/51570329
type: AnsweredQuestion
downvote count: 0
score: 1
has title: pandas dataframe place rows with same column value together
type: Question
has answer: http://stackoverflow.com/a/51570327
has comment: http://stackoverflow.com/comment/90106536
has comment: http://stackoverflow.com/comment/90106599
has body: For the following dataframe, id name 0 1 a 1 2 b 2 3 c 3 4 b 4 5 a I want to get the following result Since the first row has name 'a', we would move all rows with name 'a' below the first row and pushing all other rows down. Then we would do the same for all other names (b, c..) maintaining the initial ordering of data id name 0 1 a 1 5 a 2 2 b 3 4 b 4 3 c How can I do that with pandas dataframe? I can think of iterating rows then remove the rows with the same name, and adding them below the current iterating row. I'm wondering if there's a better way. And I'm not sure if I can mutate dataframe as I iterate . edit Maitaining the initial order .. in a sense that you only move up a row if rows above it has the same name otherwise you don't change any ordering. And ordering of the rows with the same name is the same as the initial ordering (relatively)
answer count: 2
tagged with: pandas
upvote count: 1

http://stackoverflow.com/a/51524508
answers question: http://stackoverflow.com/q/51523248
has comment: http://stackoverflow.com/comment/90060074
has comment: http://stackoverflow.com/comment/90060190
has comment: http://stackoverflow.com/comment/90060415
has comment: http://stackoverflow.com/comment/90031829
downvote count: 0
has body: Doc2Vec will have a harder time with shorter texts – and it appears your texts may only be 5-10 tokens. Your texts also don't appear to be natural-language sentences - but rather product names. Whether Doc2Vec/Word2Vec-like analyses will do anything useful with such text fragments that don't have the same sort of co-occurrence diversity as natural spoken/written language will depend on the characteristics of the data. I'm not sure it would, but it ight – only trying/tweaking it will tell. But, it's not clear what your desired results should be. What kinds of product-names should be returned as most-similar? Same brand? Same color? (If either of those, you could use a much simpler model than Doc2Vec training.) Same specs, including memory? (If so, you wouldn't want to throw away numeric info – instead you might want to canonicalize it into single tokens that are meaningful at the word-by-word level that affects Doc2Vec, such as turning "64 GB" into "64gb" or "2 GB RAM" into "2gbram".) As this isn't regular natural language text, you likely have a very small constrained vocabulary - perhaps a few thousand tokens, rather than the tens-to-hundreds-of-thousands in normal language. And, each token may only appear in a small number of examples (a single producer's product line), and absolutely never appear with closely-related terms from similar competitive products (because product names don't mix proprietary names from competitors.) These factors will also present a challenge for this sort of algorithm – which needs many varied overlapping uses of words, and many words with fine-shades of meaning, to gradually nudge vectors into useful arrangements. A small vocabulary may require use of a much-smaller model (lower vector_size) to avoid overfitting. If you had a dataset which hinted which products people consider comparable – either mentioned in same reviews, or searched-for by same people, or bought by same-people – you might want to create extra synthetic text examples …
type: Answer
upvote count: 13
score: 13
has comment: http://stackoverflow.com/comment/90060344

http://stackoverflow.com/q/51542994
tagged with: archlinux
tagged with: pip
has comment: http://stackoverflow.com/comment/90056223
tagged with: python
has comment: http://stackoverflow.com/comment/90054842
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/90053884
score: 1
has comment: http://stackoverflow.com/comment/90055006
has comment: http://stackoverflow.com/comment/90466840
type: Question
has comment: http://stackoverflow.com/comment/90056340
has comment: http://stackoverflow.com/comment/90055236
has comment: http://stackoverflow.com/comment/90056332
has comment: http://stackoverflow.com/comment/90056124
upvote count: 1
has body: Some of my python packages installed with pip had conflicts with another package I tried installing using pacman. So I decided to uninstall all the packages installed with pip. I made a requirements.txt file with all the packages and started uninstalling them. It worked fine for a while but eventually gave this error: Traceback (most recent call last): File "/usr/bin/pip", line 11, in &lt;module&gt; load_entry_point('pip==10.0.1', 'console_scripts', 'pip')() File "/usr/lib/python3.6/site-packages/pkg_resources/__init__.py", line 479, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2703, in load_entry_point return ep.load() File "/usr/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2321, in load return self.resolve() File "/usr/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2327, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/usr/lib/python3.6/site-packages/pip/_internal/__init__.py", line 42, in &lt;module&gt; from pip._internal import cmdoptions File "/usr/lib/python3.6/site-packages/pip/_internal/cmdoptions.py", line 16, in &lt;module&gt; from pip._internal.index import ( File "/usr/lib/python3.6/site-packages/pip/_internal/index.py", line 15, in &lt;module&gt; from pip._vendor import html5lib, requests, six ImportError: cannot import name 'requests' I got a similar error everytime I tried running pip after that.
has comment: http://stackoverflow.com/comment/90056207
favorite count: 0
has title: Archlinux:pip: ImportError: cannot import name 'requests'
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90466671

http://stackoverflow.com/q/51574458
has comment: http://stackoverflow.com/comment/90115046
has title: 'class' object has no attribute 'object'
has comment: http://stackoverflow.com/comment/90115577
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90115092
has comment: http://stackoverflow.com/comment/90115038
tagged with: python-2.7
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90115765
has comment: http://stackoverflow.com/comment/90115005
has answer: http://stackoverflow.com/a/51581789
has body: What am i doing wrong here. I have been trying to figure this out for hours. I think i am having issues with Django get_context_data function. Error is 'PatientBedAllotmentList' object has no attribute 'object' views.py @method_decorator(login_required, name='dispatch') class PatientBedAllotmentList(ListView): model = BedAllotment template_name = 'room/bed_allotment_list.html' def get_context_data(self, **kwargs): context = super(PatientBedAllotmentList, self).get_context_data(**kwargs) start = BedAllotment.objects.get(id=self.object.id).allotment_date end = BedAllotment.objects.get(id=self.object.id).departure_date amount = BedCreate.objects.get(id=self.object.id).cost days_number = abs((end - start).days) days_number = int(days_number) amount_due = amount * days_number context['account_type'] = AccountUser.objects.get(user_id=self.request.user.id) hospital_id = AccountUser.objects.get(user_id=self.request.user.id).hospital_id allotment_details = BedAllotment.objects.filter(hospital_id=hospital_id) context['allotment'] = allotment_details context['amount'] = amount_due return context urls.py from django.conf.urls import url from medisaver.room import views urlpatterns = [ url(r'^room-category/create/$', views.RoomCategoryCreate.as_view(), name='room_category_create'), url(r'^room-category/list/$', views.RoomCategoryList.as_view(), name='room_category_list'), url(r'^room-category/update/(?P&lt;hospital_id&gt;[0-9A-Fa-f-]+)/(?P&lt;category_id&gt;[0-9]+)/$', views.RoomCategoryUpdate.as_view(), name='room_category_update'), url(r'^room-category/delete/(?P&lt;hospital_id&gt;[0-9A-Fa-f-]+)/(?P&lt;category_id&gt;[0-9]+)/$', views.RoomCategoryDelete.as_view(), name='room_category_delete'), url(r'^hospital-rooms/list/$', views.RoomList.as_view(), name='room_list'), url(r'^hospital-rooms/create/$', views.RoomCreateView.as_view(), name='room_create'), url(r'^hospital-rooms/update/(?P&lt;category_id&gt;[0-9]+)/(?P&lt;room_id&gt;[0-9]+)/$', views.RoomUpdate.as_view(), name='roo…
has comment: http://stackoverflow.com/comment/90128797
tagged with: django
has comment: http://stackoverflow.com/comment/90115207
tagged with: python
accepted answer: http://stackoverflow.com/a/51581789
possible better answer: http://stackoverflow.com/a/51575101
tagged with: django-views
has comment: http://stackoverflow.com/comment/90115554
has answer: http://stackoverflow.com/a/51575101
has comment: http://stackoverflow.com/comment/90115470

http://stackoverflow.com/comment/90282852
has text: If I install RPy2 with conda it also installs R (another version) changes R home folder and all sorts of stuff. I am an R user(meaning I have a working R installation with specific version that needs to be maintained on a system wide basis since I have many many many R jobs running and many proprietary R packages written and used. Now, I need to use Python and call functions from my proprietary R packages from Python. The issue I have is that it looks like people using RPy2 mostly use Python and just need to call some R functions and they do not care where and which version of R they have...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51486081
score: 1

http://stackoverflow.com/q/51562808
duplicate of: http://stackoverflow.com/q/20274077
has title: Shell script pass arguments to another shell script
has comment: http://stackoverflow.com/comment/90092885
type: Question
tagged with: bash
answer count: 1
has body: I'm writing a shell script that calls another shell script which calls a python script, and passes an argument throughout the whole chain like so: Directory structure: first scripts |- second |- third first #!/usr/bin/env bash date=$1 p=$2 (cd ./scripts/ &amp;&amp; ./second "$p") second #!/usr/bin/env bash function myFunction() { ./third $1 } myFunction third #!/usr/bin/env python import sys p = sys.argv[1] print("I got " + p) I know it's a mess, but I need this to work in this way for now. When I try ./first 20180716 0.5 I expect this code to print "I got 0.5", but the python script seems to complain: Traceback (most recent call last): File "./third", line 4, in &lt;module&gt; p = sys.argv[1] IndexError: list index out of range Which means that nothing seems to be passing to ./third. Any ideas?
score: 0
has comment: http://stackoverflow.com/comment/90092798
tagged with: python
tagged with: shell
has comment: http://stackoverflow.com/comment/90092542
has comment: http://stackoverflow.com/comment/90092826
has comment: http://stackoverflow.com/comment/90092774
has comment: http://stackoverflow.com/comment/90092751
linked to: http://stackoverflow.com/q/20274077
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90093194
has answer: http://stackoverflow.com/a/51563155
has comment: http://stackoverflow.com/comment/90092693
has comment: http://stackoverflow.com/comment/90093604
has comment: http://stackoverflow.com/comment/90092564

http://stackoverflow.com/comment/90203405
comment on: http://stackoverflow.com/q/51599488
score: 0
type: Comment
has text: I installed with conda
type: QuestionComment

http://stackoverflow.com/a/51594859
has comment: http://stackoverflow.com/comment/90156249
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90156074
score: 1
has body: Using str.split Ex: import pandas as pd df = pd.DataFrame({"Path": ['C:\\Users\\user\\Desktop\\SHAPE\\45554\\INS\\INS.shp', 'C:\\Users\\user\\Desktop\\SHAPE\\45554\\INB\\INB.shp', 'C:\\Users\\user\\Desktop\\SHAPE\\32456\\INS\\INS.shp', 'C:\\Users\\user\\Desktop\\SHAPE\\32456\\INB\\INB.shp']}) df['col'] = df["Path"].str.split(r"\\").str[-3] print(df) Output: Path col 0 C:\Users\user\Desktop\SHAPE\45554\INS\INS.shp 45554 1 C:\Users\user\Desktop\SHAPE\45554\INB\INB.shp 45554 2 C:\Users\user\Desktop\SHAPE\32456\INS\INS.shp 32456 3 C:\Users\user\Desktop\SHAPE\32456\INB\INB.shp 32456
downvote count: 0
answers question: http://stackoverflow.com/q/51594725
has comment: http://stackoverflow.com/comment/90156490
has comment: http://stackoverflow.com/comment/90155940

http://stackoverflow.com/q/51621069
has title: Search for a string that contains numbers python
type: Question
has comment: http://stackoverflow.com/comment/90207633
has answer: http://stackoverflow.com/a/51621200
accepted answer: http://stackoverflow.com/a/51621200
has answer: http://stackoverflow.com/a/51621222
tagged with: string
has body: So I have the following code: cus_str = "show configuration " #intiate router command string variable with open(var) as config_file: #open file for line in config_file: #line by line reading of file if '"xe-" + #anynumber + "/" #anynumber + "/" + #anynumber' in line: line = line.replace('\n' , '').replace('"' , '').replace(']' , '') #removes all extra characters i = "| except " + (line.split("cust ", 1)[1]) + " " #split the line and save last index (cust name) cus_str+=i #append to string config_file.close() The line: if '"xe-" + #anynumber + "/" #anynumber + "/" + #anynumber' in line: Is what I'm struggling with syntax-wise. I am looking to see if a line in the file contains the following string: "xe-number/number/number" (ex: "xe-6/1/10"). It will always have this format, but the numbers will change. What sort of syntax would I use to do this most efficiently. Thanks!
answer count: 3
possible better answer: http://stackoverflow.com/a/51621222
upvote count: 1
tagged with: regex
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51621291
tagged with: digits
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/q/51532832
downvote count: 1
favorite count: 0
tagged with: xpath
possible better answer: http://stackoverflow.com/a/51533561
has comment: http://stackoverflow.com/comment/90051597
tagged with: webdriverwait
has comment: http://stackoverflow.com/comment/90033488
has answer: http://stackoverflow.com/a/51533561
tagged with: python
has comment: http://stackoverflow.com/comment/119896892
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/90047858
has title: How do I send text into a textarea through Selenium and Python as per the HTML
type: AnsweredQuestion
tagged with: selenium
type: Question
has answer: http://stackoverflow.com/a/51533181
accepted answer: http://stackoverflow.com/a/51533181
has comment: http://stackoverflow.com/comment/90033937
has comment: http://stackoverflow.com/comment/90033719
linked to: http://stackoverflow.com/q/44834358
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/7534622
has body: Cannot figure out how can I write text into a popup, here is how the pop-up looks like: This is how I tried to access it by using XPath: driver.find_element_by_xpath("/html/body/div/div[1]/textarea").send_keys("Some text here") Getting error that element is not found on the page: selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div/div[1]/textarea I used as well css_selector to access element, but still same error. How can I access popup properly? Here is more HTML code: https://pastebin.com/6jdix2Cm
upvote count: 1

xlrd
tags question: http://stackoverflow.com/q/51557701
tags question: http://stackoverflow.com/q/51620440
tags question: http://stackoverflow.com/q/51597773
tags question: http://stackoverflow.com/q/51556281
type: Tag
tags question: http://stackoverflow.com/q/51504789
tags question: http://stackoverflow.com/q/51557646
tag name: xlrd
tags question: http://stackoverflow.com/q/51567572

http://stackoverflow.com/comment/89943168
comment on: http://stackoverflow.com/q/51487012
type: Comment
type: QuestionComment
has text: Do you understand what the code that you have posted is doing?
score: 1

http://stackoverflow.com/comment/90164466
has text: The "randomness" that you are observing stems from the nature of `set` since it is an unordered collection
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51599188

http://stackoverflow.com/q/51531900
favorite count: 0
has body: I am following this (https://code.djangoproject.com/wiki/Barcodes) tutorial to handle bar code generation of my site MyBarcodeDrawing("HELLO WORLD").save(formats=['gif','pdf'],outDir='.',fnRoot='barcode') the line above saving the created bar code into the current directory, but i want to directly store this into s3 how can i achieve that?
tagged with: django-1.11
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
score: 1
tagged with: reportlab
type: Question
downvote count: 0
tagged with: boto3
tagged with: python-3.6
has title: Report lab Bar code Generation store file to S3?

http://stackoverflow.com/a/51496354
answers question: http://stackoverflow.com/q/51494257
has body: You are not supposed to use Dialect 1. It was obsoleted with releases of Interbase 6 and Firebird 0.9 in 2000. It is sole intention is backward compatibility with pre-2000 database server versions for pre-2000 legacy applications. In 2018 this purpose has little practical value and hence Dialect 1 not only blocks you from using most recent language and engine enhancements, but maybe outright buggy due to little real world exposure thus little out of the house testing. You have to migrate your database to Dialect 3. Checking and ironing out all the incompatibilities that the database creator maybe introduced to it, coding it by pre-2000 language, along your migration. http://www.firebirdfaq.org/faq24/ http://www.firebirdfaq.org/faq186/ https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-background.html
score: 0
type: Answer

http://stackoverflow.com/a/51573414
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51572846
downvote count: 0
type: Answer
has body: In both examples, your code launches a subprocess. That subprocess, which has its own environment, attempts to run the "source" command, and then exits. Since the subprocess has its own environment, this has no effect on the current process. Assuming your end goal is to run some other command in the subprocess, you should just run it directly. You don't specifically need to activate the virtual environment. subprocess.call(["./env/bin/pip", "list"]) Avoid using the shell=True option if at all possible; it can be quite dangerous if you're not extremely careful with it. If you really need to set the environment variables that the activate script sets in this script, you need to manually set them in os.environ. You can read the activate script to see what they are. They usually won't matter, though.

http://stackoverflow.com/comment/90059198
type: Comment
type: QuestionComment
has text: Maybe spend some time browsing [The Gallery](https://matplotlib.org/gallery/index.html). I highly recommend working through [The Tutorials](https://matplotlib.org/tutorials/index.html) - it will help you understand where to look for the customizations you want to accomplish (now and in the future).
comment on: http://stackoverflow.com/q/51545523
score: 0

http://stackoverflow.com/comment/90033825
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51533021
has text: @sachinsafale rps slide is empty
type: Comment

http://stackoverflow.com/a/51498573
answers question: http://stackoverflow.com/q/51498368
accepted answer of: http://stackoverflow.com/q/51498368
type: AcceptedAnswer
score: 0
has body: I am not sure why you required input as the dictionary. but if you pass elements as numpy array it converts missing values with NaN. pd.DataFrame([np.array([1,2,3]),np.array([1,2,3,4]),np.array([6,7])],columns=['A','B','C','D']) Output:- A B C D 0 1 2 3.0 NaN 1 1 2 3.0 4.0 2 6 7 NaN NaN
type: Answer

http://stackoverflow.com/q/51615916
type: Question
tagged with: python-itertools
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51616577
tagged with: http://stackoverflow.com/tag/csv
has body: I am currently looking to build a script that takes .txt files (tab delimited) and converts them to .csv. I am getting and error that says (a bytes-like object is required, not 'str') when running the following code. What is the best way to complete this operation? import csv import itertools txt_file_P_T = r"mytxt_P_T.txt" txt_file_P_C = r"mytxt_P_C.txt" txt_file_S_T = r"mytxt_S_T.txt" txt_file_S_C = r"mytxt_S_C.txt" csv_file_P_T = r"mycsv_P_T.csv" csv_file_P_C = r"mycsv_P_C.csv" csv_file_S_T = r"mycsv_S_T.csv" csv_file_S_C = r"mycsv_S_C.csv" text_list = [txt_file_P_T, txt_file_P_C, txt_file_S_T, txt_file_S_C] csv_list = [csv_file_P_T, csv_file_P_C, csv_file_S_T, csv_file_S_C] for i, j in zip(text_list, csv_list): in_txt = csv.reader(open(i, "rt"),) out_csv = csv.writer(open(j, 'wb')) out_csv.writerows(in_txt)
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90200122
linked to: http://stackoverflow.com/q/33054527
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90198114
accepted answer: http://stackoverflow.com/a/51616577
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90198101
has title: Iterate through parallel lists and convert tab delimited text in one list to csv path in other
score: 1

http://stackoverflow.com/comment/89981532
type: Comment
has text: thanks wim - for your second code block, is there a way to return the output in the function? I know your code works when i try to print a list of the function, but was wondering if you can do everything from within the function.
comment on: http://stackoverflow.com/a/51489449
type: AnswerComment
score: 0

http://stackoverflow.com/q/51566338
has title: Showing cropped image in bokeh
type: Question
has body: I am showing a picture in a figure in bokeh and am using the BoxSelectTool in order to draw a rectangle. box_select = BoxSelectTool(callback=callback) p2 = figure(x_range=(0,700), y_range=(0,500),plot_width=1100,plot_height=1100,tools=[box_select]) p2.image_url( url='url', x=1, y=1, w=700, h=500, anchor="bottom_left",source=im_src) rect_source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[])) callback = CustomJS(args=dict(rect_source=rect_source), code=""" // get data source from Callback args var data = rect_source.data; /// get BoxSelectTool dimensions from cb_data parameter of Callback var geometry = cb_data['geometry']; /// calculate Rect attributes var width = geometry['x1'] - geometry['x0']; var height = geometry['y1'] - geometry['y0']; var x = geometry['x0'] + width/2; var y = geometry['y0'] + height/2; /// update data source with new Rect attributes data['x'].push(x); data['y'].push(y); data['width'].push(width); data['height'].push(height); rect_source.data = data; rect_source.change.emit(); ''' Now I want to show that image region as cropped in a different, smaller figure, after the rectangle is drawn, without clicking a button or anything: d2 = figure(x_range=(0,200), y_range=(0,100),plot_width=200,plot_height=100) d2.image( image='image', x=1, y=1, dw=100, dh=100, source=img) img = ColumnDataSource( data=dict(image=[])) So I need something like this in JS: tmp_im = cv2.imread('static/' + str(im_nr) + '.jpg') tmp_im = tmp_im[geometry['y0']:geometry['y1'],geometry['x0']:geometry['x1']] tmp_im = cv2.cvtColor(tmp_im, cv2.COLOR_BGR2GRAY) img.data = dict(image=[tmp_im]) How can I do that in JS + bokeh?
has comment: http://stackoverflow.com/comment/90238344
tagged with: javascript
score: 12
has answer: http://stackoverflow.com/a/59239208
answer count: 1
tagged with: user-interface
has comment: http://stackoverflow.com/comment/90230469
favorite count: 0
upvote count: 12
type: UnansweredQuestion
tagged with: python
downvote count: 0
tagged with: bokeh

http://stackoverflow.com/a/51487762
type: Answer
upvote count: 4
downvote count: 0
has body: Since you already using numpy (np.nan in there) you should use ndarrays, not lists. But you can convert back if you want: &gt;&gt;&gt; a = np.array(mylist1) &gt;&gt;&gt; a[np.isnan(a)] = mylist2 &gt;&gt;&gt; a.astype(int).tolist() [1, 2, 3, -10, -11, 4, -12, 5]
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51487737
accepted answer of: http://stackoverflow.com/q/51487737

http://stackoverflow.com/comment/90060744
score: 2
comment on: http://stackoverflow.com/q/51546408
has text: What is it you're trying to do ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90100640
type: AnswerComment
comment on: http://stackoverflow.com/a/51566804
score: 0
type: Comment
has text: No, I'm missing something -- that should be the permutations of (a[0], a[2]) crossed with (product) the permutations of (a[1], a[4]). On my way oout the door, or I'd fix the pseudo-code and test it.

http://stackoverflow.com/a/51527931
downvote count: 0
upvote count: 2
has body: What you want to do is write your own TextIOBase class (or, if you want binary data, write your own RawIOBase and then wrap a stock TextIOWrapper around it), where you can put whatever behavior you want. As you can see from the docs. all you need to implement for TextIOBase is detach, read, readline, and write. And the first three aren't relevant for what you're doing. So, what should your write look like? Well, it depends on what you want to do. it sounds like your goal is to tee everything to both real stdout and to a StringIO. If so, this is pretty trivial. The only question is what you want to do if one of the targets raises an exception, or writes fewer bytes than the other, etc. Since an IOString is never going to do either of those, we can write something really dumb that just assumes that whatever real stdout did was the right thing to do. class TeeTextIO(io.TextIOBase): def __init__(self, target): self.target = target self.stringio = io.StringIO() def write(self, s): writecount = self.target.write(s) self.stringio.write(s[:writecount]) return writecount And now: stdout = sys.stdout sys.stdout = TeeTextIO(sys.stdout) threads_conn(connect, devices) #- here many threads starts with many print inside output = sys.stdout.stringio.getvalue() sys.stdout = stdout Now, the output has gone to the real stdout as it came in, but it's also been stored in the StringIO for whatever you want to do with it later. (Notice that this class will work with any TextIOBase, like a file you open, not just with stdout. It didn't cost us anything to make it general, so why not?) What if you wanted to do something totally different, like spread each write randomly among 10 different files? It should be obvious: class SpreadTextWriter(io.TextIOBase): def __init__(self, *files): self.files = files def write(self, s): return random.choice(self.files).write(s)
has comment: http://stackoverflow.com/comment/90024642
type: Answer
has comment: http://stackoverflow.com/comment/90024897
accepted answer of: http://stackoverflow.com/q/51527750
answers question: http://stackoverflow.com/q/51527750
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/90015644
comment on: http://stackoverflow.com/q/51523280
score: 0
has text: @juanpa.arrivillaga Thank you for your comment. This job will be done so many times over the running time, so I want to optimize it and thought using loops wouldn't be the best option.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51602523
type: Question
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/51603815
score: 0
answer count: 2
has body: I have a dataset as below; "birth_date_1:25 birth_date_2:august birth_date_3:1945 birth_place_1:france death_date:&lt;none&gt; " "birth_date_1:14 birth_date_2:june birth_date_3:1995 birth_place_1:dv≈Ør birth_place_2:kr√°lov√© birth_place_3:nad birth_place_4:labem birth_place_5:, birth_place_6:czech birth_place_7:republic " "birth_date_1:21 birth_date_2:february birth_date_3:1869 birth_place_1:blackburn birth_place_2:, birth_place_3:england death_date_1:12 death_date_2:march death_date_3:1917 " "birth_date_1:07 birth_date_2:july birth_date_3:1979 birth_place_1:ghana birth_place_2:, birth_place_3:accra " "birth_date_1:27 birth_date_2:february birth_date_3:1979 birth_place_1:durban birth_place_2:, birth_place_3:south birth_place_4:africa " "birth_date_1:1989 birth_place_1:lima birth_place_2:, birth_place_3:peru " "birth_date_1:5 birth_date_2:september birth_date_3:1980 birth_place_1:angola death_date:&lt;none&gt; " "birth_date_1:1 birth_date_2:february birth_date_3:1856 birth_place_1:hampstead birth_place_2:, birth_place_3:london death_date_1:14 death_date_2:august death_date_3:1905 " "birth_date_1:28 birth_date_2:december birth_date_3:1954 birth_place_1:hickory birth_place_2:, birth_place_3:north birth_place_4:carolina death_date:&lt;none&gt; " "birth_date:&lt;none&gt; " "birth_date:&lt;none&gt; birth_place:&lt;none&gt; death_date:&lt;none&gt; " "birth_date:&lt;none&gt; birth_place_1:belfast birth_place_2:, birth_place_3:northern birth_place_4:ireland " "birth_date:&lt;none&gt; birth_place:&lt;none&gt; death_date:&lt;none&gt; " "birth_date_1:28 birth_date_2:february birth_date_3:1891 birth_place_1:carberry birth_place_2:, birth_place_3:manitoba death_date_1:20 death_date_2:september death_date_3:1968 " "birth_date_1:4 birth_date_2:november birth_date_3:1993 birth_place_1:portim√£o birth_place_2:, birth_place_3:portugal " Within these dataset I am trying to extract information as below; 25.08.1945 \t France \t NA 14.06.1995 \t Dvůr Králové nad Labem,Czech Republic \t 2…
possible better answer: http://stackoverflow.com/a/51603826
has answer: http://stackoverflow.com/a/51603826
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51603815
tagged with: string
has title: String extraction from iterating and mixed lines in python

http://stackoverflow.com/q/51541151
has answer: http://stackoverflow.com/a/51541341
favorite count: 0
tagged with: python-3.x
type: Question
has body: There are many methods for creating new columns in Pandas (I may have missed some in my examples so please let me know if there are others and I will include here) and I wanted to figure out when is the best time to use each method. Obviously some methods are better in certain situations compared to others but I want to evaluate it from a holistic view looking at efficiency, readability, and usefulness. I'm primarily concerned with the first three but included other ways simply to show it's possible with different approaches. Here's your sample dataframe: df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]}) Most commonly known way is to name a new column such as df['c'] and use apply: df['c'] = df['a'].apply(lambda x: x * 2) df a b c 0 1 4 2 1 2 5 4 2 3 6 6 Using assign can accomplish the same thing: df = df.assign(c = lambda x: x['a'] * 2) df a b c 0 1 4 2 1 2 5 4 2 3 6 6 Updated via @roganjosh: df['c'] = df['a'] * 2 df a b c 0 1 4 2 1 2 5 4 2 3 6 6 Using map (definitely not as efficient as apply): df['c'] = df['a'].map(lambda x: x * 2) df a b c 0 1 4 2 1 2 5 4 2 3 6 6 Creating a new pd.series and then concat to bring it into the dataframe: c = pd.Series(df['a'] * 2).rename("c") df = pd.concat([df,c], axis = 1) df a b c 0 1 4 2 1 2 5 4 2 3 6 6 Using join: df.join(c) a b c 0 1 4 2 1 2 5 4 2 3 6 6
tagged with: python
upvote count: 3
answer count: 3
has answer: http://stackoverflow.com/a/51543465
has title: Pandas column creation methods
has comment: http://stackoverflow.com/comment/90050162
has comment: http://stackoverflow.com/comment/90050369
linked to: http://stackoverflow.com/q/24870953
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90050371
has answer: http://stackoverflow.com/a/51541214
tagged with: pandas
type: AnsweredQuestion
score: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/51543465
has comment: http://stackoverflow.com/comment/90050204
possible better answer: http://stackoverflow.com/a/51541214

http://stackoverflow.com/q/51548112
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: python-module
tagged with: python
score: 2
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/51550041
has comment: http://stackoverflow.com/comment/90066381
tagged with: python-3.6
linked to: http://stackoverflow.com/q/16192916
has body: I want to use the requests module in Google App Engine Python Standard Runtime Environment. Quote from official Google Cloud docs: You can use third-party libraries that are pure Python code with no C extensions, by copying the library into your application directory. If the third-party library is already built-in, bundled with the runtime, you can use the library without copying it into your app. Third party libraries must be implemented as pure Python code with no C extensions. If copied to your application directory, they count towards file quotas because the library is uploaded to App Engine along with your application code. requests isn't bundled with GAE, so I added it into my application folder according to the instructions. requests required a few other modules that don't come with GAE, so I added all of them to my application folder: certifi chardet idna urllib3 Another problem came up. My request goes to the Stack Exchange API, which has the https:// protocol. Here's the error: SSLError: HTTPSConnectionPool(host='api.stackexchange.com', port=443): Max retries exceeded with url: /2.2/1?site=stackoverflow (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) The ssl module is built into the GAE Python runtime, so I put the following in app.yaml: libraries: - name: webapp2 version: latest - name: ssl version: latest It didn't work. I got the same error as before. I copied the SSL module folder into my application directory and did import ssl in main.py, but now it throws an exception asking for yet another module to be installed: File "/Users/williamqin/Projects/stackpromo/ssl/__init__.py", line 61, in <module> import _ssl2 # if we can't import it, let the error propagate ImportError: No module named _ssl2 I searched all over the web for the _ssl2 Python module, but I couldn't find it anywhere! How do I properly use the requests module in Google App Engine?
has title: HTTPS get using "requests" module in Google App Engine fails
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51637196
downvote count: 1
favorite count: 0
type: UnansweredQuestion
has body: I have created Flask chatbot application with Python chatterbot example, but i wanted to load a specific questions and answer to the bot to display in the application. I am new to this kindly help. Thank you
has title: loading QA data to python chatbot tool
tagged with: python
has comment: http://stackoverflow.com/comment/90240742
answer count: 0
tagged with: chatterbot
has comment: http://stackoverflow.com/comment/90259316
type: Question
tagged with: flask
score: 0
tagged with: chatbot
upvote count: 1

http://stackoverflow.com/a/51524248
score: 2
has body: I cannot stress this enough: The behavior is by design. [1] That's it. This is they way the language was implemented and why decorators work better with classes is a consequence of that. Resources you provided go into detail why decorators on classes work better, so I will no repeat myself. Regarding your questions... If "M" descriptor was defined in init(), how come it is defined by some instances? It is not, you're right. Ian was presententing the point that, in general, per-instance initialisation based on some conditions may not quarantee that the "reg.M" will not raise AttributeError. This is not the case with class decorators. If you're always initializting in the __init__ then you're fine. Until, for example, someone overrides your __init__ or does del on the attribute. With class, you only need to watch the class. Instead of treating "holder.obj" as a simple data attribute, it would start invoking the descriptor protocol on accesses to "holder.obj" and ultimately redirect them to the non-existent and meaningless "holder.foo" attribute, which is certainly not what the author of the class intended. Ok, let's assume we have an object: &gt;&gt;&gt; a = property(lambda o: o.eggs) &gt;&gt;&gt; a &lt;property object at 0x7f9db318a838&gt; This is perfectly legal, right? Ok, what if I want to store it on an instance of some class? I would do: &gt;&gt;&gt; class Foo: pass ... &gt;&gt;&gt; foo = Foo() &gt;&gt;&gt; foo.a = a &gt;&gt;&gt; foo.a &lt;property object at 0x7f9db318a838&gt; Ok, so this works, cool! The problem with instance decorators here is that this would not be possible if Python applied decorator protocol to a. Typing foo.a would make it try to evaluate eggs yielding AttributeError. Therefore, in order to have two behaviours possible, the decorator protocol is not invoked on the instance foo. I hope this clears it up a bit. :) [1] https://mail.python.org/pipermail/python-list/2012-January/618572.html [2] https://mail.python.org/pipermail/python-list/2012…
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51512878

http://stackoverflow.com/a/51622665
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51622452
has body: If what you want is to subtract the year of DT_NASCIMENTO_BENEFICIARIO from ANO_CONCESSAO_BOLSA, and df is your DataFrame: # cast to datetime df["DT_NASCIMENTO_BENEFICIARIO"] = pd.to_datetime(df["DT_NASCIMENTO_BENEFICIARIO"]) df["age"] = df["ANO_CONCESSAO_BOLSA"] - df["DT_NASCIMENTO_BENEFICIARIO"].dt.year # print the result, or do something else with it: print(df["age"])
score: 0
answers question: http://stackoverflow.com/q/51622452

http://stackoverflow.com/comment/124448232
has text: I still have those __pycache__ under the subfolders exist. not sure why? And when I run git check-ignore -v, I got an error fatal: no path specified.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51587124

http://stackoverflow.com/q/51499723
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89968754
accepted answer: http://stackoverflow.com/a/51500631
favorite count: 0
tagged with: python
tagged with: merge
has comment: http://stackoverflow.com/comment/89967801
type: AnsweredQuestion
score: 3
tagged with: join
upvote count: 3
has body: I am trying to make a large dataframe using python. I have a large amount of little dataframes with different row and column names, but there is some overlap between the row names and column names. What I was trying to do is start with one of the little dataframes and then one by one add the others. Each of the specific row-column combinations is unique and in the end there will probably be a lot of NA. I have tried doing this with merge from pandas, but this results in a much larger dataframe than I need with row and column names being duplicated instead of merged. If I could find a way that pandas realises that NaN is not a value and overwrites it when a new little dataframe is added, I think I would obtain the result I want. I am also willing to try something that is not using pandas. For example: DF1 A B Y 1 2 Z 0 1 DF2 C D X 1 2 Z 0 1 Merged: A B C D Y 1 2 NA NA Z 0 1 0 1 X NA NA 1 2 And then a new dataframe has to be added: DF3 C E Y 0 1 W 1 1 The result should be: A B C D E Y 1 2 0 NA 1 Z 0 1 0 1 NA X NA NA 1 2 NA W NA NA 1 NA 1 But what happens is: A B C_x C_y D E Y 1 2 NA 1 NA 1 Z 0 1 0 0 1 NA X NA NA 1 1 2 NA W NA NA 1 1 NA 1
has answer: http://stackoverflow.com/a/51500631
type: Question
tagged with: dataframe
has title: Merge on columns and rows
tagged with: pandas

http://stackoverflow.com/comment/89952879
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51489605
has text: NoReverseMatch at /errorcodes/error_codes/3 Reverse for 'related_parts_view' with arguments '('',)' not found. 1 pattern(s) tried: ['errorcodes\\/error_codes/relatedparts/?P<error_code>[0-9]+']

http://stackoverflow.com/q/51579423
has comment: http://stackoverflow.com/comment/90126409
tagged with: excel
type: Question
tagged with: performance
has title: Applying excel formula using openpxl to column takes ages to execute
tagged with: formula
has comment: http://stackoverflow.com/comment/90125531
score: 0
has comment: http://stackoverflow.com/comment/90132452
type: UnansweredQuestion
has body: Here is the code: import openpyxl wb = openpyxl.load_workbook('C:/Users/xxx/Desktop/abc.xlsx') Sheet = wb['Data Owner Group History'] for cellObj in list(Sheet.columns)[12]: # print(n) j1=('J'+str(cellObj.row)) j2 = ('J'+str((cellObj.row)+1)) y=('K'+(str((cellObj.row)+1))) k=('K2'+(str(cellObj.row))) n='IF(AND({0}="SC",{1}="XXX-ZZZ-DISPATCH (xxxx/xxx group)"),{2}- {3},"")'.format(j1,j2,y,k) cellObj.value = n wb.save("C:/Users/xxxx/Desktop/Time to Dispatch 07-27-2018.xlsx") print("done") In simpler words, i need to apply a formula to whole column, but it consumes only cpu usage and produces no result. Please suggest some fix or alternative.
tagged with: python
answer count: 0

http://stackoverflow.com/a/51517483
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51516790
score: 3
type: Answer
upvote count: 3
has body: The scatter documentation states Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. If you want to specify the same RGB or RGBA value for all points, use a 2-D array with a single row. Hence c = [colorMap[m - 1]] works as expected. colormap 1 [ 1. 0. 0. 1.] 4 [ 0. 1. 0.96470316 1. ] 5 [ 0. 0.06250197 1. 1. ] 6 [ 0.93345491 0. 1. 1. ] facecolors 1 [[ 1. 0. 0. 0.6]] 4 [[ 0. 1. 0.96470316 0.6 ]] 5 [[ 0. 0.06250197 1. 0.6 ]] 6 [[ 0.93345491 0. 1. 0.6 ]]
answers question: http://stackoverflow.com/q/51516790
type: AcceptedAnswer

http://stackoverflow.com/a/51600033
answers question: http://stackoverflow.com/q/51495036
type: Answer
has body: One big difference is that gunicorn forks worker processes. In your example you pass the argument --workers=2 which will spawn 2 worker processes. Since Python has the Global Interpreter Lock (GIL), a single process running Eventlet can not take advantage of the performance of multiple processor cores while the multiple worker processes spawned by gunicorn can. If your application is CPU intensive, this might make a large improvement in performance. Of course, you could just launch multiple processes like your eventlet.wsgi example yourself. The other answers here linked to some good resources for learning about the options.
score: 5
upvote count: 5
downvote count: 0

http://stackoverflow.com/comment/90027720
comment on: http://stackoverflow.com/a/51514791
type: AnswerComment
has text: Well, not sure if this is standard practice, but I just added the `api_view` decorator into the `get_info.py` file method directly, and used that in my urls. Hope this doesn't disrupt the clean code universe lol.
score: 0
type: Comment

http://stackoverflow.com/comment/90004791
type: Comment
type: QuestionComment
has text: I updated the question with dummy examples
score: 0
comment on: http://stackoverflow.com/q/51517905

http://stackoverflow.com/comment/90322569
has text: Hi @ekhumoro. Sorry for delayed response. No, your answer did not work for my configuration of QGIS 2.14.6 (aside from adding plugins, I haven't really messed w/the default settings or configuration). I'll add a screen grab to show what I'm seeing.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51567543

http://stackoverflow.com/comment/117872271
type: AnswerComment
comment on: http://stackoverflow.com/a/51571102
type: Comment
has text: Just be careful here. A filename with more than one dot '.' will cause a ValueError: Too many values to unpack exception. for example, "bob.smith.jpg" would throw an exception
score: 2

http://stackoverflow.com/comment/90054542
has text: So what is your problem?
comment on: http://stackoverflow.com/q/51543298
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51513261
tagged with: python
accepted answer: http://stackoverflow.com/a/51520376
possible better answer: http://stackoverflow.com/a/51552890
has answer: http://stackoverflow.com/a/51552890
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89996324
tagged with: information-retrieval
type: Question
tagged with: text-processing
has answer: http://stackoverflow.com/a/51520376
answer count: 2
has title: Transforming Text To Vector
downvote count: 0
tagged with: nlp
favorite count: 0
tagged with: python-3.x
has body: I have a dictionary having words and the frequency of each words. {'cxampphtdocsemployeesphp': 1, 'emptiness': 1, 'encodingundefinedconversionerror': 1, 'msbuildexe': 2, 'e5': 1, 'lnk4049': 1, 'specifierqualifierlist': 2, .... } Now I want to create a bag of words model using this dictionary( I don't want to use standard library and function. I want to apply this using the algorithm.) Find N most popular words in the dictionary and numerate them. Now we have a dictionary of the most popular words. For each title in the dictionary create a zero vector with the dimension equals to N. For each text in the corpora iterate over words which are in the dictionary and increase by 1 the corresponding coordinate. I have my text which I will use to create the vector using a function. The function would look like this, def my_bag_of_words(text, words_to_index, dict_size): """ text: a string dict_size: size of the dictionary return a vector which is a bag-of-words representation of 'text' """ Let say we have N = 4 and the list of the most popular words is ['hi', 'you', 'me', 'are'] Then we need to numerate them, for example, like this: {'hi': 0, 'you': 1, 'me': 2, 'are': 3} And we have the text, which we want to transform to the vector: 'hi how are you' For this text we create a corresponding zero vector [0, 0, 0, 0] And iterate over all words, and if the word is in the dictionary, we increase the value of the corresponding position in the vector: 'hi': [1, 0, 0, 0] 'how': [1, 0, 0, 0] # word 'how' is not in our dictionary 'are': [1, 0, 0, 1] 'you': [1, 1, 0, 1] The resulting vector will be [1, 1, 0, 1] Any help in applying this would be really helpful. I am using python for implementation. Thanks, Neel
upvote count: 2

http://stackoverflow.com/q/51568874
tagged with: python
has answer: http://stackoverflow.com/a/51568894
favorite count: 0
has answer: http://stackoverflow.com/a/51568898
has title: How to create string with line breaks in Python?
downvote count: 2
has comment: http://stackoverflow.com/comment/124720016
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/10660435
has body: I have a text : What would I do without your smart mouth? Drawing me in, and you kicking me out You've got my head spinning, no kidding, I can't pin you down What's going on in that beautiful mind I'm on your magical mystery ride And I'm so dizzy, don't know what hit me, but I'll be alright ...now I want to create a string with this text. For example in Python: string = " What would I do without your smart mouth? Drawing me in, and you kicking me out You've got my head spinning, no kidding, I can't pin you down What's going on in that beautiful mind I'm on your magical mystery ride And I'm so dizzy, don't know what hit me, but I'll be alright " But Python didn't consider this as string as it contain line breaks. How can I make this text as a string?
score: 7
accepted answer: http://stackoverflow.com/a/51568894
type: Question
upvote count: 9
possible better answer: http://stackoverflow.com/a/51568926
tagged with: string
has answer: http://stackoverflow.com/a/51568926
answer count: 3
duplicate of: http://stackoverflow.com/q/10660435

http://stackoverflow.com/q/51501260
has comment: http://stackoverflow.com/comment/89970858
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: I have a nested list that looks like this [['ID', 'Name'], ['E001', 'Marcus Tan'], ['E002', 'Mary Tay'], ['E003', 'Patrick Goh'], ['E004', 'Joey Lim'], ['E005', 'Edward Lim']] And I have to search for a part of their name, for example ('Ma') and the supposed outcome is supposed to be Enter any part of name: Ma Emp ID Name E001 Marcus Tan E002 Mary Tay This is my code so far def search_emp(): name = input('Enter any part of name: ') emp_list = [] print('{:&lt;5} {:&gt;7}'.format('Emp ID', 'Name')) print('-------- -----------------') with open('Assignment_Data1.csv') as f: if name in emplist: print('{}'.format(name)) else: print('Sorry there are no such employees.')
score: 1
has answer: http://stackoverflow.com/a/51501338
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51501358
has title: Searching for an element in a nested list and printing it out
downvote count: 1
tagged with: python

http://stackoverflow.com/comment/90140617
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51582165
has text: @Ruchit it seems that the .dll is not compatible with your OS, how have you installed pyside2?

http://stackoverflow.com/comment/90210546
score: 0
type: AnswerComment
has text: This solution only works if there is one duplicate per row. It just fits my specific example and will not work otherwise
type: Comment
comment on: http://stackoverflow.com/a/51603585

http://stackoverflow.com/q/51506944
has answer: http://stackoverflow.com/a/51507109
has body: I have a dict inside a class. Trying to print, delete, te.is_empty() # Not printing anything te.printstats() # not printing my stack. Nothing. for k,v in te.items(): if v[0] == 'Available': print(k) Can you help me?
has comment: http://stackoverflow.com/comment/89983317
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89983290
has comment: http://stackoverflow.com/comment/89983248
has title: How to print and delete key if value of list has specific item from a stack
score: 0
has answer: http://stackoverflow.com/a/51507148
type: Question
linked to: http://stackoverflow.com/q/5384914
answer count: 2

http://stackoverflow.com/a/51565656
answers question: http://stackoverflow.com/q/51565619
has comment: http://stackoverflow.com/comment/90098233
has body: IIUC mask df['3rdcol']=df.type.mask(~(df.type=='-'),'Liability1') df Out[303]: Amount type 3rdcol 0 10 - - 1 -10 L1iability Liability1 2 20 - - 3 -20 Liability1 Liability1 4 5 - -
score: 0
has comment: http://stackoverflow.com/comment/90098246
type: Answer

http://stackoverflow.com/q/51515232
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has title: Combining ARIMA and BP for project
score: 2
tagged with: backpropagation
type: Question
upvote count: 2
tagged with: neural-network
tagged with: deep-learning
favorite count: 0
has body: This is my first post. I have to implement a model combining both ARIMA and BP to predict CPU Utilization based on previous data and reduce error. After implementing this ARIMA model I'm getting MSE of 1.6. I want to reduce it to below 0.8. Also I'm not sure on how to combine these 2 models. Any help would be greatly appreciated. It's really important to me. My data is in timestamp. I'm not sure how to bring that to the BP model. I can't attach my data as there's no option to attach a CSV file. Again ,please help. ARIMA model- import warnings from pandas import read_csv from pandas import datetime from statsmodels.tsa.arima_model import ARIMA from sklearn.metrics import mean_squared_error # evaluate an ARIMA model for a given order (p,d,q) def evaluate_arima_model(X, arima_order): # prepare training dataset train_size = int(len(X) * 0.66) train, test = X[0:train_size], X[train_size:] history = [x for x in train] # make predictions predictions = list() for t in range(len(test)): model = ARIMA(history, order=arima_order) model_fit = model.fit(disp=0) yhat = model_fit.forecast()[0] predictions.append(yhat) history.append(test[t]) # calculate out of sample error error = mean_squared_error(test, predictions) return error # evaluate combinations of p, d and q values for an ARIMA model def evaluate_models(dataset, p_values, d_values, q_values): dataset = dataset.astype('float32') best_score, best_cfg = float("inf"), None for p in p_values: for d in d_values: for q in q_values: order = (p,d,q) try: mse = evaluate_arima_model(dataset, order) if mse &lt; best_score: best_score, best_cfg = mse, order print('ARIMA%s MSE=%.3f' % (order,mse)) except: continue print('Best ARIMA%s MSE=%.3f' % (best_cfg, best_score)) # load dataset def parser(x): return datetime.strptime(x, '%d-%m-%Y %H:%M') series = read_csv('/home/techmadmin/Desktop/Data.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser) # evaluate parameters p_values = range(0,10) d_values = range(0,3…
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/90111262
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51572555
has text: Rember it, SO is fast, especially for "easy" questions. Best to stick around the site for ~15 to 30min after asking a question, else the wannabe answerers do not get theire questions in comment answered, get cranky and downvote due to "non-responsiveness" ;) we are working on our social skills here, but downvotes/closevotes do not mean you did bad, sometimes its just thats this question comes up about 3-10 times a week ;o) and got good canonical answeres - hence the "dupe" link to read up upon.

http://stackoverflow.com/a/51507745
has body: The ways suggested above are the correct ways of deleting a model, i.e. versions first (non-default, then default) and then the model itself. We are aware that this might be cumbersome and are working towards making this interface easier for our users. One way could be to have something that basically recursively deletes the versions and models. Are there other ways this can be done that will be more suitable?
downvote count: 0
answers question: http://stackoverflow.com/q/51488117
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/90439939
comment on: http://stackoverflow.com/a/51712765
has text: Not actually. The only thing I have done is to set a new constraint and set the objective variable less than my upper bound. But I am not sure this is the best way.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90043367
comment on: http://stackoverflow.com/q/51537905
has text: This is already efficient, and `s` is a list of nested tuples as opposed to a dictionary
type: Comment
type: QuestionComment
score: 6

http://stackoverflow.com/comment/89983928
type: Comment
type: QuestionComment
has text: You're very engaged with me! I read the guidelines and didn't see anything inappropriate for my post: First, I wrote a title that summarizes the specific problem; second, I introduced the problem before posting codes; third, helping others reproduce the problem by asking how to generalize it to other delimiters; fourth, include all relevant tags: python, regex; fifth, proof-read before posting; last, post the question and respond to feedback. Feel free to report me to admin, I don't see I did anything violate the guidelines.
score: 0
comment on: http://stackoverflow.com/q/51506656

http://stackoverflow.com/comment/135733506
comment on: http://stackoverflow.com/a/52552220
type: Comment
has text: If entries in the column are NaN, you may still run into problems and require this answer's 2nd solution. I had an unexpected scenario where some of my `df['column']` were single columns and others were DataFrames.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51503539
has comment: http://stackoverflow.com/comment/89976192
favorite count: 0
accepted answer: http://stackoverflow.com/a/51504181
tagged with: string-formatting
has title: Combine fixed and locale notation for string formatting
tagged with: python
tagged with: fixed-point
type: AnsweredQuestion
tagged with: numbers
score: 1
tagged with: matplotlib
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51504181
has body: I am trying to define a format string using Python's string format mini-language in order to get a string with a number in fixed notation, but with a local decimal separator. See the following snippet for further clarification of the desired output: import locale import os if os.name == 'nt': locale.setlocale(locale.LC_ALL, 'de-de') else: locale.setlocale(locale.LC_ALL, 'de_de') number = 1.234567 print('fixed notation: {:.7f}'.format(number)) print('general notation: {:.7g}'.format(number)) print('local format: {:.7n}'.format(number)) desired_output = '{:.7f}'.format(number) print('desired output: {}'.format(desired_output.replace('.', ','))) Replacing . with , is a suitable workaround when using 'regular' strings. However, this seems not to be doable in my case since I need to specify a matplotlib.ticker.StrMethodFormatter to get the desired output as tick labels. Using the locale notation works as expected: ax.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x:1.3n}')) Unfortunately, I was not able to find a format string for a combined format of fixed (e.g. {:.3f}) and locale notation ({:.3n}) to enable trailing zeros filled for same decimal length. As you can see in my sample diagram, they should have both equal amount of decimal places (which can be ensured by fixed point notation '{:.7f}') and local decimal separator (which can be ensured by '{:.7n}'):
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51603722
tagged with: python
tagged with: excel
has body: I have been having the below error trying to reload Pyxll since updating my Anaconda version to 5.0.1 Python 2.7 64. ERROR : Not reloading dependency ipywidgets.widgets because of previous failure to reload ipywidgets.widgets.interaction 2018-07-30 13:57:52,440 - ERROR : Error reloading 'ipywidgets.widgets.interaction'
type: AnsweredQuestion
tagged with: pyxll
has title: Pyxll 'ipywidgets.widgets' reloading error
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/51603733
accepted answer: http://stackoverflow.com/a/51603733
score: 0

http://stackoverflow.com/a/51620445
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51619195
answers question: http://stackoverflow.com/q/51619195
score: 1
upvote count: 1
has body: You need to set "python.pythonPath" to point to your Python executable.
type: AcceptedAnswer

tensorflow-datasets
tags question: http://stackoverflow.com/q/51622736
tags question: http://stackoverflow.com/q/51616492
tag name: tensorflow-datasets
tags question: http://stackoverflow.com/q/51630204
type: Tag
tags question: http://stackoverflow.com/q/51615027
tags question: http://stackoverflow.com/q/51601502
tags question: http://stackoverflow.com/q/51537851
tags question: http://stackoverflow.com/q/51536373
tags question: http://stackoverflow.com/q/51625529
tags question: http://stackoverflow.com/q/51623671
tags question: http://stackoverflow.com/q/51586693

http://stackoverflow.com/a/51568308
answers question: http://stackoverflow.com/q/51568251
downvote count: 0
upvote count: 2
type: Answer
has body: The issue is you are attempting to index into an integer i as if it was a list. I think you meant b[i][0] (this says: give me the 0-th item of the i-th item in b). This is a little easier: b = [['a', '1'], ['b', '2'], ['c', '3']] d = dict(b) print(d) Output: {'a': '1', 'b': '2', 'c': '3'}
score: 2

http://stackoverflow.com/a/51597094
has body: You should ask specifics at https://groups.io/g/insync I doubt anybody here uses that library. Commissions aren't returned in executions, they are returned in commissionReport. http://interactivebrokers.github.io/tws-api/classIBApi_1_1CommissionReport.html Notice that the id is the execution id which is the same in the execution that matches the commission report.
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51594556
upvote count: 2
type: Answer

http://stackoverflow.com/comment/90061270
score: 0
comment on: http://stackoverflow.com/q/51546592
type: Comment
type: QuestionComment
has text: Could you provide us with the codes you have in __init__.py? I think I might be able to help you with this issue.

http://stackoverflow.com/a/51485048
has body: The following code does not explicitly use slicing, but it is very efficient: letters = next(zip(*t)) letters #('a', 'a', 'a', 'a', 'b') This method is 25% faster than the list comprehension with selection ([0]) and 48% faster than the list comprehension with slicing ([:1]).
answers question: http://stackoverflow.com/q/51484967
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/90202269
has text: Can you show us an *example* of your input data [sensitive data excluded, we just need to know the format]?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51618228

http://stackoverflow.com/q/51515164
upvote count: 1
answer count: 1
favorite count: 0
has title: Python Generate truthtable from expression containing Numeric value and comparators
has body: I am trying to generate test cases from a boolean expression which may contain numerical values and comparators, e.g.: (10 &lt; a) and (c == 5) truth tables seems like a good approach and generation output might look like this: &gt; a, c, result &gt; 11, 5, True, &gt; 11, 4, False, &gt; 9, 5, False, &gt; 9, 4, False It is pretty straight forward to generate a truth table when expression only contains boolean operators using ast.nodevisitor. I ended up with something like this which works nicely. class Expr(): def __init__(self, expr): self.tree = ast.parse(expr) self.expr=expr self.vars = self.allVariables().visit(self.tree) self.generateTruthTable() def generateTruthTable(self): NO_GLOBALS = {'__builtins__': {}} self.truthtable=dict() for i, vals in enumerate(product([True,False],repeat=len(self.vars))): self.truthtable[i] = dict() self.truthtable[i]['inputs'] = dict(zip(self.vars, vals)) self.truthtable[i]['expectation'] = eval(self.expr, NO_GLOBALS, self.truthtable[i]['inputs']) class allVariables(ast.NodeVisitor): def visit_Module(self, node): self.names = set() self.generic_visit(node) return sorted(self.names) def visit_Name(self, node): self.names.add(node.id) now I am deeply struggling in how to perform this same generation whatever the operators are. it looks like recursion is key here. is there a way to perform such generation using python AST ? thank you.
tagged with: python
tagged with: truthtable
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90016713
has comment: http://stackoverflow.com/comment/90002754
has answer: http://stackoverflow.com/a/51535633
accepted answer: http://stackoverflow.com/a/51535633
type: Question
has comment: http://stackoverflow.com/comment/89998665
has comment: http://stackoverflow.com/comment/89999484
tagged with: abstract-syntax-tree

http://stackoverflow.com/a/52458101
score: 0
answers question: http://stackoverflow.com/q/51544649
type: Answer
has body: When you installed python 3.6 you most likely you did not check the box to add it to your user PATH environment variable. Reinstalling and checking the box should fix it. Otherwise, you could update your user Path Environment Variable adding something like "C:\Users\OdatNurd\AppData\Local\Programs\Python\Python36\"

http://stackoverflow.com/comment/90055181
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51543359
has text: It's close to impossible to know what goes wrong here without a [mcve] of the issue.

http://stackoverflow.com/comment/90139498
comment on: http://stackoverflow.com/q/51587098
type: Comment
type: QuestionComment
has text: Try changing `gender = gender_classifier()` to `gender = self.gender_classifier()`
score: 2

http://stackoverflow.com/a/63119145
has body: You should create a seperate function for buttons: def button(x, y, w, h, inactive, active, action=None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x + w > mouse[0] > x and y + h > mouse[1] > y: gameDisplay.blit(active, (x, y)) #Images are a bit easier to use if click[0] == 1 and action is not None: print("start") else: gameDisplay.blit(inactive, (x, y)) After you have done that, you can call it like this: #For Example button(100, 350, 195, 80, startBtn, startBtn_hover, game_loop) Here is what each parameter means: x: x-coordinate of button y: y-coordinate of button w: width of button h: height of button active: picture of button when the mouse is hovering over it inactive: picture of button when it is idle
score: 0
answers question: http://stackoverflow.com/q/51624383
type: Answer

http://stackoverflow.com/comment/90224225
comment on: http://stackoverflow.com/a/51629651
score: 0
type: AnswerComment
has text: @jezrael With the `astype(int)` solution, I get the error: `ValueError: invalid literal for int() with base 10: '14.5928565'`.
type: Comment

http://stackoverflow.com/a/51500728
score: 3
has comment: http://stackoverflow.com/comment/89997978
has comment: http://stackoverflow.com/comment/89997920
has comment: http://stackoverflow.com/comment/90002378
has comment: http://stackoverflow.com/comment/89986895
downvote count: 0
answers question: http://stackoverflow.com/q/51500003
has comment: http://stackoverflow.com/comment/89997994
type: Answer
has comment: http://stackoverflow.com/comment/89982938
upvote count: 3
has body: def l(d): return '\n'.join(k + (i and ' ' + i) for k, v in d.items() for i in l(v).split('\n')) print(l({'a': {'b': {'c': {}, 'd': {}}, 'g': {}}})) This outputs: a b c a b d a g

http://stackoverflow.com/comment/90142557
type: QuestionComment
score: 1
has text: Also, thinking in a puritan way, I have no idea why you pointed out to another question that explicitly compares `simple` vs `oneshot` systemd options. For the "other options [...] to explore", I think you should have pointed me to: https://www.freedesktop.org/software/systemd/man/systemd.service.html (which by the way, I read but still not yet found a solution to make it run from Ansible)
comment on: http://stackoverflow.com/q/51583624
type: Comment

http://stackoverflow.com/comment/115598452
score: 2
comment on: http://stackoverflow.com/a/51622519
has text: Now we have it: https://pypi.org/project/django-tarantool/
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90096039
type: QuestionComment
has text: So, what is your problem?
score: 0
comment on: http://stackoverflow.com/q/51563673
type: Comment

http://stackoverflow.com/a/51528977
downvote count: 0
score: 2
type: AcceptedAnswer
upvote count: 2
type: Answer
has body: If queue_id groups do not contain foo_id duplicates, you could use a LEFT JOIN: qc2 = aliased(QueueContent) session.query(QueueContent.queue_id, func.count(), func.count(qc2.foo_id)).\ outerjoin(qc2, and_(qc2.queue_id == 3, qc2.foo_id == QueueContent.foo_id)).\ filter(QueueContent.queue_id != 3).\ group_by(QueueContent.queue_id) If they do, you could use an EXISTS subquery expression wrapped in NULLIF (or cast as integer and summed): qc2 = aliased(QueueContent) sq = session.query(qc2).\ filter_by(queue_id=3, foo_id=QueueContent.foo_id).\ exists() session.query(QueueContent.queue_id, func.count(), func.count(func.nullif(sq, False))).\ filter(QueueContent.queue_id != 3).\ group_by(QueueContent.queue_id) Both variants use the fact that COUNT(expression) produces the number of rows where value of expression is not NULL.
accepted answer of: http://stackoverflow.com/q/51527075
answers question: http://stackoverflow.com/q/51527075

http://stackoverflow.com/a/51493568
has body: If you want users, you should request users. User.objects.filter(Q(myself__someone=request.user) | Q(someone__user=request.user)) This gives you all users who are either the "someone" in a message from the current user, or the "user" in a message to the current user. Since you are querying users directly, the is no possibility of duplicates.
score: 3
answers question: http://stackoverflow.com/q/51493219
has comment: http://stackoverflow.com/comment/89960468
has comment: http://stackoverflow.com/comment/89959962
accepted answer of: http://stackoverflow.com/q/51493219
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89960440
type: Answer
upvote count: 3

http://stackoverflow.com/comment/89934490
comment on: http://stackoverflow.com/q/51482640
score: 1
type: Comment
has text: Please read https://stackoverflow.com/help/mcve and adjust your question appropriately.
type: QuestionComment

http://stackoverflow.com/a/51577658
has comment: http://stackoverflow.com/comment/90120915
has comment: http://stackoverflow.com/comment/90139802
type: Answer
has comment: http://stackoverflow.com/comment/90139409
has comment: http://stackoverflow.com/comment/90137268
has body: There is difference, because in second sample use list of Series, so if need row in first is necessary one lement list [s]: s = pd.Series({'a':1,'b':2}, name='joe') #list of Series df = pd.DataFrame([s]) print (df) a b joe 1 2 s1 = pd.Series({'a':1,'b':2}, name='joe') s2 = pd.Series({'a':4,'b':5}, name='john') #list of Series df = pd.DataFrame([s1,s2]) print (df) a b joe 1 2 john 4 5 In my opinion one Seriess is parsed to column, because in DataFrame each column is Series with some dtype. DataFrame: DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.
has comment: http://stackoverflow.com/comment/90120718
answers question: http://stackoverflow.com/q/51577648
score: 0

http://stackoverflow.com/comment/90053053
comment on: http://stackoverflow.com/a/51497791
type: AnswerComment
has text: if I do not plot the number < 0.1, how to adjust the code?
score: 0
type: Comment

http://stackoverflow.com/comment/90097406
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51565244
has text: Why not write to the file directly instead of building `res`?

http://stackoverflow.com/comment/90041521
score: 1
comment on: http://stackoverflow.com/q/51534109
type: Comment
has text: The primary point of forms is for validation. What happens if your users don't include a bio or location? What happens if they upload something that isn't an image? What happens if they enter a string that is too long for the location? The Django form will catch and deal with all those issues.
type: QuestionComment

http://stackoverflow.com/comment/90474227
has text: @12williamsa should be simple enough. Using a entry filed for the user to type a name then use the `get()` method on the entry filed and assign the string to a variable. It would be best if you post a quest with what you have tried so far and explain where you are stuck so someone can assist.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51487667

http://stackoverflow.com/a/51505250
has comment: http://stackoverflow.com/comment/89982717
has comment: http://stackoverflow.com/comment/89980364
has body: You can do it like this ^(\d{1,})\s?(A(?=BC)|D(?=EF)|G(?=HI)).. This truncates the remaining 2 characters. so, re.sub(regex_pattern, r'\1 \2', str) will convert 123 ABC to 123 A update info If you use the new Python regex module, you'd have access to branch reset construct. Then it's as simple as putting a capture group (2) around the first letters (or any particular letter, in any particular item see note 1) of all in the alternation ist. This avoids the callback, thus increasing performance, and it enables you to add intense constructs within the branch reset list. ^(\d{1,})\s?(?|(A)BC|(D)EF|(G)HI) https://regex101.com/r/S9XBpb/1 Readable version ^ ( \d{1,} ) # (1) \s? (?| # Branch reset ( A ) # (2) BC | ( D ) # (2) EF | ( G ) # (2) HI ) note 1: https://regex101.com/r/S9XBpb/2 https://regex101.com/r/S9XBpb/3 &lt;- Couldn't do this with a callback
has comment: http://stackoverflow.com/comment/89981889
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89982698
has comment: http://stackoverflow.com/comment/89979845
has comment: http://stackoverflow.com/comment/89979904
downvote count: 0
answers question: http://stackoverflow.com/q/51505166

http://stackoverflow.com/q/51561710
duplicate of: http://stackoverflow.com/q/51562730
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90090373
has comment: http://stackoverflow.com/comment/90091631
has title: How to initialize an object with a field a numpy array, and the array is passed as an argument?
has body: How to initialize an object with a field a numpy array, and the array is passed as an argument? For example class Foo def __init__() self.x = None self.m = None self.v = None this has static methods @staticmethod def pop_x(x): # populate x with zeros x = zeros(n) wouldn't work if I say self.pop(self.x) because set x= something it's just losing the referenced to x def pop_x(): # populate x with zeros self.x = zeros(n) because I have a bunch of fields Object.x, Object.y, ... so I don't want to make a pop method for each of them. @staticmethod def update_q(q, i, val): """ update i-th quantity """ if q.ndim == 1: q[i] = val elif q.ndim == 2: q[i, :] = val @staticmethod def pop_q(q, n, m): """ populate quantity with zeros """ if q.ndim == 1: q = zeros(n) elif q.ndim == 2: q = zeros((n, m)) @staticmethod def get_q(q, i): if q.ndim == 1: return q[i] elif q.ndim == 2: return q[i, :] Here pop_q wouldn't work because setting q equals a numpy array lose the reference to q.
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90090741
score: 1
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51563099
tagged with: python
has comment: http://stackoverflow.com/comment/90091169
linked to: http://stackoverflow.com/q/51562730
has comment: http://stackoverflow.com/comment/90090586
tagged with: oop

http://stackoverflow.com/q/51632260
upvote count: 0
type: UnansweredQuestion
tagged with: pymongo
has body: I am new to python and flask, trying to import a function from route_user.py file which is present in folder named Users_service into a route_jd.py file which is present in folder named JD_service and both the folder Users_service and JD_service is present inside a folder named blue. route_users.py file from flask import jsonify,request,Blueprint,make_response from flask_pymongo import PyMongo from blue import app from werkzeug.security import generate_password_hash,check_password_hash import uuid import jwt import datetime from functools import wraps app.config['SECRET_KEY'] = 'itshouldbehidden' app.config['MONGO_URI'] = "mongodb://localhost:27017/mydata" mongo = PyMongo(app) mod = Blueprint('Users_Service',__name__) def token_required(f): @wraps(f) def decorated(*args,**kwargs): token = None if 'x-access-token' in request.headers: token = request.headers['x-access-token'] if not token: return jsonify({'message':'token is missing!'}),401 try: data = jwt.decode(token, app.config['SECRET_KEY']) print(data) jd = mongo.db.hashed_User current_user = jd.find_one({'public_id':data['public_id']}) print(current_user) except: return jsonify({'message':'Token is invalid'}),401 return f(current_user,*args,**kwargs) return decorated @mod.route('/add',methods=['POST']) @token_required def create_user(current_user): if not current_user['admin']: return jsonify({'message':'cannot perform that function'}) jd = mongo.db.hashed_User data = request.get_json() try: hashed_password = generate_password_hash(data['password'],method='sha256') jd.insert({"public_id":str(uuid.uuid4()),"name":data['name'],"password":hashed_password,"admin":False}) output = 'new user created!' except: output = 'please fill all the fields and try again' return jsonify({'message':output}) @mod.route('/all',methods=['GET']) @token_required def get_all_users(current_user): if not current_user['admin']: return jsonify({'message':'cannot perform that function'}) jd = mongo.db.hashed_User output = [] for q in jd.find…
score: -1
type: Question
has answer: http://stackoverflow.com/a/51632568
answer count: 2
downvote count: 1
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/51632548
has title: i am not being able to import function from another folder, it is giving an import error (ImportError: cannot import name 'token_required')
tagged with: python

http://stackoverflow.com/q/51580046
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51580167
tagged with: tkinter
has body: So i was working on a code to show my logo i want to make out of lines and polygons in a canvas, and after i tried to run it: surprise, the canvas doesn't show up. What did i do wrong? from tkinter import * class Logo(Frame): def _init__(self): Frame.__init__(self) logo = Canvas(root, width=100, height=100) logo.pack(in_=self) class App(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.pack() self.showLogo() def showLogo(self): self.logo = Logo().pack(side=TOP, pady=100) root = Tk() root.title("K-80.1") root.configure(background="#7E607E") root.geometry("760x500") app = App(master = root) app.mainloop()
has title: Why doesn't this show my canvas when i run it?
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90125538
score: -1
accepted answer: http://stackoverflow.com/a/51580167
tagged with: canvas
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90125520

http://stackoverflow.com/q/51619976
has comment: http://stackoverflow.com/comment/90205895
accepted answer: http://stackoverflow.com/a/51620413
has title: Extending the Django user model with a __getattr__ method
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has body: In a Django project, I have a module which extends Django's user model, similar to the following: from django.contrib.auth.models import User def __str__(self): return "%s %s" % (self.first_name, self.last_name) User.add_to_class('__str__', __str__) I've noticed that this works. However, if I try to define a __getattr__ method, like so: def __getattr__(self, attr): if self.user_profile: return getattr(self.user_profile, attr) else: raise AttributeError(f"'{self.__class__.__name__}' has no attribute '{attr}'") I get the following error upon importing the module: (lucy-web-CVxkrCFK) bash-3.2$ python manage.py shell Traceback (most recent call last): File "manage.py", line 28, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 1006, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 983, in _find_and_load File "&lt;frozen importlib._bootstrap&gt…
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: django
has answer: http://stackoverflow.com/a/51620413
type: Question

http://stackoverflow.com/comment/89992938
has text: Row 2, column A also has four letters; what decides that it is the four letter string in column C that decides what is merged?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51510818
type: Comment

http://stackoverflow.com/comment/90108358
type: AnswerComment
has text: FlyingTeller - detail mate :D code's copied... tabs added with spaces, anyone will tell you that technically python is tabs sensitive so you can argue for spaces if you want, but thats the official definition :)
type: Comment
comment on: http://stackoverflow.com/a/51571128
score: 0

http://stackoverflow.com/comment/89972327
type: Comment
score: 0
type: QuestionComment
has text: You never opened the file. https://docs.python.org/3/library/functions.html#open
comment on: http://stackoverflow.com/q/51501974

http://stackoverflow.com/q/51605226
has answer: http://stackoverflow.com/a/51605577
tagged with: python
linked to: http://stackoverflow.com/q/32011359
answer count: 4
type: AnsweredQuestion
has title: How to convert a pandas dataframe from a string based categorical column to a numeric representation
has answer: http://stackoverflow.com/a/51605239
possible better answer: http://stackoverflow.com/a/51605259
score: 1
has answer: http://stackoverflow.com/a/51605259
upvote count: 1
accepted answer: http://stackoverflow.com/a/51605285
type: Question
has comment: http://stackoverflow.com/comment/109814375
tagged with: pandas
downvote count: 0
has body: I have a column in a dataframe which looks like this: df['label'] ['some_label', 'some_label', 'a_diff_label', 'a_diff_label',...] I want to convert it to something like this: [1,1,0,0,...]
favorite count: 0
has answer: http://stackoverflow.com/a/51605285

http://stackoverflow.com/comment/90213336
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51623477
has text: The size of the generators doesn't account for costs like the suspended stack frame or the iterator over `ys`.

http://stackoverflow.com/comment/90085328
type: AnswerComment
has text: Thanks a lot for the help.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51550148

http://stackoverflow.com/a/51630292
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: The problem is that setting the zorder with the keyword arguments sets the zorder of the image inside the OffsetBox, which will have no effect. In order to set the zorder of the box itself, you need to set this externally: addLogo = OffsetImage(logo, zoom=0.6) addLogo.set_zorder(10)
answers question: http://stackoverflow.com/q/51628902

http://stackoverflow.com/a/51589462
answers question: http://stackoverflow.com/q/51588717
accepted answer of: http://stackoverflow.com/q/51588717
type: AcceptedAnswer
score: 0
type: Answer
has body: It turns out I need to save checkpoint with relative path. But it is not enough, the relative metadata path in Projector config file is still not recognizable, so I have to use an adhoc relative path. In general, you need to go look into each path and fix it, depending on your checkpoint dir structure.

http://stackoverflow.com/q/51537645
tagged with: python
has title: External functions in main file PyQt4
has body: I tried really hard to make this code to work. I tried with Qtimer, proccesEvents and I didn't have the results I wanted. The GUI starts, so something works, but there are no changes, so the method reading() doesn't work. I searched a lot on stackoverflow to find some help, but I couldn't find. Perhaps I am not capable. This is the code: import RPi.GPIO as GPIO import MFRC522 import signal import time from PyQt4 import QtCore, QtGui from ui_mainwindow import Ui_MainWindow class MainWindow(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) def reading(self): self.ui.processEvents() ### Event Functions ### continue_reading = True # Hook the SIGINT signal.signal(signal.SIGINT, end_read) # Create an object of the class MFRC522 MIFAREReader = MFRC522.MFRC522() # This loop keeps checking for chips. If one is near it will get the UID and authenticate while continue_reading: # Scan for cards (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL) # Get the UID of the card (status,uid) = MIFAREReader.MFRC522_Anticoll() # If we have the UID, continue if status == MIFAREReader.MI_OK: # This is the default key for authentication key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF] # Select the scanned tag MIFAREReader.MFRC522_SelectTag(uid) # Authenticate status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid) # Check if authenticated if status == MIFAREReader.MI_OK: MIFAREReader.MFRC522_Read(8) self.ui.label_3.show() self.ui.label_2.show() self.ui.label_4.show() self.ui.groupBox.setStyleSheet(_fromUtf8("background: white;\n" "border-style: solid;\n" "border-width: 1px;\n" "border-radius: 20px;")) time.sleep(5) MIFAREReader.MFRC522_StopCrypto1() self.ui.label_3.hide() self.ui.label_2.hide() self.ui.label_4.hide() self.ui.groupBox.setStyleSheet(_fromUtf8("background: white url(scan.png) no-repeat center;\n" "border-style: solid;\n" "border-width: 1px;\n" "border-radius: 20p…
type: AnsweredQuestion
type: Question
tagged with: pyqt4
possible better answer: http://stackoverflow.com/a/51537715
has answer: http://stackoverflow.com/a/51537715
accepted answer: http://stackoverflow.com/a/51538598
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51538598

http://stackoverflow.com/q/51558747
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90109863
tagged with: authentication
type: Question
has answer: http://stackoverflow.com/a/51558815
has comment: http://stackoverflow.com/comment/90085665
has body: I've been coding for a project and is to make a login/ sign in with python and by using csv file. The problem is that when it makes a user and password in the csv file it overwrites the previous one meaning their can only be one user and password. My code right now looks like this... import time def sign_menu(): time.sleep(2) print() print(' Create a username and') print( ' password') NewUser = input(' Username: ') NewpWord = input(' Password: ') with open('UserPassword.csv', 'w') as outfile: outfile.write("username," + NewUser) outfile.write("password," + NewpWord) Also my csv file looks like this... username,password, if you could improve the code it would be appreciated and if you could explain on how to make it not overwrite that would also be helpful. Thank you.
has title: CSV overwrites username and password in Python
score: 0
has comment: http://stackoverflow.com/comment/90109981
answer count: 1
accepted answer: http://stackoverflow.com/a/51558815
has comment: http://stackoverflow.com/comment/90084301
tagged with: overwrite

http://stackoverflow.com/comment/90224457
comment on: http://stackoverflow.com/a/51629636
type: Comment
has text: (venv)root@graphene-62:~/tensorflow# sudo python -c "import tensorflow as tf; print(tf.__version__)" 1.5.0 Thank you so much.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90039283
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51535232
has text: Still failing[root@ip-172-31-77-17 ~]# curl http://35.173.47.24:8090/put -d {"id":102} -X PUT -H "Content-Type:application/json" { "message": "The browser (or proxy) sent a request that this server could not understand." } [root@ip-172-31-77-17 ~]#

printing
tags question: http://stackoverflow.com/q/51568024
tag name: printing
tags question: http://stackoverflow.com/q/51637417
tags question: http://stackoverflow.com/q/51563629
tags question: http://stackoverflow.com/q/51488861
type: Tag

http://stackoverflow.com/comment/89990781
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51511142
has text: Possible duplicate of [Debugging "Element is not clickable at point" error](https://stackoverflow.com/questions/11908249/debugging-element-is-not-clickable-at-point-error)
score: 0

http://stackoverflow.com/a/51583300
score: 0
has comment: http://stackoverflow.com/comment/90131987
has comment: http://stackoverflow.com/comment/90131978
type: Answer
answers question: http://stackoverflow.com/q/51578978
has comment: http://stackoverflow.com/comment/90131977
has body: From a simple research i found that you need to redirect the the page using javascript afrer you have received your response. In your case $scope.logout = function() { var url = '/logout'; var toSend = { username: username_id, } $http({ method: 'POST', url: url, data: toSend, }).then(function(response) { // perform redirect window.location('/login'); }) };

http://stackoverflow.com/q/51582726
has comment: http://stackoverflow.com/comment/90130838
has comment: http://stackoverflow.com/comment/90130854
has title: Overfitting terminology in Machine Learning
tagged with: python
has answer: http://stackoverflow.com/a/51589953
type: AnsweredQuestion
upvote count: 0
tagged with: machine-learning
type: Question
score: -1
has answer: http://stackoverflow.com/a/51582939
accepted answer: http://stackoverflow.com/a/51582939
has body: In the book Introduction to Machine Learning with Python on page 50 the author is performing a Linear Regression on a dataset and gets: training set score: 0.67 test set score: 0.66 They then state that they are “likely underfitting, not overfitting.” However, when using TensorFlow’s Basic Classification Tutorial they are using the MNIST Fashion dataset with a neural network and get: training set score: 0.892 test set score: 0.876 and then they state the following “It turns out, the accuracy on the test dataset is a little less than the accuracy on the training dataset. This gap between training accuracy and test accuracy is an example of overfitting. Overfitting is when a machine learning model performs worse on new data than on their training data.” I believe that the quote taken from the TensorFlow site is the correct one, or are they both correct and I don’t fully understand overfitting.
answer count: 3
downvote count: 1
possible better answer: http://stackoverflow.com/a/51582794
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/51582794
favorite count: 0
has comment: http://stackoverflow.com/comment/90130967

http://stackoverflow.com/a/51637783
upvote count: 3
has comment: http://stackoverflow.com/comment/90240900
has comment: http://stackoverflow.com/comment/90287836
type: Answer
accepted answer of: http://stackoverflow.com/q/51637310
has comment: http://stackoverflow.com/comment/90242731
downvote count: 0
answers question: http://stackoverflow.com/q/51637310
has comment: http://stackoverflow.com/comment/90287771
score: 3
has comment: http://stackoverflow.com/comment/90287725
has comment: http://stackoverflow.com/comment/90287682
has comment: http://stackoverflow.com/comment/90287370
has body: You're getting generators which as you said are just memory locations. To access them, you need to call a function on them, in this case, you want the text so .text Additionally, I would highly recommend changing your XPath since it's a literal location and subject to change. prices = content.xpath("//div[@id='site']//div[@class='price']//span[@class='push-data ']") prices_holder = [i.text for i in prices] prices_holder ['25,389.06', '25,374.60', '7,251.60', '2,813.60', '22,674.50', '12,738.80', '3,500.58', '1.1669', '111.7250', '1.3119', '1,219.58', '15.43', '6,162.55', '67.55'] Also of note, you will only get the values at load. If you want the prices as they change, you'd likely need to use Selenium.
has comment: http://stackoverflow.com/comment/90241035
has comment: http://stackoverflow.com/comment/90292115
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90247878
has comment: http://stackoverflow.com/comment/90243051

http://stackoverflow.com/comment/90099993
type: QuestionComment
has text: Had you closed the terminal inbetween? Could just be that, it reads path when it initialises.
comment on: http://stackoverflow.com/q/51523826
score: 0
type: Comment

local
tags question: http://stackoverflow.com/q/51488941
type: Tag
tag name: local
tags question: http://stackoverflow.com/q/51585600

http://stackoverflow.com/q/51524994
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51525593
score: 0
answer count: 2
has body: While scripting Abaqus-Python, i frequently store objects in variables like myAssembly in order to shorten the code and to reliably address these objects later on. For example: myAssembly = mdb.models['Model-1'].rootAssembly However, the return value of myAssembly.ReferencePoint(point=(0.5, 0.5, 0.0)) is a FeatureObject and no "ReferencePoint" (see Abaqus 2016 Scripting Manual 20.1.58). Therefore the code: myReferencePoint = myAssembly.ReferencePoint(point=(0.5, 0.5, 0.0)) mySetMaster = myAssembly.Set( name='m_Set-1', referencePoints=(myReferencePoint, )) results in "TypeError: referencePoints[0]; found Feature, expecting tuple". The recorded journal uses (shortend by usage of myAssembly) myAssembly.ReferencePoint(point=(0.5, 0.5, 0.0)) myAssembly.Set(name='m_Set-1', referencePoints=( myAssembly.referencePoints[4], )) The question is: How can one address a ReferencePoint through usage of variables (e.g. myReferencePoint) instead of possibly changing numbers (e.g. 4)?
has answer: http://stackoverflow.com/a/51550769
tagged with: python
tagged with: abaqus
has title: How to address/reuse ReferencePoints in Abaqus-Python like other Abaqus-Python-Objects?

http://stackoverflow.com/comment/89939774
score: 0
type: QuestionComment
type: Comment
has text: There is a *huge* difference in comparing `Utilities` and `Utilities` (i.e. same words) and saying they're similar, and `Banking` and `Finance`. The former can be done with a couple of lines of code; the latter can get veeeeery complex
comment on: http://stackoverflow.com/q/51485167

http://stackoverflow.com/q/51598859
has answer: http://stackoverflow.com/a/51599177
upvote count: 1
has body: If I have an array [1, 2, 3, 4, 5] and a Pandas Dataframe df = pd.DataFrame([[1,1,1,1,1], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]]) 0 1 2 3 4 0 1 1 1 1 1 1 0 0 0 0 0 2 0 0 0 0 0 3 0 0 0 0 0 How do I iterate through the Pandas DataFrame adding my array to each previous row? The expected result would be: 0 1 2 3 4 0 1 1 1 1 1 1 2 3 4 5 6 2 3 5 7 9 11 3 4 7 10 13 16
has answer: http://stackoverflow.com/a/51599195
has title: How do you add an array to each previous row in pandas?
has answer: http://stackoverflow.com/a/51599018
answer count: 4
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/51599018
favorite count: 0
has answer: http://stackoverflow.com/a/51599008
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/51599008
has comment: http://stackoverflow.com/comment/90163579

http://stackoverflow.com/q/51599191
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: Doing a calculation that references the previous value in the same column
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51599779
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90164396
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90164658
upvote count: 2
tagged with: pandas
has body: I have a dataframe that I've trying to replicate from an excel spreadsheet. It has a list of values and in the final column the formula should be if the RunningTotal = Max then the value should be 0. If the Max is equal to the max.shift(1) then the value should be the minimum of the Diff column and the and the previous value of the the MaxDraw column. list = [-350, 1350, 300, 300, -500, -100, -550, 1450, -3900, -1150, 4150, -1900, 1700, 7750, -3050, -1450, -1850, 4250] df = pd.DataFrame(data=list, columns=['Values']) df['RunningTotal'] = df['Values'].cumsum() df['Max'] = df['RunningTotal'].cummax() df['Diff'] = df['RunningTotal']-df['Max'] df['MaxDraw'] = np.where(df['RunningTotal'] == df['Max'], 0, np.where(df['Max'] == df['Max'].shift(1), **np.minimum(df['MaxDraw'].shift(1)**, df['Max']), np.nan)) The double starred code snippet is what I've tried but it looks like it can't reference a value in the row that I'm defining. I've tried doing a temporary column but i need the previous value in order to get the final result. The expected results should match the MaxDraw column below. Vales Running Total Max MaxDraw -350 -350 NA NA 1350 1000 1000 0 300 1300 1300 0 300 1600 1600 0 -500 1100 1600 -500 -100 1000 1600 -600 -550 450 1600 -1150 1450 1900 1900 0 -3900 -2000 1900 -3900 -1150 -3150 1900 -5050 4150 1000 1900 -5050 -1900 -900 1900 -5050 1700 800 1900 -5050 7750 8550 8550 0 -3050 5500 8550 -3050 -1450 4050 8550 -4500 -1850 2200 8550 -6350 4250 6450 8550 -6350 The excel forumula in D3 is =IF(A3="","",IF(C3=B3,0,IF(C3=C2,MIN(B3-C3,D2)))) Any help would be greatly appreciated as I've been banging my head against a wall over this for quite some time now! EDIT: In trying to keep this vectorized and not have to use iteration - would there be a solution that would utilize np.where and say something like the value is 0 if the max column isn't equal to the max column's previous row - otherwise return a running min of the diff column until the max column changes again?

http://stackoverflow.com/comment/90025723
has text: No, I am creating a new user for sure. But I have added a print statement, and I assume that register_view is running twice because if i add print("Yes") after form.is_valid(), "yes" is printed twice on the console.
comment on: http://stackoverflow.com/q/51523357
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51581293
type: Answer
has body: Instead of passing CSRF Token at each AJAX call (which seems to be a headache and adds to the data array passed) you could make a function in jquery to save the CSRF token as a cookie. Refer the docs. Create a file "csrf_ajax.js" (or something of your choice) paste this in it. function getCookie(name) { var cookieValue = null; if (document.cookie &amp;&amp; document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i &lt; cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) &amp;&amp; !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); Load the script using static files or relative reference Now you can make an AJAX call over POST request without worrying about the CSRF token. Hope this helps you. Cheers Kudos :)
score: 0
answers question: http://stackoverflow.com/q/51580885

http://stackoverflow.com/q/51607847
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/51607921
has comment: http://stackoverflow.com/comment/90180767
type: Question
has comment: http://stackoverflow.com/comment/90180870
has comment: http://stackoverflow.com/comment/90180959
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/90180788
has body: I have a method to remove punctuation from every word in an array of words and I want to use it a list comprehension. All I can think of with my basic Python knowledge is: def remove_punctuation(sentence: str) -&gt; str: return sentence.translate(str.maketrans('', '', string.punctuation)) def letters_only(astr): return astr.isalpha() def clean_text(docs): cleaned_docs = [] for doc in docs: cleaned_docs.append(' '.join([lemmatizer.lemmatize(remove_punctuation(word.lower())) for word in doc.split() if letters_only(word) and remove_punctuation(word) not in all_names and remove_punctuation(word) not in all_names_lower])) return cleaned_docs As you can see I am using the"remove_punctuation" method in many place. Is there any way to use if only once or more efficiently? Thanks! *letters_only - it is from some tutorial and unfortunatelly it sees word "best!" with exclamation mark at the end and removes the word - bu I am trying to make it remove only exclamation mark.
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90181113
has title: Python how to use a method in a list comprehensions
has answer: http://stackoverflow.com/a/51608242
possible better answer: http://stackoverflow.com/a/51608242
has answer: http://stackoverflow.com/a/51607921
tagged with: python

http://stackoverflow.com/q/51587601
score: 4
linked to: http://stackoverflow.com/q/19324453
tagged with: pandas
has answer: http://stackoverflow.com/a/51587702
answer count: 1
has comment: http://stackoverflow.com/comment/90140698
favorite count: 0
has comment: http://stackoverflow.com/comment/90140714
has comment: http://stackoverflow.com/comment/90140384
tagged with: python
downvote count: 1
has title: Fill in missing dates in pandas df
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51587702
linked to: http://stackoverflow.com/q/17071871
has comment: http://stackoverflow.com/comment/90140654
type: Question
has comment: http://stackoverflow.com/comment/90140614
has comment: http://stackoverflow.com/comment/90140811
has body: I have a data corresponding to a list of DBs and diff rows with dates that they were in use. DB Dates USAGE ABC 03-06-2018 IN USE ABC 07-06-2018 IN USE XYZ 04-06-2018 IN USE XYZ 08-06-2018 IN USE What i want is to have the full calendar month corresponding to every db and not just the dates on which they were in use DB Dates USAGE ABC 01-06-2018 NOT IN USE ABC 02-06-2018 NOT IN USE ABC 03-06-2018 IN USE . . ABC 07-06-2018 IN USE . . ABC 30-06-2018 NOT IN USE XYZ 01-06-2018 NOT IN USE . . XYZ 30-06-2018 NOT IN USE
upvote count: 5

http://stackoverflow.com/a/51524890
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90770054
answers question: http://stackoverflow.com/q/51524821
upvote count: 2
has body: You need threading to run 2 parts of your program "asynchronously". Untested guess: from threading import Thread def threaded_run(): t = Thread(target=main.run) t.daemon = True t.start() S = a(top, bg=(green), text= "Start Program", font=("Segoe UI Black", 40), height="2", width="15", command=threaded_run) Integrating the main.quit may be a lot harder depending on what that function does. If all it does is set the global variable 'r' to stop the loop then you can leave it as is. Otherwise you may need to walk though a couple threading tutorials to learn to make your own Thread class.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51524821

http://stackoverflow.com/comment/90234060
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51634841
has text: Try to imagine reading this from the point of view of someone who does not live in your head and isn't familiar with your work.
type: Comment

http://stackoverflow.com/comment/90091048
type: Comment
comment on: http://stackoverflow.com/a/51548973
has text: I get the following error: `Traceback (most recent call last): File "C:\Users\USER\Desktop\test.py", line 3, in <module> header = soup.find("h5") NameError: name 'soup' is not defined`
score: 0
type: AnswerComment

http://stackoverflow.com/q/51505729
tagged with: yolo
has body: I would like to train a new model using my own dataset. I will be using Darkflow/Tensorflow for it. Regarding my doubts: (1) Should we resize our training images for a specific size? (2) I think smaller images might save time, but can smaller images harm the accuracy? (3) And what about the images to be predicted, should we resize them as well or is it not necessary?
type: UnansweredQuestion
tagged with: darknet
has answer: http://stackoverflow.com/a/57575081
upvote count: 7
has title: Is image resizing needed to training a new Yolo model?
has answer: http://stackoverflow.com/a/51522729
tagged with: tensorflow
score: 7
has answer: http://stackoverflow.com/a/57576484
type: Question
downvote count: 0
favorite count: 0
answer count: 3
tagged with: darkflow
tagged with: python

http://stackoverflow.com/a/51491826
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51491656
has body: One option (according to the data samples that you provided) can be this: import re strings = ['Fresh Value Colocasia 250g', 'Fresh Value Banana Robusta 1kg', 'Fresh Value Raw Papaya 1 U (units) (300g-400g)','Fresh Value Premium Pomegranate Kabul (500g - 700g)'] for i in strings: start = re.findall('\d|\(', i)[0] name = i.split(start)[0].strip() quantity = start + i.split(start)[1] print 'Name = '+ name + ', Quantity = ', quantity Output: Name = Fresh Value Colocasia, Quantity = 250g Name = Fresh Value Banana Robusta, Quantity = 1kg Name = Fresh Value Raw Papaya, Quantity = 1 U (units) (300g-400g) Name = Fresh Value Premium Pomegranate Kabul, Quantity = (500g - 700g) Of course it is valid if the numbers and parenthesis are present only in the quantity and not in the name. If the quantity starts with other symbols, you can add them in findall
score: 1
type: Answer

http://stackoverflow.com/a/51550750
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90451007
has comment: http://stackoverflow.com/comment/90421524
upvote count: 1
answers question: http://stackoverflow.com/q/51548874
has comment: http://stackoverflow.com/comment/90433957
has comment: http://stackoverflow.com/comment/90410085
has body: You can't use a variable or an attribute before you've defined it. Either pass x and y to pygame.Rect instead of self.x, self.y, class Ball(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((100, 100)).convert_alpha() self.image.fill((160, 70, 0)) self.rect = pygame.Rect(x, y, 100, 100) self.x = self.rect.x self.y = self.rect.y or assign x and y to self.x, self.y first and create the rect afterwards: self.x = x self.y = y self.rect = pygame.Rect(self.x, self.y, 100, 100)
type: Answer
has comment: http://stackoverflow.com/comment/90450866

http://stackoverflow.com/comment/90143104
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51588402
has text: So make two "counters", for a param and b param

http://stackoverflow.com/q/51627639
accepted answer: http://stackoverflow.com/a/51627871
tagged with: python
type: AnsweredQuestion
tagged with: dataframe
has body: How do you delete and shift up specific values in pandas df. For the df below I want to delete the string 'Remove' and the 2 adjacent values and then shift the next row up. import pandas as pd d = ({ 'A' : ['X','Y','X','X','Y'], 'B' : ['Remove','A','X','Remove','A'], 'C' : ['stri','Big','Y','st','Big'], 'D' : ['ng','Cat','X','ring','Cat'], }) df = pd.DataFrame(data = d) Out: A B C D 0 X Remove stri ng 1 Y A Big Cat 2 X X Y X 3 X Remove st ring 4 Y A Big Cat I have used df['B'] = df['B'].shift(-1) but this only removes the first value. My intended output is: A B C D 0 X A Big Cat 1 Y 2 X X Y X 3 X A Big Cat 4 Y
type: Question
upvote count: 4
has title: Delete and shift values in a pandas df
downvote count: 0
score: 4
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51627871

http://stackoverflow.com/q/51521615
has comment: http://stackoverflow.com/comment/90012214
has comment: http://stackoverflow.com/comment/90012544
has body: Is there any pythonic way to find the first coincidence before a giving index? For example I want to find the 2 that go before the 1, and the the 2 that go after the 1. a = [0,2,0,0,1,0,0,2,0] for the 2 that go after the 1 I use this a.index(2,4). Is there any easy or clean way to do it?
score: 4
favorite count: 0
accepted answer: http://stackoverflow.com/a/51521748
linked to: http://stackoverflow.com/q/6890170
has title: find the index of the first coincidence in a list giving a starting position but backward
possible better answer: http://stackoverflow.com/a/51521849
tagged with: python
has answer: http://stackoverflow.com/a/51521849
has answer: http://stackoverflow.com/a/51521902
answer count: 4
has answer: http://stackoverflow.com/a/51522819
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51521748
upvote count: 5
has comment: http://stackoverflow.com/comment/90012196
type: Question

http://stackoverflow.com/q/51522050
score: 2
tagged with: anaconda
has comment: http://stackoverflow.com/comment/90044164
has comment: http://stackoverflow.com/comment/90042592
type: Question
has comment: http://stackoverflow.com/comment/90085100
downvote count: 0
has title: adding dependencies to a conda environment yaml file
has comment: http://stackoverflow.com/comment/90042395
tagged with: conda
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I have a process to setup an initial project whereby I create a standardised conda environment based on a yaml file. conda env create -f environment.yaml The yaml file looks something like this name: testA channels: - conda-forge - defaults - anaconda dependencies: - python=3.6.3=1 - yaml=0.1.7=0 - connexion=1.1.10=py36_0 - setuptools=38.4.0=py36_0 - pymongo=3.4.0=py36_0 - gunicorn=19.8.1=py36_0 - flask-cors=3.0.6=py36_0 As the project progresses a user might add another library conda install scikit-learn Is it possible to append the updated conda environment to original environment.yaml ??? - I know I can overwrite with conda env export &gt; environment.yaml

http://stackoverflow.com/q/51600390
downvote count: 0
has comment: http://stackoverflow.com/comment/90170644
has comment: http://stackoverflow.com/comment/90169806
favorite count: 0
tagged with: dtw
has comment: http://stackoverflow.com/comment/90173866
type: Question
linked to: http://stackoverflow.com/q/5963269
has comment: http://stackoverflow.com/comment/90167000
tagged with: python
has comment: http://stackoverflow.com/comment/90177160
has comment: http://stackoverflow.com/comment/90171595
tagged with: matlab
upvote count: 3
has body: I have a multiple sequences of different lengths in a list in R. I would like to construct the DTW distance matrix to be used by hierarchical clustering. When I run the following command in R: a2&lt;-dtw(Data[[1]][1],Data[[1]][2]) Error in dtw(Data[[1]][1], Data[[1]][2]) : No warping path exists that is allowed by costraints I get above error. I have no NAN or missing value but they are different lengths.I know matlab dtw can support sequence with different lengths .Can anyone suggest me how to solve this problem in R? Also to calculate the DTW distance between all sets of observation should I write a for loop for each two data series or is there any command in R or Python that can calculate the Distance given the list or dictionary as an input. Update: Input : 1 1 2 5 6 7 2 4 2 1 1 2 4 5 3 3 2 2 1 1 2 1 1 2 3 1 2 1 2 6 6 5 1 2 3 5 6 2 4 2 2 3 I want to be have the distance matrix for the above input.
has comment: http://stackoverflow.com/comment/90179895
has comment: http://stackoverflow.com/comment/90170179
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/49500668
tagged with: http://stackoverflow.com/tag/r
has title: DTW package in R Rfor sequence of different length
score: 3
has comment: http://stackoverflow.com/comment/90173361
answer count: 0

http://stackoverflow.com/comment/90059802
score: 2
has text: (1) If you would please post the code and a link to the data just for the data01.txt file, as typing in the code from the screenshot is somewhat tedious and error-prone. (2) what function are you using to fit the data? (3) Have you considered a 3D surface equation of type z = f(x,y) for fitting the data?
comment on: http://stackoverflow.com/q/51545811
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51511421
type: AcceptedAnswer
downvote count: 0
has body: It's fairly easy. All you need to have is a lookup table mapping the 23 labels into unique colors. The easiest way is to have a 23-by-3 numpy array with each row storing the RGB values for the corresponding label: import numpy as np import matplotlib.pyplot as plt lut = np.random.rand(23, 3) # using random mapping - but you can do better lb = np.argmax(prediction, axis=1) # converting probabilities to discrete labels rgb = lut[lb[0, ...], :] # this is all it takes to do the mapping. plt.imshow(rgb) plt.show() Alternatively, if you are only interested in the colormap for display purposes, you can use cmap argument of plt.imshow, but this will requires you to transform lut into a "colormap": from matplotlib.colors import LinearSegmentedColormap cmap = LinearSegmentedColormap.from_list('new_map', lut, N=23) plt.imshow(lb[0, ...], cmap=cmap) plt.show()
accepted answer of: http://stackoverflow.com/q/51495927
answers question: http://stackoverflow.com/q/51495927
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/90116747
type: Comment
score: 0
type: AnswerComment
has text: then try item_list.append(str(item['SellerSKU'])) if item['SellerSKU'] else pass
comment on: http://stackoverflow.com/a/51575455

http://stackoverflow.com/q/51489548
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51490592
tagged with: python
tagged with: dictionary
score: 1
has title: Slicing the Values of a Dictionary
has body: I'm trying to write a function that takes three parameters: a dictionary, emp_dict, a string, username, and a number emp_no. The key values in the dicionary store employee number as the key and a string for the employee name. The first three letters or the last three letters of the username must match the first three letters of the employee's name. How can I compare the string username to each of the dictionary's first three value fields. Other constraints include: The given employee number exists in the dictionary The username must be at least 4 characters The first three letters or the last three letters of the username must match the first three letters of the employee's name Here is what I have so far: def validate_employee(emp_dict, username, emp_no): if emp_no not in emp_dict: return False elif len(username) &lt; 4: return False This is where I'm having trouble. How can I write the next two elifs? elif username[0:2}.lower == emp_dict.values(): return True emp_dict={1111:'Sim',1234:'James',9999:'Amy',5555:'Jessica'} username='Jess' emp_no=5555 print(validate_employee(emp_dict, username, emp_no)) I apologize if I didn't ask this very well or if I made some pretty rookie mistakes. I'm pretty new to StackOverflow and Python programming in general. I sometimes have some trouble thinking through some problems logically. Thanks for any help you can offer!
tagged with: loops
has answer: http://stackoverflow.com/a/51489603
type: Question
tagged with: if-statement
tagged with: slice
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/51491630
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/51485205
answer count: 2
has title: Pythonic Name-Value pairs to Dictionary Conversion
has comment: http://stackoverflow.com/comment/89939533
has body: Given an array of dicts of name–value pairs, what is the most effective or most Pythonic method for converting them to a dictionary with the names as keys and and values as the values? Here's what I've come up. It's pretty short and seems to work fine, but is there some built-in function for doing just this sort of thing? verbose_attributes = [ { 'Name': 'id', 'Value': 'd3f23fa5' }, { 'Name': 'first_name', 'Value': 'Guido' }, { 'Name': 'last_name', 'Value': 'van Rossum' }] attributes = {} for pair in verbose_attributes: attributes[pair['Name']] = pair['Value'] print(repr(attributes)) # {'id': 'd3f23fa5', 'first_name': 'Guido', 'last_name': 'van Rossum'} In short, is there a better way of converting verbose_attributes to attributes?
score: 0
accepted answer: http://stackoverflow.com/a/51485271
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51485624
has answer: http://stackoverflow.com/a/51485624
type: Question
has answer: http://stackoverflow.com/a/51485271
has comment: http://stackoverflow.com/comment/89939494

http://stackoverflow.com/q/51617406
linked to: http://stackoverflow.com/q/2864842
tagged with: python
has title: Get common (not repeated) elements among 2 lists using list comprehension
has comment: http://stackoverflow.com/comment/90200461
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51617712
downvote count: 2
possible better answer: http://stackoverflow.com/a/51617518
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51617518
has comment: http://stackoverflow.com/comment/90200483
has comment: http://stackoverflow.com/comment/90200708
type: Question
has comment: http://stackoverflow.com/comment/90200405
answer count: 2
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/51617712
favorite count: 0
has body: Suppose you have 2 lists [Python 3.x]: x=[2,2,3,4,5,5,6] y=[2,3,5,9,11] What I want to accomplish is I want to get the common elements among the 2 lists, without getting repeated elements, only using list comprehension. I hope its possible ?! In other threads, I have seen the following list comprehension that kinda does the job but returns the repeated elements as well: &gt;&gt;&gt; x=[2,2,3,4,5,5,6] &gt;&gt;&gt; y=[2,3,5,9,11] &gt;&gt;&gt; z=[t for t in x if t in y] &gt;&gt;&gt; z [2, 2, 3, 5, 5] I know there are many solutions to get common elements between 2 lists. The most common solution is doing a set intersection, which gets exactly what I want, without the repeated elements. But I want to accomplish this only using list comprehension, as I said before. Thanks in advance!

tfidfvectorizer
tags question: http://stackoverflow.com/q/51633775
tag name: tfidfvectorizer
type: Tag

http://stackoverflow.com/q/51571756
type: UnansweredQuestion
tagged with: python
has title: numpy array division for entropy calculation
has answer: http://stackoverflow.com/a/51571779
type: Question
tagged with: numpy
answer count: 1
tagged with: entropy
score: 0
has body: I'm trying to create a shannon_entropy function that works on both python 2 and 3. The following code works in python 3, however, the statement to evaluate norm_counts returns a narray equaling 0 on python 2 and returns correctly in python 3. I've broken down and simplified the code below: import unittest import numpy as np def shannon_ent(labels, base=256): value, counts = np.unique(labels, return_counts=True) sum_counts = counts.sum() norm_counts = counts / sum_counts print(norm_counts) base = e if base is None else base logged_counts = np.log(norm_counts) logged_base = np.log(base) logged = logged_counts/logged_base final = -(norm_counts * logged) return final.sum() class function_tests(unittest.TestCase): def test_shannon_ent(self): chunk = [32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126] ent = shannon_ent(chunk) print('*** is: {}'.format(ent)) self.assertEqual(ent, 0.8212319510413685) if __name__ == '__main__': unittest.main() The following output is given: Python 2 # python unittest_binGraph.py (array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), 95) [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] E ====================================================================== ERROR: test_shannon_ent (__main__.function_tests) -----------…

http://stackoverflow.com/q/51527148
upvote count: 6
has body: How does pip install select wheels to install? Say I've built multiple wheels for different platforms, and upload to PyPI does pip install &lt;package&gt; automatically install the correct wheel that matches the platform? What happens if I've built a Linux specific wheel only and upload to PyPI, and someone on Windows/Mac trying to install it by running pip install &lt;package&gt;?
tagged with: pip
answer count: 1
has answer: http://stackoverflow.com/a/51527304
score: 6
has title: Pip install and platform specific wheels
type: AnsweredQuestion
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51527304
type: Question
tagged with: python-wheel
tagged with: python

http://stackoverflow.com/a/51592720
score: 0
has comment: http://stackoverflow.com/comment/90159914
type: Answer
answers question: http://stackoverflow.com/q/51592488
has comment: http://stackoverflow.com/comment/90193772
has comment: http://stackoverflow.com/comment/90152519
has body: Check out .loc[] for pandas. df_1 = pd.DataFrame(some_stuff) df_2 = df_1.loc[tickers['column'] &gt;= some-condition, 'specific-column'] you can access specific columns, run a loop to check for certain types of conditions, and if you add a comma after the condition and put in a specific column name it'll only return that column. I'm not 100% sure if that answers whatever question you're asking, cause I didn't actually see one, but it seemed like you were running a lot of for loops and stuff to isolate columns, which is what .loc[] is for.

http://stackoverflow.com/q/51551333
tagged with: python
tagged with: pythonanywhere
type: UnansweredQuestion
type: Question
has body: When attempting to use the Slack API (Real Time Messaging) I get what seems to be a certification error. Any ideas why this is happening? Would love to get some feedback to point me in the right direction. I am using python 2.7 and the code is hosted in a paid account at pythonanywhere. import os from slackclient import SlackClient verif_token = os.environ.get("MYTOKEN") slack_client = SlackClient(verif_token) slack_client.rtm_connect(with_team_state=False) Traceback (most recent call last): File "/home/xyz/.local/lib/python2.7/site-packages/slackclient/client.py", line 52, in rtm_connect self.server.rtm_connect(use_rtm_start=with_team_state, **kwargs) File "/home/xyz/.local/lib/python2.7/site-packages/slackclient/server.py", line 147, in rtm_connect self.connect_slack_websocket(self.ws_url) File "/home/xyz/.local/lib/python2.7/site-packages/slackclient/server.py", line 186, in connect_slack_websocket raise SlackConnectionError(message=str(e)) SlackConnectionError: _ssl.c:335: No root certificates specified for verification of other-side certificates.
tagged with: python-2.7
answer count: 1
has title: Slack API - rtm_connect error
tagged with: slack-api
has answer: http://stackoverflow.com/a/51557152
score: 0

http://stackoverflow.com/q/51507047
has title: selenium flashscore scrape tennis
has comment: http://stackoverflow.com/comment/89984343
has comment: http://stackoverflow.com/comment/89983547
has body: Good day! I'm trying to scrape info about matches from this site https://www.flashscore.com/player/nadal-rafael/xUwlUnRK/results/ with code: from selenium import webdriver from selenium.webdriver.firefox.options import Options from bs4 import BeautifulSoup options = Options() options.add_argument("--headless") profile = webdriver.FirefoxProfile() profile.set_preference('permissions.default.image', 2) driver = webdriver.Firefox(firefox_options = options, firefox_profile=profile) driver.implicitly_wait(40) driver.get('https://www.flashscore.com/player/nadal-rafael/xUwlUnRK/results/') src = driver.page_source soup = BeautifulSoup(src, "html.parser") table = soup.prettify() f = open('text.txt', 'w', encoding='utf-8') f.write(table) f.close() driver.close() But finally all text contains matches inside tag with id="fs-results_s" disappear &lt;div class="fs-passive fs-table tournament-page" id="fs-results_s"&gt; &lt;/div&gt; . I tried using Chrome, but that doesn't help. What can be the error?
score: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: selenium
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/89984334
type: Question

http://stackoverflow.com/a/51613444
has body: MySQLdb conforms to PEP-249. Therefore,execute must return an iterator. You can just do: for tupl in cursor.execute(query): pass where tupl is a tuple. *Alternatively, you can use fetchone, fetchmany(n) or fetchall() to evaluate at once.
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90191990
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51613359
answers question: http://stackoverflow.com/q/51613359
upvote count: 2
type: Answer

teradata
type: Tag
tags question: http://stackoverflow.com/q/51577884
tag name: teradata
tags question: http://stackoverflow.com/q/51541761
tags question: http://stackoverflow.com/q/51516588
tags question: http://stackoverflow.com/q/51526720

http://stackoverflow.com/comment/90195027
comment on: http://stackoverflow.com/q/51614756
score: 0
has text: My csv first column contains all the countries in the world and doesn't have any value Nan. I am guessing as a novice that since I used numpy to extract the file data it assumes all data to be float? Hence as the first column is all strings it shows Nan? But I'd like to know what is the work around for this if I'm correct.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90178730
type: Comment
comment on: http://stackoverflow.com/q/51588329
score: 0
type: QuestionComment
has text: We don't need such a large image to view high-resolution image. We can view without making a large image. Related issue: https://github.com/openseadragon/openseadragon/issues/1506

http://stackoverflow.com/comment/90116442
score: 0
type: Comment
has text: I liked this answer but it's not working here. A have a variable without a separator so I just applied your code without the `sep` argument. And I got this error: `ValueError: Shape of passed values is (2, 2), indices imply (2, 66899)`
type: AnswerComment
comment on: http://stackoverflow.com/a/51575137

http://stackoverflow.com/comment/90225167
score: 0
type: QuestionComment
has text: File "test2", line 8, in <module> region = sys.argv[1] IndexError: list index out of range
type: Comment
comment on: http://stackoverflow.com/q/51630229

directory
tags question: http://stackoverflow.com/q/51632645
tags question: http://stackoverflow.com/q/51529531
tag name: directory
tags question: http://stackoverflow.com/q/51507836
type: Tag
tags question: http://stackoverflow.com/q/51571270
tags question: http://stackoverflow.com/q/51501974

http://stackoverflow.com/comment/90014404
has text: Hi. My xrange is 70. y is 1.168 and the point is at 59. I don't know how you calculated these values.
comment on: http://stackoverflow.com/a/51509570
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51612693
score: 5
answers question: http://stackoverflow.com/q/51611051
upvote count: 5
downvote count: 0
has body: This kind of plot is called a "violin" plot: import numpy as np from matplotlib import pyplot as plt # Generate 5 actions with different reward distributions data = np.random.randn(1000, 5) * [1, 0.5, 1.5, 1, 0.5] + [0, 1, -1, 2, -0.5] plt.violinplot(data) plt.xlabel('Action') plt.ylabel('Reward distribution')
type: Answer

http://stackoverflow.com/a/51624114
downvote count: 0
has comment: http://stackoverflow.com/comment/90288654
has comment: http://stackoverflow.com/comment/90243314
score: 4
has comment: http://stackoverflow.com/comment/90213390
has comment: http://stackoverflow.com/comment/90213306
has body: This is covered in PEP8, the official Python style guide's, "Programming Recommendations" section: Don't compare boolean values to True or False using ==. Yes: if greeting: No: if greeting == True: Worse: if greeting is True: In other parts of the guide, they emphasize this for other use cases (e.g. testing for empty/non-empty collections should not use len()); unless a specific value is critical to your logic, use the implicit boolean nature of what you're testing (with not if it must be inverted), don't spin your wheels with comparisons that ultimately add little in terms of readability, increase fragility, and slow your code to boot. The only reason to prefer the other approaches is if you expect there to be other truthy values that should not count as truthy. In this case, the translate_tabs_to_spaces setting is very clearly boolean in nature, so you almost certainly want to handle any truthy value the same way; if they later redesigned the setting to have a numeric value, where 0 meant "don't translate" and any positive value meant the number of spaces each tab was worth, implicit truthiness evaluation would continue to work, but for the standard four space indents, a test for == 1 or == True would suddenly decide no translation was occurring.
has comment: http://stackoverflow.com/comment/90213363
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51623949

http://stackoverflow.com/comment/89959801
has text: I'm sorry, I thought you knew it.
comment on: http://stackoverflow.com/a/51495633
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51516796
answer count: 2
has comment: http://stackoverflow.com/comment/90002065
has answer: http://stackoverflow.com/a/51517155
has comment: http://stackoverflow.com/comment/90002137
downvote count: 6
favorite count: 0
type: UnansweredQuestion
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/90002006
has body: I have the following arrays: info = ['test', 'apple', 'cars', 'dog'] data = ['cat', 'list', 'text','code'] and I want to get the following result. test cat apple list cars text dog code I did this with the following code: for x, y in zip(info, data): print('{0:18} {1:}'.format(x,y)) it works, but maybe there are better options/way than mine?
has comment: http://stackoverflow.com/comment/90001985
has answer: http://stackoverflow.com/a/51518698
type: Question
upvote count: 2
has title: Join the two list into a tuple of 2 elements

http://stackoverflow.com/q/51589558
tagged with: scrapy
has body: I am using "scrapy" to scrape the author and quote from "quotes.to.scrape.com", I am passing the scraping requests through a pool of elite rotating proxy. when the scraping is done without a proxy, the result is successful. When the proxy is used, it shows error - "ImportError: No module named Tutorial.settings". I trigger the scraper within the proxy code by using 'call' function I am a beginner python coder. Thanks in advance! Following is my code : proxies = ['hardcoded proxies'] proxy_pool = cycle(proxies) url = 'httpbin.org/ip'; for i in range(1,12): #Get a proxy from the pool proxy = next(proxy_pool) print("Request #%d"%i) try: response = requests.get(url, proxies={"http": proxy, "https": proxy}) print(response.json()) print("ping/handshake passed through proxy") call(["scrapy","crawl","extract_text_author","extract.jl"]) #terminal equivalent command of triggering scrapy crawler print("scrapy passed through proxy") except: print("Skipping. Connnection error")
type: Question
tagged with: proxy
score: 0
tagged with: importerror
has title: ImportError: No module named Tutorial.settings
has comment: http://stackoverflow.com/comment/90145286
tagged with: python
has comment: http://stackoverflow.com/comment/90144980
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90236372
score: 0
has text: So i have 2 big folders: Windows and Linux. Each of them has these two i386 and x86_64 folders. I have to copy what's in folders but after the command I give it. if I run the program like this: Python example.py -i -d -a i386 p windows Will only copy the i386 folder in the windows folder if a much easier exeption would be: Python example.py -i -d -a all p all In this exe I will copy the i386 and x86_64 folders from windows but also from Linux so there are 9 command combinations
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51634841

http://stackoverflow.com/a/51677505
has body: Thank you for your suggestions but I installed it through a different way by using Anaconda with the command Conda install dlib in the Anaconda Prompt then created an environment for it. After that, I used Anaconda 5.3.0 in VSCode then started coding.
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51583346
answers question: http://stackoverflow.com/q/51583346
type: AcceptedAnswer

http://stackoverflow.com/comment/90049799
type: QuestionComment
has text: @user2285236 the problem was the complex variable which I miss them but with the **np.array** it did not solved and I used **np.ones** as you told, do you know why this happened?
comment on: http://stackoverflow.com/q/51533162
score: 0
type: Comment

http://stackoverflow.com/a/51635109
has comment: http://stackoverflow.com/comment/90236755
upvote count: 2
has comment: http://stackoverflow.com/comment/90243602
has body: The Radiobutton's variable is supposed to be a tkinter variable: import tkinter as tk root = tk.Tk() user_no = tk.IntVar() user_rb_1 = tk.Radiobutton(root, text = "Margy", variable = user_no, value = 1) user_rb_1.pack() user_rb_2 = tk.Radiobutton(root, text = "Steve", variable = user_no, value = 2) user_rb_2.pack() root.mainloop() You can then get the value selected (1 or 2) whenever you want with user_no.get(). As long as nothing's selected it will be 0.
has comment: http://stackoverflow.com/comment/90237168
downvote count: 0
answers question: http://stackoverflow.com/q/51634729
has comment: http://stackoverflow.com/comment/90265946
type: Answer
score: 2

http://stackoverflow.com/a/51548072
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51544101
type: Answer
answers question: http://stackoverflow.com/q/51544101
upvote count: 1
has comment: http://stackoverflow.com/comment/90064681
score: 1
has body: Suppose your app name is blog so in your blog's urls.py add app_name= 'blog' and in template use {% url 'blog:post_detail' pk=post.pk %}
type: AcceptedAnswer

http://stackoverflow.com/q/51569669
tagged with: python
has body: when I am running this code i get an import errror import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import Image import cv2 cap = cv2.VideoCapture("ipr.mp4") from utils import label_map_util from utils import visualization_utils as vis_util MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017' MODEL_FILE = MODEL_NAME + '.tar.gz' DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/' PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb' PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt') NUM_CLASSES = 90 opener = urllib.request.URLopener() opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE) tar_file = tarfile.open(MODEL_FILE) for file in tar_file.getmembers(): file_name = os.path.basename(file.name) if 'frozen_inference_graph.pb' in file_name: tar_file.extract(file, os.getcwd()) detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) def load_image_into_numpy_array(image): (im_width, im_height) = image.size return np.array(image.getdata()).reshape( (im_height, im_width, 3)).astype(np.uint8) PATH_TO_TEST_IMAGES_DIR = 'test_images' TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ] IMAGE_SIZE = (12, 8) with detection_graph.as_default(): with tf.Session(graph=detection_graph) as sess: while True: ret, image_np = cap.read() image_np_expanded = np.expand_dims(im…
type: UnansweredQuestion
downvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90109248
has answer: http://stackoverflow.com/a/64266768
answer count: 3
score: 5
upvote count: 6
has answer: http://stackoverflow.com/a/56287905
favorite count: 0
has comment: http://stackoverflow.com/comment/90105867
has comment: http://stackoverflow.com/comment/90112382
has answer: http://stackoverflow.com/a/51574399
has title: python - "from utils import label_map_util" ImportError: cannot import name 'label_map_util'

http://stackoverflow.com/q/51570306
has answer: http://stackoverflow.com/a/51570914
type: Question
has comment: http://stackoverflow.com/comment/90108004
has body: Sorry if the question is simple or I'm missing something obvious but I'm fairly new with console commands and Python. As the title suggests, I installed Homebrew and subsequently the latest version of Python. I want to make this the default when running python --version in bash. I tried changing the path in my bash_profile with the following line at the bottom: export PATH=/usr/local/bin:/usr/local/sbin:$PATH It seems that when I install new modules however, that they are for 2.7 and not 3. Checking pip --version going straight to the default: pip 18.0 from /usr/local/lib/python2.7/site-packages/pip (python 2.7) I also tried running the following commands: echo "export Path=/usr/local/bin:$PATH" &gt;&gt; ~/.bash_profile &amp;&amp; source ~/.bash_profile this does edit my bash_profile again, but the line I wanted (and added manually) isn't the one that appears; instead the following is inserted (I have no idea why Applications/VMware is inserted at the end, it has nothing to do with Python or what I'm trying to do): export PATH=/usr/local/bin:/usr/local/sbin:$PATHexport Path=/usr/local/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/VMware Can anyone explain to me how I can make python3 the default. I don't want to get rid of 2.7 obviously because a lot of scripts for mac still depend on it. Would it be possible to install pipenv and run 3.7 from there, while keeping 2.7 at the default?
score: 0
answer count: 2
tagged with: bash
possible better answer: http://stackoverflow.com/a/51570540
has comment: http://stackoverflow.com/comment/90106789
accepted answer: http://stackoverflow.com/a/51570914
has answer: http://stackoverflow.com/a/51570540
has comment: http://stackoverflow.com/comment/90106811
tagged with: macos
has comment: http://stackoverflow.com/comment/90106833
has comment: http://stackoverflow.com/comment/90107065
tagged with: python
type: AnsweredQuestion
has title: Installed Python 3.7 and tried changing that to the default however, changing $PATH and running python --version still shows 2.7

http://stackoverflow.com/comment/89955777
score: 3
comment on: http://stackoverflow.com/q/51493578
type: Comment
type: QuestionComment
has text: Membership tests on lists are O(N) on the size of the list (a linear search is used). You should use a `set` object, which has constant-time membership testing, and would be the typical container used in this situation.

http://stackoverflow.com/q/51539051
tagged with: attributeerror
has title: Attribute Error to send pictures on a FTP server with Python and ftplib
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51539284
type: Question
tagged with: python
has body: I'm actually trying to send pictures(.jpg) saved on a directory of my computer to a FTP server with a python script and ftplib . The path where are the images is : "D:/directory_image". I use python 2.7 and the command .storbinary from ftplib to send .jpg. Despite my search, I get an error message that I can't resolve : `AttributeError: 'str' object has no attribute 'storbinary' Here's the part of my code that cause problems : from ftplib import FTP import time import os ftp = FTP('Host') connect= ftp.login('user', 'passwd') path = "D:/directory_image" FichList = os.listdir( path ) i = len(FichList) u = 0 While u &lt; i : image_name= FichList[u] jpg_to_send = path + '/' + image_name file_open = open (image_name, 'rb') connect.storbinary('STOR '+ jpg_to_send, file_open) file_open.close() u = u + 1 I know that the file argument in Storbinary () must be an open file object instead of a string... But it's an open file object in my script, isn't it? Thanks a lot, Clara
tagged with: ftp
tagged with: ftplib
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51539170

http://stackoverflow.com/a/51595958
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51595920
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51595920
upvote count: 2
type: Answer
has body: [i for i in string.split('|') if i!=''] This should work
score: 2

http://stackoverflow.com/comment/89998034
type: Comment
comment on: http://stackoverflow.com/q/51514481
has text: I fixed it with correct pice of code
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90058846
type: QuestionComment
score: 0
has text: Might this depend on how fast the packets are arriving? Using Windows Resource manager how did you profile this (how many times, what control)? Also Java has a slow-start where Python does not.
comment on: http://stackoverflow.com/q/51545033
type: Comment

http://stackoverflow.com/q/51523063
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90015528
tagged with: python
has comment: http://stackoverflow.com/comment/90015405
answer count: 2
has title: Splitting a unicode string within a generic list
upvote count: 1
has body: So my data looks like this: data = {"technology1": [ [ 20, 0.02, u'10.00,106.10,107.00,107.00,0.45', u'24.00,-47.15,-49.50,-51.00,0.12', u'11.00,0.35,0.00,0.00,0.92', u'0.00',0.04,0.16, u'0.223196881092', u'f',0.02, ], [ 100, 0.02, u'10.00,106.10,107.00,107.00,0.45', u'24.00,-47.15,-49.50,-51.00,0.12', u'11.00,0.35,0.00,0.00,0.92', u'0.00', 0.04, 0.16, u'0.223196881092', u'f', 0.01 ] ... ], "technology2": ...} As you can see, it is a dictionary, with each key accessing a list of lists, all with the same format. Each "inner" list contains a mix of ints, floats. There are also unicode strings, some with single values in them, some with a set of 5 numbers within the unicode string. What I want: To make an array for each technology. In each array, the rows will be the "outer" list of the above, and the columns the different elements of the "inner list". The unicode ideally needs to be converted to strings (as I know how to work with them better), and the sets of 5 numbers in the unicode strings need to be expanded to be an element each. I.e. Array for technology1 20, 0.02, 10.00, 106.10, ... "f", 0.02 100, 0.02, ... "f", 0.01 Attempt so Far: for tech in data: features = data[tech] # i.e. grab technologyn for row in features: for i in row[2:5]: # 2 til 5 defines the instance which are sets of 5 #print i,"\n" i = str(i) i = i.split(',') This does not work, and when I look at features after code execution, it's exactly the same! This isn't an attempt at a complete solution, as it obviously won't convert all the unicode types to strings, but this is a stepping stone. I also tried to used a list comprehension as so: for row in features: [i.split(',') for i in row if (type(i)==unicode and "," in i)]
has comment: http://stackoverflow.com/comment/90015357
tagged with: split
has comment: http://stackoverflow.com/comment/90015663
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51524243
has answer: http://stackoverflow.com/a/51523407
downvote count: 0
score: 1
tagged with: string
tagged with: unicode

http://stackoverflow.com/a/51552641
has comment: http://stackoverflow.com/comment/118361488
upvote count: 13
has comment: http://stackoverflow.com/comment/90101754
has comment: http://stackoverflow.com/comment/118153134
type: Answer
answers question: http://stackoverflow.com/q/51523994
downvote count: 0
has body: Here is an extension of @radarhere's answer that divides the .gif into num_key_frames different parts and saves each part to a new image. from PIL import Image num_key_frames = 8 with Image.open('somegif.gif') as im: for i in range(num_key_frames): im.seek(im.n_frames // num_key_frames * i) im.save('{}.png'.format(i)) The result is somegif.gif broken into 8 pieces saved as 0..7.png.
score: 13
has comment: http://stackoverflow.com/comment/118364299
has comment: http://stackoverflow.com/comment/118358761
has comment: http://stackoverflow.com/comment/90079218

http://stackoverflow.com/comment/90010619
comment on: http://stackoverflow.com/q/51499897
type: QuestionComment
score: 0
has text: @dashiell good to know. I would have expected that this way would be faster than the "normal" recursive way, but in this case I think it won't be.
type: Comment

http://stackoverflow.com/comment/113455431
comment on: http://stackoverflow.com/q/51635113
score: 0
type: QuestionComment
has text: @ead, I just found the Holy Grial you were hiding in your garden https://github.com/realead/solinks . Have you ever thought of writing a book about Cython?
type: Comment

http://stackoverflow.com/a/51569093
downvote count: 0
answers question: http://stackoverflow.com/q/51569043
has comment: http://stackoverflow.com/comment/90140477
type: Answer
has comment: http://stackoverflow.com/comment/90104873
has body: You can use apply with pd.value_counts: df.apply(pd.value_counts).T No Why Yes Qn1 3 1 2 Qn2 2 2 2 Qn3 1 3 2 Qn4 3 1 2 If you have missing values, this will fill with NaN, so you so you way want to fillna if that is a possibility: df = pd.DataFrame({'Qn1': ['Yes'], 'Qn2': ['No'], 'Qn3': ['Why']}) df.apply(pd.value_counts).T No Why Yes Qn1 NaN NaN 1.0 Qn2 1.0 NaN NaN Qn3 NaN 1.0 NaN # With fillna() df.apply(pd.value_counts).T.fillna(0).astype(int) No Why Yes Qn1 0 0 1 Qn2 1 0 0 Qn3 0 1 0 If not all of the items are in any column, you may want to define a CategoricalDtype: df = pd.DataFrame({'Qn1': ['Yes'], 'Qn2': ['No'], 'Qn3': ['No']}) df.apply(pd.value_counts).T.fillna(0).astype(int) # Missing 'why' No Yes Qn1 0 1 Qn2 1 0 Qn3 1 0 But using a CategoricalDtype: from pandas.api.types import CategoricalDtype ct_type = CategoricalDtype(categories=['Yes', 'No', 'Why'], ordered=False) df.astype(ct_type).apply(pd.value_counts).T.fillna(0).astype(int) No Why Yes Qn1 0 0 1 Qn2 1 0 0 Qn3 1 0 0
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51569043
type: AcceptedAnswer

http://stackoverflow.com/a/51578293
type: Answer
accepted answer of: http://stackoverflow.com/q/51578119
answers question: http://stackoverflow.com/q/51578119
upvote count: 1
score: 1
has body: You can use issubclass to check types like this: from typing import Dict, List, Type, TypeVar IntList = List[int] StrList = List[str] IntStrDict = Dict[int, str] TypeT = TypeVar('TypeT') # todo: Solve without using string representation of type def is_list_type(the_type: Type[TypeT]) -&gt; bool: return issubclass(the_type, List) assert not is_list_type(IntStrDict) assert not is_list_type(int) assert not is_list_type(str) assert is_list_type(IntList) assert is_list_type(StrList)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90106316
has text: i have tried without scroll or without fixed height still it has crashed
comment on: http://stackoverflow.com/q/51569131
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51582024
tagged with: tensorflow
type: Question
score: 0
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51596212
accepted answer: http://stackoverflow.com/a/51596212
has body: I'm trying to use tensorflow thanks to a tutorial, but I'm really struggling with the way you have to use it. For the moment I trained a model with these functions : def initialize_parameters(beta=0.05): tf.set_random_seed(1) #Regularization if beta!=0: regularizer = tf.contrib.layers.l2_regularizer(scale=beta) else: regularizer=None W1 = tf.get_variable('W1',[4,4,3,8],initializer=tf.contrib.layers.xavier_initializer(seed = 0), regularizer=regularizer) W2 = tf.get_variable('W2',[2,2,8,16],initializer=tf.contrib.layers.xavier_initializer(seed = 0), regularizer=regularizer) parameters = {"W1": W1, "W2": W2} return parameters, regularizer def forward_propagation(X, parameters, regularizer=None): # Retrieve the parameters from the dictionary "parameters" W1 = parameters['W1'] W2 = parameters['W2'] # CONV2D: stride of 1, padding 'SAME' Z1 = tf.nn.conv2d(X,W1,strides=[1,1,1,1],padding='SAME') # RELU A1 = tf.nn.relu(Z1) # MAXPOOL: window 8x8, sride 8, padding 'SAME' P1 = tf.nn.max_pool(A1, ksize=[1,8,8,1], strides=[1,8,8,1],padding='SAME') # CONV2D: filters W2, stride 1, padding 'SAME' Z2 = tf.nn.conv2d(P1,W2,strides=[1,1,1,1],padding='SAME') # RELU A2 = tf.nn.relu(Z2) # MAXPOOL: window 4x4, stride 4, padding 'SAME' P2 = tf.nn.max_pool(A2,ksize=[1,4,4,1],strides=[1,4,4,1],padding='SAME') # FLATTEN P2 = tf.contrib.layers.flatten(P2) # FULLY-CONNECTED without non-linear activation function (not not call softmax). # 6 neurons in output layer. Hint: one of the arguments should be "activation_fn=None" Z3 = tf.contrib.layers.fully_connected(P2, num_outputs=6,activation_fn=None,weights_regularizer=regularizer) return Z3 def compute_cost(Z3, Y, regularizer=None): cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = Z3, labels = Y)) #Regularize if regularizer is not None: reg_variables = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) reg_term = tf.contrib.layers.apply_regularization(regularizer, reg_variables) else: reg_term = 0 cost += reg_term return cost…
type: AnsweredQuestion
has title: Predicting on new datas with TensorFlow

http://stackoverflow.com/comment/90065299
type: QuestionComment
has text: This is an ongoing issue: https://github.com/travis-ci/travis-ci/issues/9815. Seems like 3.7 isn't fully supported, so I would recommend either waiting or using a different version a python.
comment on: http://stackoverflow.com/q/51489125
score: 0
type: Comment

http://stackoverflow.com/q/51577524
tagged with: function
has answer: http://stackoverflow.com/a/51577628
answer count: 6
has comment: http://stackoverflow.com/comment/90120419
has answer: http://stackoverflow.com/a/51577629
has answer: http://stackoverflow.com/a/51577647
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51577539
has comment: http://stackoverflow.com/comment/90120412
has answer: http://stackoverflow.com/a/51577781
has answer: http://stackoverflow.com/a/51577592
downvote count: 1
possible better answer: http://stackoverflow.com/a/51577539
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51577781
has body: I am still new to python, so pardon me if this question seems stupid. I need my code to work on user input. I was expecting to be prompted for user input to complete the code but when I run the code, I get a blank terminal, no errors or extra information. This is the code: def minutes_to_hours(name): minutes = input("Insert minutes here: ") hours = minutes / 60 return hours print(hours) This is the output: Adwoks-MacBook-Pro:Python Adwok$ python3 myfunction.py
score: -1
has title: How do you print a function from user input?
type: Question
upvote count: 0

http://stackoverflow.com/q/51635286
tagged with: amazon-s3
type: Question
answer count: 2
downvote count: 0
tagged with: boto3
tagged with: amazon-web-services
accepted answer: http://stackoverflow.com/a/51637408
has answer: http://stackoverflow.com/a/66196125
tagged with: python
linked to: http://stackoverflow.com/q/1233539
favorite count: 0
possible better answer: http://stackoverflow.com/a/66196125
tagged with: python-3.x
has title: How do you specify tagging in put_object?
upvote count: 2
has body: I need to specify taggings using put_object as follows: s3client = boto3.client('s3') response = s3client.put_object(Bucket = dest_bucket_name, Body = body, Key = dest_key, Tagging = tagging, ACL = acl ) My question is what data structure do I use to for the tagging variable? I've seen various examples, but I can't get them to work. For example: tagging = {'TagSet' : [ { 'Key': 'voiceid', 'Value': polly_voice }, { 'Key': 'author', 'Value': book_author }, . . . ] } gives me "errorMessage": "Parameter validation failed:\nInvalid type for parameter Tagging, value: {'TagSet': [{'Key': 'voiceid', 'Value': 'Matthew'}, {'Key': 'author', 'Value': 'some guy'},...]}, type: &lt;class 'dict'&gt;, valid types: &lt;class 'str'&gt;" I see that it's expecting a string, but then how do I specify the key:value pairs? And all the examples I've found use some specific data structure like in my example. I doubt that this makes any difference, but I'm doing this in a lambda function.
linked to: http://stackoverflow.com/q/49047085
has answer: http://stackoverflow.com/a/51637408
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/51491133
downvote count: 2
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/51491206
has comment: http://stackoverflow.com/comment/89950804
tagged with: python
has comment: http://stackoverflow.com/comment/89950825
type: AnsweredQuestion
tagged with: conditional-statements
has answer: http://stackoverflow.com/a/51491272
accepted answer: http://stackoverflow.com/a/51491272
has body: I am trying to create a variable based in various business rules from another variable. Please see example below. When I am dealing with only one word I need to use as a condition I use the following code: physical = ['light', 'sedentary', 'medium', 'heavy'] def matcher(x): for i in physical: if i.lower() in x.lower(): return i else: return 'other' My issue is when that are multiple words that match in a sentence, in this specific cases I want to call mix. For example if more than one of the words appear in a sentence as on the first sentence then 'mix' Physical Demand Result Light to medium with occasional heavy levels mix Light lifting light Medium effort required when lifting medium tks.
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51491206
tagged with: if-statement
score: -1
has title: Conditional statements with more than 1 word in the same variable

http://stackoverflow.com/q/51628380
tagged with: python
accepted answer: http://stackoverflow.com/a/51630409
type: AnsweredQuestion
has body: I'm slowly learning my way through python and Maya, so I'm probably doing something wrong. So, for some reason, when I use polyInfo, it returns the wrong information. Example, on the basic plane, I select one vertice and execute the following command. import maya.cmds as cmds cmds.polyInfo(ve = True) It returns # Result: [u'VERTEX 48: 93 90 72 92 \n'] # Those vertices aren't relative at all to the one I selected. Hell, sometimes, it returns non-existing vertices, depending on the selected one. I don't know if relevant, but I have the same result in MEL with polyInfo -ve The doc isn't useful to me and I have a hard time finding someone with a similar problem. What's the deal here?
score: 0
type: Question
has title: Maya polyInfo -ve return the wrong values
has answer: http://stackoverflow.com/a/51630409
answer count: 1
tagged with: maya
tagged with: mel

http://stackoverflow.com/q/51555309
has comment: http://stackoverflow.com/comment/90077980
type: Question
accepted answer: http://stackoverflow.com/a/51555512
has comment: http://stackoverflow.com/comment/90078112
has comment: http://stackoverflow.com/comment/90078000
downvote count: 0
answer count: 1
has title: Is there an after request method in aiohttp like in flask
favorite count: 0
has answer: http://stackoverflow.com/a/51555512
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: aiohttp
upvote count: 2
has body: Flask provides this nice @app.after_request decorator which allows to execute a method after an http request has been handled. See documentation here. How would you achieve a similar pattern with aiohttp? Typically to send logs after the request has been handled.

http://stackoverflow.com/comment/90054800
score: 1
comment on: http://stackoverflow.com/a/51543417
has text: `Assumes your numbers are between 1 and 9.`. I'd like more clarity from OP to see whether this is actually a problem.
type: AnswerComment
type: Comment

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

http://stackoverflow.com/a/51697772
type: Answer
has body: You're supposed to have obtained a private key from docusign and saved it as "docusign_private_key.txt" on your computer. The example assumes that the file is inside a folder called "keys" which is located in your working directory. For example, you could have a docusign folder on your desktop be your working directory. Then, you could have a key folder which contains the text file. Also make sure your key is saved in PEM format as a lot of people seem to be having issues with that as well. Good luck.
answers question: http://stackoverflow.com/q/51636945
has comment: http://stackoverflow.com/comment/90415494
score: 0
accepted answer of: http://stackoverflow.com/q/51636945
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90416147

http://stackoverflow.com/q/51568024
has title: Print a nested list line by line in reverse order using list comprehension and for loop - Python
has body: my_list =[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] I am trying my best to print my_list of the form: 3 2 1 6 5 4 10 9 8 7 This is my output: 1 2 3 4 5 6 7 8 9 10 It seems really simple in "python ways", Thanks!
tagged with: nested-lists
has comment: http://stackoverflow.com/comment/90102379
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51568025
score: 1
has comment: http://stackoverflow.com/comment/90102384
has comment: http://stackoverflow.com/comment/90102371
type: Question
tagged with: for-loop
downvote count: 0
possible better answer: http://stackoverflow.com/a/52275672
has answer: http://stackoverflow.com/a/51606120
has answer: http://stackoverflow.com/a/52275672
favorite count: 0
accepted answer: http://stackoverflow.com/a/51568025
tagged with: python-2.7
tagged with: printing
answer count: 3

http://stackoverflow.com/q/51547637
downvote count: 1
tagged with: python
favorite count: 0
score: 2
tagged with: ruby
tagged with: pack
possible better answer: http://stackoverflow.com/a/76656955
tagged with: binascii
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51547687
has title: Ruby pack('H*') equivalent in Python
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/76656955
has body: I'm having a hard time figuring out why outputs aren't the same. Notice that the difference is very tiny if you compare both OUT's. What I'm trying to achieve is have the same output in Python to the one in Ruby. Ruby: IN:['034151a3ec46b5670a682b0a63394f863587d1bc97483b1b6c70eb58e7f0aed192'].pack('H*') OUT:\x03AQ\xA3\xECF\xB5g\nh+\nc9O\x865\x87\xD1\xBC\x97H;\elp\xEBX\xE7\xF0\xAE\xD1\x92 Python: IN:unhexlify('034151a3ec46b5670a682b0a63394f863587d1bc97483b1b6c70eb58e7f0aed192') OUT:\x03AQ\xa3\xecF\xb5g\nh+\nc9O\x865\x87\xd1\xbc\x97H;\x1blp\xebX\xe7\xf0\xae\xd1\x92
has answer: http://stackoverflow.com/a/51547687
upvote count: 3

http://stackoverflow.com/a/51603536
downvote count: 0
has comment: http://stackoverflow.com/comment/90173109
answers question: http://stackoverflow.com/q/51603472
type: Answer
has body: May be you can use slice as: phone['PN'] = phone['PN'].str.slice(0, 10) or, phone['PN'] = phone['PN'].str[:10]
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90173099

http://stackoverflow.com/comment/92448168
score: 0
type: Comment
has text: It does say in the docs "However, for a structured record type use namedtuple() instead.", but they don't seem to make that distinction about immutable instances
comment on: http://stackoverflow.com/a/51560628
type: AnswerComment

http://stackoverflow.com/comment/90143102
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51588925
has text: [i] come from list comprehension --> for i in similar_indices

http://stackoverflow.com/comment/90110974
comment on: http://stackoverflow.com/a/51572366
type: Comment
has text: Thanks a lot, acctually im not using conda (gave me some problems) , but I got this output: C:\Users\bbattach\AppData\Local\Continuum\anaconda3\python.exe C:\Users\bbattach\AppData\Local\Programs\Python\Python36\python.exe". How can I change to the second interpeter?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90122815
comment on: http://stackoverflow.com/q/51578720
has text: Your YAML indentation seems to be off. Can you fix that?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/51571612
score: -4
type: Question
has comment: http://stackoverflow.com/comment/90109479
linked to: http://stackoverflow.com/q/6967632
has title: How to unpack a nested list in Python3?
upvote count: 2
has answer: http://stackoverflow.com/a/51571679
tagged with: iterable-unpacking
has answer: http://stackoverflow.com/a/51571753
favorite count: 0
has answer: http://stackoverflow.com/a/51571866
type: UnansweredQuestion
tagged with: python
answer count: 4
has body: Lst = [[1,2,3],[201,202,203],[3,1,4],[591,2019,3.14]] What I need is- a1,b1,c1 = (1,2,3) a2,b2,c2 = (201,202,203) and so on ...
downvote count: 6
tagged with: list
has answer: http://stackoverflow.com/a/51571700

http://stackoverflow.com/comment/115663675
has text: Note, it's daily-rounded. i.e.: print(pd.to_datetime(pd.Series(2880), unit='m').dt.strftime('%H:%M')) returns 00:00
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51566287

http://stackoverflow.com/comment/90234716
type: AnswerComment
score: 0
type: Comment
has text: Table does get created. I can see it on my mysql but not on my phpmyadmin.
comment on: http://stackoverflow.com/a/51620218

http://stackoverflow.com/comment/90243870
type: Comment
comment on: http://stackoverflow.com/a/51639429
has text: Yep. It was clearly visible and spread over throughout the time.
type: AnswerComment
score: 0

http://stackoverflow.com/a/51576939
has comment: http://stackoverflow.com/comment/90119621
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51574470
has body: You keep overwriting your coindata dictionary inside the loop, which is why only the last value remains. The second issue with your code is that you keep overriding the coindata['koinex'] dictionary inside the loop. This should be a list not a dictionary because you'll keep adding values to it. If you move the initialization code outside the loop, you will not have this problem: coindata = {} coindata['koinex'] = [] # this should be a list, not a dictionary for coin in koinexprice: print(coin) # Create a temporary dictionary d to hold the data you want # to add to coindata d = {coin: {'SellingPrice': koinexprice[coin]['highest_bid'], 'buyingPrice': koinexprice[coin]['lowest_ask']} } coindata["koinex"].append(d) # add the new dictionary to the list print(coindata)
has comment: http://stackoverflow.com/comment/90119668
type: Answer
has comment: http://stackoverflow.com/comment/90119612
answers question: http://stackoverflow.com/q/51574470

http://stackoverflow.com/q/51489570
favorite count: 0
possible better answer: http://stackoverflow.com/a/51489731
has answer: http://stackoverflow.com/a/51489731
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51491949
downvote count: 0
score: 1
has title: How to subtract numbers from lines to get time difference
type: Question
has answer: http://stackoverflow.com/a/51491949
has body: So for a data like : 01:58:30| USER INPUT : "Hello " 01:58:30| SYSTEM RESPONSE: "Hello. How are you" 01:58:56| USER INPUT : "Good thank you. How about you?" 01:58:57| SYSTEM RESPONSE: "I am doing great!" 01:59:13| USER INPUT : "Thats it" 01:59:15| SYSTEM RESPONSE: "Deal" 13:29:28| USER INPUT : "Deal" I want to subtract the time it took for response for each line For example: 01:58:30| USER INPUT : "Hello " &lt;0 seconds&gt; 01:58:30| SYSTEM RESPONSE: "Hello. How are you" &lt;26 seconds&gt; 01:58:56| USER INPUT : "Good thank you. How about you?" &lt;1 seconds&gt; 01:58:57| SYSTEM RESPONSE: "I am doing great!" &lt;16 seconds&gt; 01:59:13| USER INPUT : "Thats it" &lt;2 seconds&gt; 01:59:15| SYSTEM RESPONSE: "Deal" so far, I know how to calculate the time difference: from datetime import datetime s1 = '01:59:13' s2 = 01:59:15' # for example format = '%H:%M:%S' time = datetime.strptime(s2, format) - datetime.strptime(s1, format) print time I could use any suggestions to get just the a way to read lines. Please feel free to ask me more clarification any time!
tagged with: python-2.7
answer count: 2
upvote count: 1

http://stackoverflow.com/comment/89957710
type: Comment
has text: Django won't serve static files in a production setup, you must use a webserver in front of it. [Django](https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/uwsgi/) and [uwsgi](https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html) docs.
comment on: http://stackoverflow.com/q/51494633
score: 0
type: QuestionComment

http://stackoverflow.com/q/51497681
has comment: http://stackoverflow.com/comment/90005540
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89964530
has comment: http://stackoverflow.com/comment/90003107
downvote count: 2
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89994490
has title: AttributeError: 'list' object has no attribute 'lower' : clustering
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51552215
accepted answer: http://stackoverflow.com/a/51552215
has body: I'm trying to do a clustering. I'm doing with pandas and sklearn. import pandas import pprint import pandas as pd from sklearn.cluster import KMeans from sklearn.metrics import adjusted_rand_score from sklearn.feature_extraction.text import TfidfVectorizer dataset = pandas.read_csv('text.csv', encoding='utf-8') dataset_list = dataset.values.tolist() vectors = TfidfVectorizer() X = vectors.fit_transform(dataset_list) clusters_number = 20 model = KMeans(n_clusters = clusters_number, init = 'k-means++', max_iter = 300, n_init = 1) model.fit(X) centers = model.cluster_centers_ labels = model.labels_ clusters = {} for comment, label in zip(dataset_list, labels): print ('Comment:', comment) print ('Label:', label) try: clusters[str(label)].append(comment) except: clusters[str(label)] = [comment] pprint.pprint(clusters) But I have the following error, even though I have never used the lower(): File "clustering.py", line 19, in <module> X = vetorizer.fit_transform(dataset_list) File "/usr/lib/python3/dist-packages/sklearn/feature_extraction/text.py", line 1381, in fit_transform X = super(TfidfVectorizer, self).fit_transform(raw_documents) File "/usr/lib/python3/dist-packages/sklearn/feature_extraction/text.py", line 869, in fit_transform self.fixed_vocabulary_) File "/usr/lib/python3/dist-packages/sklearn/feature_extraction/text.py", line 792, in _count_vocab for feature in analyze(doc): File "/usr/lib/python3/dist-packages/sklearn/feature_extraction/text.py", line 266, in <lambda> tokenize(preprocess(self.decode(doc))), stop_words) File "/usr/lib/python3/dist-packages/sklearn/feature_extraction/text.py", line 232, in <lambda> return lambda x: strip_accents(x.lower()) AttributeError: 'list' object has no attribute 'lower' I don't understand, my text (text.csv) is already lowercase. And I at no time called lower() Data: hello wish to cancel order thank you confirmation hello would like to cancel order made today store house world dimensions bed not compatible would like to k…
score: -1
has comment: http://stackoverflow.com/comment/89963384
type: Question
has comment: http://stackoverflow.com/comment/89995160
has comment: http://stackoverflow.com/comment/89964272
has comment: http://stackoverflow.com/comment/89978003
answer count: 1
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/89963374
tagged with: pandas

http://stackoverflow.com/comment/89948670
type: QuestionComment
comment on: http://stackoverflow.com/q/51490014
has text: " https://drive.google.com/open?id=1AJfASFyL9SSE82-Y0rrQi9a956NIXdIc " here's my code. And I have checked my working directory multiple times. the idea is to count .png file per month in a year
score: 0
type: Comment

http://stackoverflow.com/q/51516628
has comment: http://stackoverflow.com/comment/90001749
has comment: http://stackoverflow.com/comment/90001844
answer count: 6
has title: split string using re and add integers in python
has comment: http://stackoverflow.com/comment/90002099
accepted answer: http://stackoverflow.com/a/51516763
has answer: http://stackoverflow.com/a/51516770
tagged with: regex
has comment: http://stackoverflow.com/comment/90001899
has answer: http://stackoverflow.com/a/51520574
score: 0
tagged with: python
has body: I have following string '100000|^104,500|^^0^0^0^0^0^0^0|^^^^^^^^^412824|103000|103000|103000|103000^^' How to sum last 5 integers after |^^^^^^^^^ till ^^ separated by |. I tried re.split('[|^^^^^^^^^]', string) but it splits using |^ delimiter and returns list.
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51516768
has comment: http://stackoverflow.com/comment/90001826
has answer: http://stackoverflow.com/a/51516768
has answer: http://stackoverflow.com/a/51516916
has answer: http://stackoverflow.com/a/51516763
has answer: http://stackoverflow.com/a/51516997
has comment: http://stackoverflow.com/comment/90001681
type: Question
has comment: http://stackoverflow.com/comment/90001850

sublimetext3
tags question: http://stackoverflow.com/q/51585792
tags question: http://stackoverflow.com/q/51576404
type: Tag
tags question: http://stackoverflow.com/q/51544649
tag name: sublimetext3
tags question: http://stackoverflow.com/q/51584708

http://stackoverflow.com/comment/90027180
type: QuestionComment
has text: My MetPy's version is 0.8.0
comment on: http://stackoverflow.com/q/51515440
score: 0
type: Comment

http://stackoverflow.com/a/51491277
score: 0
answers question: http://stackoverflow.com/q/51490376
has body: I got this resolved myself. I was using a function to check for nonzero values. Here I just did a compare of string directly. Thanks for the help. a['testcol'] = np.where(a['SLOT'] == '0',a['name'],a['name'] + '_' + a['SLOT'])
type: Answer

http://stackoverflow.com/q/51583268
tagged with: django
answer count: 1
has title: Template not rendered in Vue served by Django
upvote count: 4
accepted answer: http://stackoverflow.com/a/51583269
type: AnsweredQuestion
tagged with: vue.js
downvote count: 0
tagged with: javascript
favorite count: 0
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/33878766
has body: I have a Django app for backend, which renders templates with Vue as frontend. My view code in django has the following parts: # thing/views.py def index(request): template = loader.get_template('thing/index.html') return HttpResponse(template.render({}, request)) # thing/urls.py from django.views.generic import TemplateView urlpatterns = [ path('', TemplateView.as_view(template_name='index.html')), ] # some other files that complete the project are not included In index.html there is the following code: &lt;div id="app"&gt; &lt;p v-if="quotaRemaining &gt; -1"&gt; Remaining: {{ quotaRemaining }} &lt;/p&gt; &lt;/div&gt; &lt;script&gt; const app = new Vue({ el: '#app', data: { quotaRemaining: 42, }, }); &lt;/script&gt; The only thing that is being rendered when I access this page is: Remaining: While I would expect it to be Remaining: 42 Why is my Vue template not being rendered correctly when served by Django? How do I make it work?
score: 4
duplicate of: http://stackoverflow.com/q/33878766
has answer: http://stackoverflow.com/a/51583269

http://stackoverflow.com/q/51571530
favorite count: 0
has answer: http://stackoverflow.com/a/51571613
has answer: http://stackoverflow.com/a/51571554
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: selenium
accepted answer: http://stackoverflow.com/a/51571554
type: Question
has body: I am trying to Write some data in a CSV file using Selenium While running the Code labels = browser.find_elements_by_xpath('.//a[@class="question-hyperlink"]') text = [x.text for x in labels] data.append(text) print(text) with open('output.csv', 'wb') as data_file: writer = csv.writer(data_file) writer.writerows(data) the output am getting is data1 data2 data3 data4 data5 data6 data7 data8 data9 data10 data11 data12 data13 data14 data15 But I want to write the data as below data1 data2 data3 data4 ..... data15 How can I do that? please help me.
answer count: 2
has title: Selenium WebDriver Write data line by line into CSV
downvote count: 0
possible better answer: http://stackoverflow.com/a/51571613

http://stackoverflow.com/comment/90157250
type: QuestionComment
score: 2
has text: What problem are you facing when grouping by the `year-month` set?
comment on: http://stackoverflow.com/q/51595690
type: Comment

http://stackoverflow.com/q/51620155
has answer: http://stackoverflow.com/a/51620294
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51620774
score: 1
type: Question
answer count: 2
tagged with: python-2.7
has body: I have a log file : USER INPUT : “clear” SYSTEM RESPONSE: “Hello! How are you?” USER INPUT : “Good thank you” SYSTEM RESPONSE: "Okay" USER INPUT : “clear” SYSTEM RESPONSE: “Hello! How are you?” USER INPUT : “I am good, Thank you!” SYSTEM RESPONSE: "Great!" USER INPUT : “Good” and my current code for them is in python and html : import re from pprint import pprint log_file = """USER INPUT : "clear" SYSTEM RESPONSE: Hello! How are you? USER INPUT : Good thank you SYSTEM RESPONSE: Okay USER INPUT : "clear" SYSTEM RESPONSE: Hello! How are you? USER INPUT : I am good, Thank you! SYSTEM RESPONSE: Great! USER INPUT : Good""" groups = re.findall(r'USER INPUT.*?clear.*?(?:(?=USER INPUT :\s+\Wclear\W)|(?=\Z))', log_file, flags=re.DOTALL) html='' data = [] for d, g in zip(data, groups): for line in groups.splitlines(): html += """ """+ line + 'Tooltip text \n' pprint(""" """+ html) My code currently adds the hover feature for all the lines, but I only want it for anything that follows USER INPUT: "....." Any suggestions will be great! Thank you! Please feel free to ask me for any questions or clarifications
has title: Find all words after a specific word and replace it with HTML code
tagged with: http://stackoverflow.com/tag/html
downvote count: 0

http://stackoverflow.com/comment/90003959
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51517421
has text: Thanks , it clarifies .
score: 0

http://stackoverflow.com/comment/90134751
score: 0
type: AnswerComment
type: Comment
has text: On Postgresql you do need the 2 column index, if you want to avoid the sort. Of course if it's already performant enough without, you might not need to bother.
comment on: http://stackoverflow.com/a/51527976

http://stackoverflow.com/comment/90055330
type: AnswerComment
type: Comment
has text: i tried your code but its giving 900 combinations possible, that is it is joining 75 lines of 2.csv to each single lines of 1.csv that is 50 lines.
score: 0
comment on: http://stackoverflow.com/a/51543619

http://stackoverflow.com/a/51493075
has comment: http://stackoverflow.com/comment/89955265
type: Answer
has body: Some of your lists - a and c - have more than one value, but you're only using one value in your statements (%s). This is considered an error since it's unclear if the extra parameters were intentional or not. If you intend to insert one row per element in the source arrays, use executemany and pass in a sequence of parameters: a = [('apq3',), ('aquaporin',)] b = [('skin',)] c = [('down-regulated',), ('down regulation',) ('down regulate',)] [...] # Insert two rows (one for each parameter list in `a`) cursor.executemany('INSERT INTO a (term) VALUES(%s)', a)
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51493021
has comment: http://stackoverflow.com/comment/89954834
answers question: http://stackoverflow.com/q/51493021
upvote count: 1
has comment: http://stackoverflow.com/comment/89954856
type: AcceptedAnswer

http://stackoverflow.com/comment/90065276
has text: The value of ``sys.prefix`` would usually give the root directory of a virtual environment. If conda env are similar you just need to take last segment of path from that. Possibly easier to determine from that than ``sys.executable``.
type: Comment
comment on: http://stackoverflow.com/a/51548805
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90210794
type: QuestionComment
has text: Yes, that's what I meant.
comment on: http://stackoverflow.com/q/51622452
score: 0
type: Comment

http://stackoverflow.com/a/51581607
has body: You could retrieve all of the URLs and then sort through them keeping only those that begin with /players/. This can easily be done using a list comprehension and the startswith method. urls = [url for url in urls if url.startswith("/players/")] Where urls is an array of all of the urls you have retrieved.
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51581264
answers question: http://stackoverflow.com/q/51581264
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/90233762
type: AnswerComment
has text: I'm really not a fan of the `tuple(iterable)` here. You're losing all the benefits of lazy evaluation just to get slicing. If you're going to write a generator solution, you should try to hold it to the same standards as the `itertools` generators, so you can hook them together into a lazily evaluated pipeline.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51600100

http://stackoverflow.com/q/51577412
answer count: 2
has title: How to compare values between key value pairs in a dictionary of python?
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51577453
has body: My plan is to take every value in a python dict, so I have done that. data = {} for _ in range(int(input())): n = input() s = float(input()) data.update({n: s}) &gt;&gt;&gt; 2 &gt;&gt;&gt; harry &gt;&gt;&gt; 2 &gt;&gt;&gt; barry &gt;&gt;&gt; 3 &gt;&gt;&gt; {'harry': 2.0, 'barry': 3.0} now I want to compare the VALUES in this dict and return the result of max-min. How could i do this ? thanks in advance
type: Question
has answer: http://stackoverflow.com/a/51577449
accepted answer: http://stackoverflow.com/a/51577449
has answer: http://stackoverflow.com/a/51577453
score: 0

http://stackoverflow.com/comment/89994631
comment on: http://stackoverflow.com/q/51510255
has text: You presumably want a POST request rather than a GET here, and the contents should be JSON.
score: 0
type: Comment
type: QuestionComment

javascript
tags question: http://stackoverflow.com/q/51634550
tags question: http://stackoverflow.com/q/51561396
tags question: http://stackoverflow.com/q/51616647
tags question: http://stackoverflow.com/q/51575373
tags question: http://stackoverflow.com/q/51503242
tags question: http://stackoverflow.com/q/51525261
tags question: http://stackoverflow.com/q/51590480
tag name: javascript
tags question: http://stackoverflow.com/q/51600410
tags question: http://stackoverflow.com/q/51580885
tags question: http://stackoverflow.com/q/51509970
type: Tag
tags question: http://stackoverflow.com/q/51508977
tags question: http://stackoverflow.com/q/51627149
tags question: http://stackoverflow.com/q/51517968
tags question: http://stackoverflow.com/q/51525964
tags question: http://stackoverflow.com/q/51583268
tags question: http://stackoverflow.com/q/51578978
tags question: http://stackoverflow.com/q/51572230
tags question: http://stackoverflow.com/q/51577038
tags question: http://stackoverflow.com/q/51489198
tags question: http://stackoverflow.com/q/51495315
tags question: http://stackoverflow.com/q/51566338
tags question: http://stackoverflow.com/q/51604230
tags question: http://stackoverflow.com/q/51552622
tags question: http://stackoverflow.com/q/51621972
tags question: http://stackoverflow.com/q/51584796
tags question: http://stackoverflow.com/q/51500703
tags question: http://stackoverflow.com/q/51581792
tags question: http://stackoverflow.com/q/51486736
tags question: http://stackoverflow.com/q/51526790
tags question: http://stackoverflow.com/q/51620561
tags question: http://stackoverflow.com/q/51552684
tags question: http://stackoverflow.com/q/51575155
tags question: http://stackoverflow.com/q/51591849
tags question: http://stackoverflow.com/q/51507333
tags question: http://stackoverflow.com/q/51507395
tags question: http://stackoverflow.com/q/51491217
tags question: http://stackoverflow.com/q/51622776
tags question: http://stackoverflow.com/q/51542001
tags question: http://stackoverflow.com/q/51585240
tags question: http://stackoverflow.com/q/51505142
tags question: http://stackoverflow.com/q/51549170

http://stackoverflow.com/comment/90186934
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51598416
has text: That's great; it does exactly what I asked for; apply the same functions to each dataframe in a dictionary of dataframes. Now I only have to work out what I wanted!
score: 1

http://stackoverflow.com/q/51540046
has answer: http://stackoverflow.com/a/51540237
has body: Say i have two arrays: a = [1, 1, 1] and b = [0, 0] I want to concatenate these randomly in a seperate variable c, until i reach some desired length of c. So something like: N = 10 c = random_concatenating((a, b), N) [1, 1, 1, 0, 0, 1, 1, 1, 0, 0]
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51540119
possible better answer: http://stackoverflow.com/a/51540176
type: Question
has answer: http://stackoverflow.com/a/51540176
accepted answer: http://stackoverflow.com/a/51540237
has title: In python randomly concatenating two arrays until limit length is met
score: -4
has comment: http://stackoverflow.com/comment/90047723
downvote count: 4
answer count: 3
upvote count: 0
has comment: http://stackoverflow.com/comment/90047862
favorite count: 0

http://stackoverflow.com/a/51624602
has comment: http://stackoverflow.com/comment/90354797
has comment: http://stackoverflow.com/comment/90270172
has comment: http://stackoverflow.com/comment/90220930
type: AcceptedAnswer
downvote count: 0
score: 1
has body: Legend part: it's the same way you would put a legend into a plot - simply call plt.legend() with m.plot() having the label argument. So, in your case it would be: handle_dict = { "Andriod" : 0, "iPhone" : 0, "Other" : 0 } colors = ['r', 'g', 'b'] increment = 0 for app in data: for item in app: if len(item) == 2: lat, lon = item[0], item[1] x, y = map(lon, lat) map.plot(x, y, colors[increment] + 'o', label = handle_dict[type_phone] if handle_dict[type_phone] == 0 else "_no-legend_") handle_dict[type_phone] += 1 increment += 1 plt.legend() plt.title("Geo-position Twitter Devices") plt.show() You'd also have to modify your code to identify the type of phone that is being plotted (hence the variable type_phone). Here's the link to the documentation regarding legends to modify the legend. Making the map better: Personally, I like to use map.shadedrelief() for these world views - it's not as dark as map.bluemarble() and you can easily see the points better. There's really no need for the map.arcgisimage() argument here because you have a world view rather than a zoomed in view - it'll generate your map a bit quicker if you use the built in function. I'd also add the markeredgewidth argument to map.plot() to make the marker edge width to be something other than zero because right now your points look like they're blending in with the background. It'll make your dots pop out more. Oh - also take time out to upgrade to Python 3 if you're able to.
type: Answer
accepted answer of: http://stackoverflow.com/q/51584866
answers question: http://stackoverflow.com/q/51584866
upvote count: 1

http://stackoverflow.com/comment/90224090
score: 0
has text: Ah, I think we're almost there. First execute `pip uninstall -U tensorflow` and then `pip install -U tensorflow==1.5.0 --ignore-installed six`
type: Comment
comment on: http://stackoverflow.com/a/51629636
type: AnswerComment

http://stackoverflow.com/q/51544483
has comment: http://stackoverflow.com/comment/90077209
has comment: http://stackoverflow.com/comment/90077001
has title: How can I copy pyre2.Pattern object
has body: I am using pyre2 in my code and get such error: &gt;&gt;&gt; import re2 &gt;&gt;&gt; pattern = re2.compile('gfhkjgf') &gt;&gt;&gt; from copy import deepcopy &gt;&gt;&gt; pattern_copy = deepcopy(pattern) &gt;&gt;&gt; pattern.match('hgjfkkhjg') &gt;&gt;&gt; pattern_copy.match('hgjfkkhjg') [1] 21440 segmentation fault python Python version: Python 2.7.14 (default, Mar 22 2018, 15:04:47) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin This is simplified example of what I am trying to do. In my code I have Config object which is looking like {re2.Pattern: str} in some cases I need to update it with value and pass to some function. Why I cannot just copy re2.Pattern object? UPD: With re everything is ok
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90076971
upvote count: 1
has comment: http://stackoverflow.com/comment/90076859
score: 1
type: Question
tagged with: re2
downvote count: 0

http://stackoverflow.com/a/51541710
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51541386
upvote count: 1
has body: You need: grp = df.groupby('group') df.assign( min_utd = grp['amount'].cummin(), max_utd = grp['amount'].cummax(), no_n_utd = grp.apply(lambda g: g['amount'].lt(0).cumsum()).values, no_p_utd = grp.apply(lambda g: g['amount'].gt(0).cumsum()).values ) Output: group year amount min_utd max_utd no_n_utd no_p_utd 0 1 2007 2.0 2.0 2.0 0 1 1 1 2008 -4.0 -4.0 2.0 1 1 2 1 2009 5.0 -4.0 5.0 1 2 3 1 2010 7.0 -4.0 7.0 1 3 4 2 2006 8.0 8.0 8.0 0 1 5 2 2007 -10.0 -10.0 8.0 1 1 6 2 2008 12.0 -10.0 12.0 1 2

http://stackoverflow.com/q/51549853
type: Question
tagged with: python
tagged with: jupyter-notebook
upvote count: 2
tagged with: excel
type: UnansweredQuestion
has body: I'm planning on creating some pd.pivot_table() views with some sns.plots and export as a html report. Is it possible to have the data / graph update based on an user-friendly filter button? For instance, I want the end users to have the ability to select their Sales Region, Direction of Trade (Export vs. Import), etc. and view the data/graph accordingly.
has title: Pandas: Is it possible to create an Excel Slicer-like (interactive filters) within Jupyter Notebook?
has comment: http://stackoverflow.com/comment/90067177
tagged with: pandas
score: 2
answer count: 0
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90145680
comment on: http://stackoverflow.com/a/51576045
score: 0
type: Comment
has text: @Martoolius Thank you for your additional information. I couldn't notice about it. I could study from your question. Thank you so much.
type: AnswerComment

http://stackoverflow.com/comment/89973215
has text: `df['gender'].map({ 'Male':1, 'Female':0 })` ?
comment on: http://stackoverflow.com/q/51502373
score: 0
type: Comment
type: QuestionComment

parsimonious
tags question: http://stackoverflow.com/q/51561623
tag name: parsimonious
type: Tag

http://stackoverflow.com/a/51494851
answers question: http://stackoverflow.com/q/51494675
has comment: http://stackoverflow.com/comment/89958558
score: 1
upvote count: 1
downvote count: 0
has body: I believe you can use itertools groupby function but might need to modify the areTheSame function so it will be a keyfunc, i.e. will yield some kind of key. L1 = sorted(L1, key=keyfunc) L2 = [list(g) for _, g in groupby(L1, keyfunc))
type: Answer

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

regex
tags question: http://stackoverflow.com/q/51506177
tags question: http://stackoverflow.com/q/51526759
tags question: http://stackoverflow.com/q/51577128
tags question: http://stackoverflow.com/q/51568224
tags question: http://stackoverflow.com/q/51534312
tags question: http://stackoverflow.com/q/51492791
tags question: http://stackoverflow.com/q/51590122
tags question: http://stackoverflow.com/q/51579629
tags question: http://stackoverflow.com/q/51510378
tags question: http://stackoverflow.com/q/51583749
tags question: http://stackoverflow.com/q/51627355
tags question: http://stackoverflow.com/q/51608162
tags question: http://stackoverflow.com/q/51600237
tags question: http://stackoverflow.com/q/51546408
tags question: http://stackoverflow.com/q/51512892
tags question: http://stackoverflow.com/q/51636854
tags question: http://stackoverflow.com/q/51489128
tags question: http://stackoverflow.com/q/51575504
tags question: http://stackoverflow.com/q/51545783
tags question: http://stackoverflow.com/q/51493070
tags question: http://stackoverflow.com/q/51562147
tags question: http://stackoverflow.com/q/51499765
tag name: regex
tags question: http://stackoverflow.com/q/51602523
tags question: http://stackoverflow.com/q/51621069
tags question: http://stackoverflow.com/q/51543354
tags question: http://stackoverflow.com/q/51599289
tags question: http://stackoverflow.com/q/51618390
tags question: http://stackoverflow.com/q/51522564
tags question: http://stackoverflow.com/q/51588754
tags question: http://stackoverflow.com/q/51582913
tags question: http://stackoverflow.com/q/51564375
tags question: http://stackoverflow.com/q/51555521
tags question: http://stackoverflow.com/q/51618575
tags question: http://stackoverflow.com/q/51513925
tags question: http://stackoverflow.com/q/51555643
tags question: http://stackoverflow.com/q/51518172
tags question: http://stackoverflow.com/q/51505207
tags question: http://stackoverflow.com/q/51536619
tags question: http://stackoverflow.com/q/51576181
tags question: http://stackoverflow.com/q/51526896
tags question: http://stackoverflow.com/q/51619889
tags question: http://stackoverflow.com/q/51516361
tags question: http://stackoverflow.com/q/51496215
tags question: http://stackoverflow.com/q/51487012
tags question: http://stackoverflow.com/q/51520989
tags question: http://stackoverflow.com/q/51525961
tags question: http://stackoverflow.com/q/51517016
tags question: http://stackoverflow.com/q/51620195
tags question: http://stackoverflow.com/q/51588887
tags question: http://stackoverflow.com/q/51606837
tags question: http://stackoverflow.com/q/51494308
tags question: http://stackoverflow.com/q/51493351
tags question: http://stackoverflow.com/q/51636658
tags question: http://stackoverflow.com/q/51620908
tags question: http://stackoverflow.com/q/51523720
tags question: http://stackoverflow.com/q/51526695
tags question: http://stackoverflow.com/q/51509915
tags question: http://stackoverflow.com/q/51524227
tags question: http://stackoverflow.com/q/51635285
tags question: http://stackoverflow.com/q/51606032
tags question: http://stackoverflow.com/q/51495994
tags question: http://stackoverflow.com/q/51619188
tags question: http://stackoverflow.com/q/51534256
tags question: http://stackoverflow.com/q/51564511
tags question: http://stackoverflow.com/q/51603472
tags question: http://stackoverflow.com/q/51593524
tags question: http://stackoverflow.com/q/51535921
tags question: http://stackoverflow.com/q/51589769
tags question: http://stackoverflow.com/q/51602700
tags question: http://stackoverflow.com/q/51595343
tags question: http://stackoverflow.com/q/51619552
tags question: http://stackoverflow.com/q/51608432
tags question: http://stackoverflow.com/q/51613804
tags question: http://stackoverflow.com/q/51557531
tags question: http://stackoverflow.com/q/51586094
tags question: http://stackoverflow.com/q/51587474
tags question: http://stackoverflow.com/q/51632275
tags question: http://stackoverflow.com/q/51583544
tags question: http://stackoverflow.com/q/51540331

http://stackoverflow.com/comment/107984092
comment on: http://stackoverflow.com/a/51517863
score: 0
type: AnswerComment
type: Comment
has text: Your code is for google cloud speech to text api. Whereas I am using speech_recognition available on Pypi which uses google web speech. link is here : https://pypi.org/project/SpeechRecognition/

http://stackoverflow.com/q/51575089
has title: Python - One-hot-encode to single column
has body: I'm almost zero experienced with python but I'm trying to learn it. I have a Pandas dataframe which came with some dummies. I want to convert them back to a single column but I simply can't figure out a way to that. Is there any way to that? I have this: ID var_1 var_2 var_3 var_4 231 1 0 0 0 220 0 1 0 0 303 0 0 1 0 324 0 0 0 1 I need to transform to it: ID var 231 1 220 2 303 3 324 4
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51575128
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51575137
downvote count: 0
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51575128
possible better answer: http://stackoverflow.com/a/51575137
type: Question
tagged with: one-hot-encoding
tagged with: python

http://stackoverflow.com/comment/90155639
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51594877
type: QuestionComment
has text: You shouldn't have a try at all. There is no relevant exception that raw_input could raise that you want to catch.

http://stackoverflow.com/comment/118358761
has text: @mins The value is since the question asked for "extracting 15 frames", and the answer I'm extending almost reaches that goal, my answer takes it all the way.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51552641
score: 1

http://stackoverflow.com/comment/90124402
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51579514
type: Comment
has text: @IonicSolutions I know that, but I suggested this as an alternative, as other answers said that this is a more general method.

http://stackoverflow.com/a/51559000
downvote count: 0
type: Answer
has body: You could count the perfect squares with a collections.Counter(), and retrieve the tuples that have atleast 2 perfect squares: from math import sqrt from collections import Counter b = [(1, 2, 9), (1, 2, 9), (1, 3, 8), (1, 4, 7), (1, 5, 6), (2, 3, 7), (2, 4, 6), (3, 4, 5)] def perfect_square(n): return round(sqrt(n)) ** 2 == n counts = Counter() for i, tup in enumerate(b): for number in tup: if perfect_square(number): counts[i, tup] += 1 print([k for (_, k), v in counts.items() if v &gt;= 2]) Which Outputs: [(1, 2, 9), (1, 4, 7)] Note: The above Counter() can also be written as: counts = Counter((i, tup) for i, tup in enumerate(b) for number in tup if perfect_square(number)) But this becomes hard to read.
has comment: http://stackoverflow.com/comment/90084865
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51558462

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

http://stackoverflow.com/q/51508514
has comment: http://stackoverflow.com/comment/89986036
type: Question
has comment: http://stackoverflow.com/comment/89986031
upvote count: 0
has body: There is a list: a= [5,6,8,4] I tried to find index by typing something like this a.index(max(a)),but it didn't work. Instead of printing '3' it printed '0'. Why did it do that, and how do I fix it?
answer count: 1
has comment: http://stackoverflow.com/comment/89986328
accepted answer: http://stackoverflow.com/a/51508755
tagged with: python
has comment: http://stackoverflow.com/comment/89986058
favorite count: 0
has title: How to find index of list's max?
has comment: http://stackoverflow.com/comment/89986346
type: AnsweredQuestion
score: -5
has comment: http://stackoverflow.com/comment/89986061
downvote count: 5
has answer: http://stackoverflow.com/a/51508755

http://stackoverflow.com/a/51601852
type: Answer
has body: What data are you using? If you ingested the default Quandl bundle, that dataset in particular only has daily prices, and does not have minutely prices. You'll need to gather your own minutely data and either write a new bundle or ingest csv files. If you want to use anything that's not US equity daily pricing, you'll need your own data. Source / Disclaimer: I'm a Zipline maintainer.
score: 0
answers question: http://stackoverflow.com/q/51592575

http://stackoverflow.com/a/51629710
type: Answer
upvote count: 1
has body: From the code behind the Jira library it looks like the create_issue method returns an Issue object which contains lots of information. When you try to print it, it prints the first human readable value it can find in the object. Try this instead: response = {'JIRA ID': new_issue.key} return jsonify(response),201 The code for the returned Issue class can be found here beginning on line 404
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51628968
answers question: http://stackoverflow.com/q/51628968

http://stackoverflow.com/a/51568753
upvote count: 1
score: 1
type: AcceptedAnswer
has body: Let's just focus on the x part, ignoring y because it works the same way. def firstmoment(stars, bins): xsum = 0.0 itot = 0.0 for i in range(bins): for j in range(bins): xsum += stars[i][j][0] * stars[i][j][2] itot += stars[i][j][2] x0 = xsum / itot return x0, itot stars is a 3D array indexed as [x, y, luminance]. At the end, itot is the sum of the luminance values, which is trivially stars[:bins,:bins,2].sum(). Using a similar transformation for xsum, we get: def firstmoment(stars, bins): xsum = (stars[:bins,:bins,0] * stars[:bins,:bins,2]).sum() itot = stars[:bins,:bins,2].sum() x0 = xsum / itot return x0, itot
downvote count: 0
answers question: http://stackoverflow.com/q/51568499
has comment: http://stackoverflow.com/comment/90103946
accepted answer of: http://stackoverflow.com/q/51568499
type: Answer

http://stackoverflow.com/comment/90164519
score: 0
type: QuestionComment
has text: Are you using a virtual environment ?
type: Comment
comment on: http://stackoverflow.com/q/51598930

http://stackoverflow.com/a/51600921
has comment: http://stackoverflow.com/comment/90201454
score: 4
has comment: http://stackoverflow.com/comment/90236055
has comment: http://stackoverflow.com/comment/90170259
has comment: http://stackoverflow.com/comment/90201649
answers question: http://stackoverflow.com/q/51600414
type: Answer
accepted answer of: http://stackoverflow.com/q/51600414
upvote count: 4
has comment: http://stackoverflow.com/comment/90198629
has comment: http://stackoverflow.com/comment/90171146
has comment: http://stackoverflow.com/comment/90201089
downvote count: 0
has comment: http://stackoverflow.com/comment/90182902
has comment: http://stackoverflow.com/comment/90223940
has body: I am not quite sure I completely understand your code in lieu of an MCVE but I think there is a bit of a misunderstanding here. In this piece of code you take a row and a DataFrame and append one row to that DataFrame. #Function to applied row wise down the dataframe. Takes a column (post) and new empty df. def func(post,New_DF): post = str(post) scores = OtherFUNC.countWords(post) scores['post'] = post New_DF = New_DF.append(scores, ignore_index=True) return(New_DF) Instead of appending to New_DF, I would recommend just returning a pd.Series which df.apply concatenates into a DataFrame. That is because if you are appending to the same New_DF object in all nCores partitions, you are bound to run into trouble. #Function to applied row wise down the dataframe. Takes a row and returns a row. def tobsecret_func(row): post = str(row.post) scores = OtherFUNC.countWords(post) scores['post'] = post length_adjusted_series = pd.Series(scores).reindex(range(55)) return(length_adjusted_series) Your error also suggests that as you wrote in your question, your function creates a variable number of values. If the pd.Series you return doesn't have the same shape and column names, then df.apply will fail to concatenate them into a pd.DataFrame. Therefore make sure you return a pd.Series of equal shape each time. This question shows you how to create pd.Series of equal length and index: Pandas: pad series on top or bottom I don't know what kind of dict your OtherFUNC.countWords returns exactly, so you may want to adjust the line: length_adjusted_series = pd.Series(scores).reindex(range(55)) As is, the line would return a Series with an index 0, 1, 2, ..., 54 and up to 55 values (if the dict originally had less than 55 keys, the remaining cells will contain NaN values). This means after applied to a DataFrame, the columns of that DataFrame would be named 0, 1, 2, ..., 54. Now you take your dataset and map your function to each partition and in each partition you apply it to the DataFr…
type: AcceptedAnswer

http://stackoverflow.com/a/59999387
answers question: http://stackoverflow.com/q/51489746
downvote count: 0
score: 26
has body: in case someone did not see the answer, its in the comment: from selenium.webdriver.remote.webelement import WebElement i'm adding this answer to close this question, thanks for the help
type: AcceptedAnswer
upvote count: 26
type: Answer
accepted answer of: http://stackoverflow.com/q/51489746

python-3.x
tags question: http://stackoverflow.com/q/51572829
tags question: http://stackoverflow.com/q/51630114
tags question: http://stackoverflow.com/q/51495560
tags question: http://stackoverflow.com/q/51503591
tags question: http://stackoverflow.com/q/51590045
tags question: http://stackoverflow.com/q/51552554
tags question: http://stackoverflow.com/q/51528009
tags question: http://stackoverflow.com/q/51600336
tags question: http://stackoverflow.com/q/51567177
tags question: http://stackoverflow.com/q/51604181
tags question: http://stackoverflow.com/q/51606837
tags question: http://stackoverflow.com/q/51589060
tags question: http://stackoverflow.com/q/51504268
tags question: http://stackoverflow.com/q/51583255
tags question: http://stackoverflow.com/q/51515176
tags question: http://stackoverflow.com/q/51607931
tags question: http://stackoverflow.com/q/51572131
tags question: http://stackoverflow.com/q/51491502
tags question: http://stackoverflow.com/q/51585383
tags question: http://stackoverflow.com/q/51550056
tags question: http://stackoverflow.com/q/51543359
tags question: http://stackoverflow.com/q/51631105
tags question: http://stackoverflow.com/q/51611458
tags question: http://stackoverflow.com/q/51542630
tags question: http://stackoverflow.com/q/51536757
tags question: http://stackoverflow.com/q/51513386
tags question: http://stackoverflow.com/q/51574392
tags question: http://stackoverflow.com/q/51623051
tags question: http://stackoverflow.com/q/51627218
tags question: http://stackoverflow.com/q/51524421
tags question: http://stackoverflow.com/q/51541053
tags question: http://stackoverflow.com/q/51526263
tags question: http://stackoverflow.com/q/51558745
tags question: http://stackoverflow.com/q/51601454
tags question: http://stackoverflow.com/q/51560435
tags question: http://stackoverflow.com/q/51523468
tags question: http://stackoverflow.com/q/51538489
tags question: http://stackoverflow.com/q/51496685
tags question: http://stackoverflow.com/q/51519532
tags question: http://stackoverflow.com/q/51512621
tags question: http://stackoverflow.com/q/51606283
tags question: http://stackoverflow.com/q/51527805
tags question: http://stackoverflow.com/q/51576511
tags question: http://stackoverflow.com/q/51505187
tags question: http://stackoverflow.com/q/51558462
tags question: http://stackoverflow.com/q/51596338
tags question: http://stackoverflow.com/q/51522174
tags question: http://stackoverflow.com/q/51601286
tags question: http://stackoverflow.com/q/51591776
tags question: http://stackoverflow.com/q/51573795
tags question: http://stackoverflow.com/q/51590677
tags question: http://stackoverflow.com/q/51559830
tags question: http://stackoverflow.com/q/51617405
tags question: http://stackoverflow.com/q/51587347
tags question: http://stackoverflow.com/q/51605920
tags question: http://stackoverflow.com/q/51493185
tags question: http://stackoverflow.com/q/51546170
tags question: http://stackoverflow.com/q/51484682
tags question: http://stackoverflow.com/q/51515491
tags question: http://stackoverflow.com/q/51560490
tags question: http://stackoverflow.com/q/51634679
tags question: http://stackoverflow.com/q/51633153
tags question: http://stackoverflow.com/q/51575883
tags question: http://stackoverflow.com/q/51567059
tags question: http://stackoverflow.com/q/51523720
tags question: http://stackoverflow.com/q/51604302
tags question: http://stackoverflow.com/q/51555862
tags question: http://stackoverflow.com/q/51546855
tags question: http://stackoverflow.com/q/51499366
tags question: http://stackoverflow.com/q/51512907
tags question: http://stackoverflow.com/q/51571242
tags question: http://stackoverflow.com/q/51541895
tags question: http://stackoverflow.com/q/51595372
tags question: http://stackoverflow.com/q/51599746
tags question: http://stackoverflow.com/q/51592584
tags question: http://stackoverflow.com/q/51598340
tags question: http://stackoverflow.com/q/51514609
tags question: http://stackoverflow.com/q/51584171
tags question: http://stackoverflow.com/q/51574640
tags question: http://stackoverflow.com/q/51580869

http://stackoverflow.com/q/51544451
has answer: http://stackoverflow.com/a/51544829
accepted answer: http://stackoverflow.com/a/51544829
type: AnsweredQuestion
type: Question
has body: I want to fill the missing values in col 2 to corresponding col1. import pandas as pd data={"col1":["A","B","C","A","B","C","A","B","A"], "col2":["{hey1}"," ","{hello2}","{hey2}","{he1}","{hello3}","set()","set()","{hey1}"]} df=pd.DataFrame(data=data) It should fill it with some rules, given below: for example, if A is occuring four times and out of 4, it has corresponding col2 value for three times and fourth one is missing, so missing value should be a combination of all three. Like in this case 3 values are hey1, hey2, hey1. Fourth missing should contain hey2, hey1. Set() is the garbage value, I dont want that value. So, I want to remove it, before dealing with column comparison. Desired output: col1 col2 A hey1 B he1 C hello2 A hey2 B he1 C hello3 A hey1,hey2 B he1 A hey1
tagged with: string
tagged with: multiple-columns
has title: How to fill missing value based on column comparison Python
score: 0
answer count: 1
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/90134040
comment on: http://stackoverflow.com/q/51584100
score: 0
type: Comment
type: QuestionComment
has text: If my solution resolved your issue mark it as correct

http://stackoverflow.com/a/51527365
upvote count: 25
has comment: http://stackoverflow.com/comment/108445631
answers question: http://stackoverflow.com/q/51527364
has body: Well, there should be await in front of asyncio.wait :) done, pending = await asyncio.wait( [a, b], return_when=asyncio.FIRST_COMPLETED)
accepted answer of: http://stackoverflow.com/q/51527364
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/108446359
score: 25
has comment: http://stackoverflow.com/comment/108427526

http://stackoverflow.com/comment/90201258
has text: Would running 2to3 on the file fix it? It seems like a simple case that should be handled by that
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51616995

http://stackoverflow.com/q/51613439
tagged with: concurrent.futures
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion
type: Question
has body: I am currently trying to develop a fast webscraping function so I can scrape a large list of files. This is the code I have currently: import time import requests from bs4 import BeautifulSoup from concurrent.futures import ProcessPoolExecutor, as_completed def parse(url): r = requests.get(url) soup = BeautifulSoup(r.content, 'lxml') return soup.find_all('a') with ProcessPoolExecutor(max_workers=4) as executor: start = time.time() futures = [ executor.submit(parse, url) for url in URLs ] results = [] for result in as_completed(futures): results.append(result) end = time.time() print("Time Taken: {:.6f}s".format(end-start)) this brings backs results for websites i.e www.google.com, however my problem is I have no idea to view the data it brings back I only get future objects. Please can someone explain/show me how to do this. I appreciate anytime you give to help me with this.
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/51614479
accepted answer: http://stackoverflow.com/a/51614479
has title: Concurrent futures webscraping

http://stackoverflow.com/a/51543222
type: Answer
has body: Managed to do it with some steps with a different mindset: Created 2 lists, each with i's own parameters Used NumPy's append so that for each row a different random number lognormal_tone = [] lognormal_ttwo = [] for i in range(len(s)): lognormal_tone.append(stats.lognorm(0.5, scale=np.exp(1.8)).ppf(random.random()).astype(int)) lognormal_ttwo.append(stats.lognorm(0.4, scale=np.exp(2.7)).ppf(random.random()).astype(int)) Then, included them in the DataFrame with another previously created list: df = pd.DataFrame({'arrival':arrival,'minTypeOne':lognormal_tone, 'minTypeTwo':lognormal_two})
answers question: http://stackoverflow.com/q/51528272
accepted answer of: http://stackoverflow.com/q/51528272
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/90321013
comment on: http://stackoverflow.com/a/51621323
type: Comment
has text: Excellent. Now I just need to find out why the values are offset to the left one column over. e.g. 0.0.0.0 is showing under Result, and 2018-08-20T12:00:00.000Z is showing up under IP.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51597896
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51597842
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51597842
has comment: http://stackoverflow.com/comment/90162811
upvote count: 2
has comment: http://stackoverflow.com/comment/90162531
has body: Simply force the missing to NaN (either by explicit replacement or by forcing to numeric dtype), and then use cut as you had: df['TotalChargesCategories'] = pd.cut(pd.to_numeric(df['TotalCharges'], errors='coerce'),10) &gt;&gt;&gt; df TotalCharges Churn TotalChargesCategories 0 29.85 No (21.985, 816.38] 1 1889.5 No (1602.91, 2389.44] 2 108.15 Yes (21.985, 816.38] 3 1840.75 No (1602.91, 2389.44] 4 151.65 Yes (21.985, 816.38] 5 820.5 Yes (816.38, 1602.91] 6 1949.4 No (1602.91, 2389.44] 7 301.9 No (21.985, 816.38] 8 3046.05 Yes (2389.44, 3175.97] 9 3487.95 No (3175.97, 3962.5] 10 587.45 No (21.985, 816.38] 11 326.8 No (21.985, 816.38] 12 5681.1 No (5535.56, 6322.09] 13 5036.3 Yes (4749.03, 5535.56] 14 2686.05 No (2389.44, 3175.97] 15 7895.15 No (7108.62, 7895.15] 16 missing No NaN 17 7382.25 No (7108.62, 7895.15] 18 528.35 Yes (21.985, 816.38]
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90162855

http://stackoverflow.com/comment/90055664
type: QuestionComment
score: 2
has text: It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on his own. A good way to show this effort is to include a [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve). Check the [intro tour](https://stackoverflow.com/tour) you finished before posting, especially [How to Ask](http://stackoverflow.com/help/how-to-ask).
comment on: http://stackoverflow.com/q/51543865
type: Comment

http://stackoverflow.com/comment/90257400
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51636383
has text: How have you installed the scikit-learn? Have you cloned the repo from github and making changes in that? Or you installed in editable mode?

http://stackoverflow.com/q/51594877
has answer: http://stackoverflow.com/a/51594930
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90155638
downvote count: 3
has comment: http://stackoverflow.com/comment/90155511
has comment: http://stackoverflow.com/comment/90155588
type: Question
has comment: http://stackoverflow.com/comment/90156650
has title: Why am I having an invalid Syntax?
tagged with: penetration-testing
accepted answer: http://stackoverflow.com/a/51594930
has comment: http://stackoverflow.com/comment/90155639
tagged with: python-2.7
answer count: 2
upvote count: 0
has body: Why am I having an invalid Syntax? Please be patient with me if it's just because of a stupid mistake. import os gateway = raw_input("What is your gateway IP: ") target = raw_input("What is your target IP: ") interface = raw_input("What is your network interface: ") os.system('arpspoof -i {0} -t {1} {2} 2&gt;/dev/null 1&gt;/dev/null &amp;'.format(interface, gateway, target)) os.system('arpspoof -i {0} -t {1} {2} 2&gt;/dev/null 1&gt;/dev/null &amp;'.format(interface, target, gateway)) while True: try: stop_command = raw_input("If you want to exit type stop: ") if stop_command != "stop": print("You didn't type stop") continue else: break
has answer: http://stackoverflow.com/a/51595400
favorite count: 0
possible better answer: http://stackoverflow.com/a/51595400
score: -3
tagged with: python

http://stackoverflow.com/a/51525125
downvote count: 0
has body: Use pandas.Series.str.extract and then drop null rows: df.assign(A=df.A.str.extract(r'[a-z]{2}\_(\d+)\_[a-z]')).dropna() A B 0 1 9 1 2 2 3 4 5 You may need to change the regular expression, here is an explanation of the one I chose: [a-z]{2} # matches two lowercase characters a-z \_ # matches an underscore (\d+) # matches one or more digits \_ # matches an underscore [a-z] # matches a single character a-z Here is an intermediate visualization of the series after using str.extract: df.A.str.extract(r'[a-z]{2}\_(\d+)\_[a-z]') 0 0 1 1 2 2 NaN 3 4 Any rows where a match is not found result in NaN, which we then drop in the final step.
has comment: http://stackoverflow.com/comment/90019808
type: Answer
accepted answer of: http://stackoverflow.com/q/51525031
has comment: http://stackoverflow.com/comment/90020101
has comment: http://stackoverflow.com/comment/90019272
has comment: http://stackoverflow.com/comment/90019609
answers question: http://stackoverflow.com/q/51525031
has comment: http://stackoverflow.com/comment/90019596
has comment: http://stackoverflow.com/comment/90020043
has comment: http://stackoverflow.com/comment/90019658
upvote count: 5
has comment: http://stackoverflow.com/comment/90019464
has comment: http://stackoverflow.com/comment/90019308
score: 5
type: AcceptedAnswer

http://stackoverflow.com/comment/89979689
comment on: http://stackoverflow.com/q/51505334
has text: I wouldn't do this all the time, but I've seen things like this done sometimes in `__init__.py` or a `config.py` file.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51536159
has body: I have a dataframe with multiple columns and I would like to replace cells with 0 with the previous value in the column, in one shot. It works with df['A'].replace(to_replace=0, method='ffill') but as soon as it's the all dataframe it throws an error, probably because to_replace is not a series. How can I do that ? import datetime import pandas as pd import numpy as np todays_date = datetime.datetime.now().date() index = pd.date_range(todays_date-datetime.timedelta(10), periods=4, freq='D') columns = ['A','B', 'C'] data = np.array([[1, 2, 2], [3, 0, 5], [0, 4, 0], [3, 4, 5]]) df = pd.DataFrame(data, index=index, columns=columns) df Out[333]: A B C 2018-07-16 1 2 2 2018-07-17 3 0 5 2018-07-18 0 4 0 2018-07-19 3 4 5 # Throws an error here : df.replace(to_replace=0, method='ffill') TypeError: cannot replace [0] with method ffill on a DataFrame # Works column by column : df['A'].replace(to_replace=0, method='ffill') Out[338]: 2018-07-16 1 2018-07-17 3 2018-07-18 3 2018-07-19 3 Freq: D, Name: A, dtype: int64
tagged with: pandas
has answer: http://stackoverflow.com/a/51536246
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51536246
type: Question
has title: How to replace cells in a Pandas dataframe with multiple columns?
tagged with: dataframe
upvote count: 4
tagged with: numpy
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51536279
score: 4
has answer: http://stackoverflow.com/a/51536279
favorite count: 0

heroku
tags question: http://stackoverflow.com/q/51603888
tags question: http://stackoverflow.com/q/51507757
tags question: http://stackoverflow.com/q/51519333
tags question: http://stackoverflow.com/q/51488600
tags question: http://stackoverflow.com/q/51567483
tags question: http://stackoverflow.com/q/51620153
tags question: http://stackoverflow.com/q/51585303
tags question: http://stackoverflow.com/q/51509121
type: Tag
tags question: http://stackoverflow.com/q/51548871
tag name: heroku

http://stackoverflow.com/comment/90217395
type: AnswerComment
type: Comment
has text: @NaseerMohammad I see. Are you looking for just the common file names? My code assumes that you're looking for common path names as well.
score: 0
comment on: http://stackoverflow.com/a/51625515

http://stackoverflow.com/comment/90027359
has text: Also realized I threw the label in the wrong spot. The top code set is what was the updated code. Originally, I was not calling it but in the updated code I was with `for file in os.listdir(folderPath)`. Thoughts on why that might not work?
type: Comment
comment on: http://stackoverflow.com/a/51529275
type: AnswerComment
score: 0

http://stackoverflow.com/comment/114067054
type: AnswerComment
score: 0
type: Comment
has text: This was exactly my issue. Thank you! I noticed I was able to convert my timestamp via one of the online converters, but kept getting a 1970s date with Pandas. I assumed all unix timestamps were in the same format. Learned something new!
comment on: http://stackoverflow.com/a/54914293

http://stackoverflow.com/q/51623806
tagged with: google-cloud-datastore
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/50729803
has comment: http://stackoverflow.com/comment/90213195
has comment: http://stackoverflow.com/comment/90213249
has answer: http://stackoverflow.com/a/51795844
tagged with: python
has comment: http://stackoverflow.com/comment/90213370
has comment: http://stackoverflow.com/comment/90392457
type: AnsweredQuestion
downvote count: 0
has title: Can no longer install `google-cloud-datastore` dependency for Google Cloud Dataflow jobs in requirements.txt file
type: Question
has body: Something similar to this last post happened again: Google Python cloud-dataflow instances broke without new deployment (failed pubsub import) Essentially, overnight, all of our cloud dataflow jobs broke for seemingly no reason. There were no new deployments, there were no SDK updates, nothin, our team simply awoke to StackDriver notifications saying that our mapping jobs failed overnight. This is the stack trace that the jobs are failing with Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 609, in do_work work_executor.execute() File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/executor.py", line 167, in execute op.start() File "apache_beam/runners/worker/operations.py", line 340, in apache_beam.runners.worker.operations.DoOperation.start def start(self): File "apache_beam/runners/worker/operations.py", line 341, in apache_beam.runners.worker.operations.DoOperation.start with self.scoped_start_state: File "apache_beam/runners/worker/operations.py", line 346, in apache_beam.runners.worker.operations.DoOperation.start pickler.loads(self.spec.serialized_fn)) File "/usr/local/lib/python2.7/dist-packages/apache_beam/internal/pickler.py", line 225, in loads return dill.loads(s) File "/usr/local/lib/python2.7/dist-packages/dill/dill.py", line 277, in loads return load(file) File "/usr/local/lib/python2.7/dist-packages/dill/dill.py", line 266, in load obj = pik.load() File "/usr/lib/python2.7/pickle.py", line 864, in load dispatch[key](self) File "/usr/lib/python2.7/pickle.py", line 1096, in load_global klass = self.find_class(module, name) File "/usr/local/lib/python2.7/dist-packages/dill/dill.py", line 423, in find_class return StockUnpickler.find_class(self, module, name) File "/usr/lib/python2.7/pickle.py", line 1130, in find_class __import__(module) File "/usr/local/lib/python2.7/dist-packages/dataflow_pipeline/invoice_overages.py", line 26, in &lt;module&gt; from google.cloud.datastore.h…
has comment: http://stackoverflow.com/comment/90214013
score: 3
tagged with: google-cloud-dataflow
has comment: http://stackoverflow.com/comment/90371673
upvote count: 3
tagged with: python-import
accepted answer: http://stackoverflow.com/a/51795844
tagged with: google-cloud-platform

http://stackoverflow.com/comment/90187751
type: Comment
score: 0
has text: @Aspect: a = ["x" * n] becomes ['xxxxx'] which is a single element array, but you are trying to iterate till 5th element, hence you are getting out of bounds exception
type: QuestionComment
comment on: http://stackoverflow.com/q/51611358

http://stackoverflow.com/comment/90164956
type: Comment
comment on: http://stackoverflow.com/q/51599428
has text: We can't run your code without `mylist`.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89984817
has text: You could add your custom code to the extract function. But I do understand that going to Pandas is a much larger step. For your case the other answer is easier and more appropriate.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51507649
type: AnswerComment

http://stackoverflow.com/a/51549750
type: Answer
answers question: http://stackoverflow.com/q/51544433
has comment: http://stackoverflow.com/comment/99302371
downvote count: 2
has comment: http://stackoverflow.com/comment/119912391
accepted answer of: http://stackoverflow.com/q/51544433
score: 2
has comment: http://stackoverflow.com/comment/94447865
has body: Just set the Name at runtime like: docker run --name MYCOOLCONTAINER alpine:latest Then: bashCommandName = `echo $NAME` output = subprocess.check_output(['bash','-c', bashCommandName]) print output
has comment: http://stackoverflow.com/comment/100087655
upvote count: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/99857546

http://stackoverflow.com/a/51522834
has comment: http://stackoverflow.com/comment/90075908
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90014981
has comment: http://stackoverflow.com/comment/90040197
upvote count: 2
answers question: http://stackoverflow.com/q/51522433
has comment: http://stackoverflow.com/comment/90015715
has body: Firstly, check out this page: https://biopython.org/wiki/Download You don't have to worry about biopython being bound to a specific version of python - you can use it with either v2.7 or v3.4/v3.5/v3.6. You can also have multiple version installed on your system but I recommend you to focus on digging deeper into one of them. Personally, I work now for several years with python3.x (at the moment 3.6) but I know a lot of people sticking to v2.7. Having also a bioinformatics background, one thing that I can highly recommend you at the beginning of your journey is taking a course such as: https://www.coursera.org/specializations/python There is also a bunch of free tutorials on youtube - you will easily find one that fits your needs by searching for "python tutorial" or "python getting started". Get yourself comfortable with the language, check out the basics such as data structures, databases, and data visualization. Check also some "python cheat sheets" - they can help you pick up the basic concepts of the language. All the best and keep on coding!
has comment: http://stackoverflow.com/comment/90014749
downvote count: 0

http://stackoverflow.com/comment/94210443
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51552422
has text: Possible duplicate of ['readline/readline.h' file not found](https://stackoverflow.com/questions/23085076/readline-readline-h-file-not-found)

http://stackoverflow.com/q/51596148
has comment: http://stackoverflow.com/comment/90158164
has answer: http://stackoverflow.com/a/51596477
has comment: http://stackoverflow.com/comment/90158187
has title: Sort a value in python list of dict
has comment: http://stackoverflow.com/comment/90158362
type: Question
has comment: http://stackoverflow.com/comment/90158195
has answer: http://stackoverflow.com/a/51596268
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51596403
accepted answer: http://stackoverflow.com/a/51596403
tagged with: python
has body: I am looking to sort a list of dictionary based on a key which is in the format \d+:\d+ The list of dictionary should have the expected key(age) lst = [ [{'id': 'SOMEDATA_31_30', 'age': '31:30', 'values':0, 'hasdata': False, 'name': u'SOMEDATA'}] [{'id': 'SOMEDATA1_32_29', 'age': '32:29', 'values':1, 'hasdata': False, 'name': u'SOMEDATA1'}] [{'id': 'SOMEDATA2_22_20', 'age': '22:20', 'values':3, 'hasdata': False, 'name': u'SOMEDATA2'},{'id': 'SOMEDATA2_28_27', 'age': '28:27', 'values':4, 'hasdata': False, 'name': u'SOMEDATA2'}] ] So when I pass the whole(lst) to compare(function?!) then it should give me a list of dict ordered in desc order based on the age. lst = [ {'id': 'SOMEDATA1_32_29', 'age': '32:29', 'values':1, 'hasdata': False, 'name': u'SOMEDATA1'} {'id': 'SOMEDATA_31_30', 'age': '31:30', 'values':0, 'hasdata': False, 'name': u'SOMEDATA'} {'id': 'SOMEDATA2_28_27', 'age': '28:27', 'values':4, 'hasdata': False, 'name': u'SOMEDATA2'} {'id': 'SOMEDATA2_22_20', 'age': '22:20', 'values':3, 'hasdata': False, 'name': u'SOMEDATA2'} ] How should we do this ? Thanks for your time.
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51596268

http://stackoverflow.com/comment/90208755
type: Comment
score: 0
has text: ...something like `rpm -Qa | xargs -d $'\n' -P 4 rpm -V` if you have 4 CPUs, f/e. (Not tested; I don't have any RPM-based distro handy).
type: QuestionComment
comment on: http://stackoverflow.com/q/51621281

http://stackoverflow.com/q/51597936
has answer: http://stackoverflow.com/a/51598001
score: -2
has comment: http://stackoverflow.com/comment/90162037
has comment: http://stackoverflow.com/comment/90161924
type: Question
downvote count: 2
answer count: 1
has title: python 3 TypeError: 'int' object is not callable
favorite count: 0
tagged with: python-2.7
tagged with: python-3.x
upvote count: 0
has body: can u tell me what's wrong with this code? a=int(input()) for i in range(a): lst=list(map(int,input().split(" "))) ans=lst[1] for j in range(lst[0]): ans=(ans(ans+1))/2 print(ans) And in output it shows- line 6, in &lt;module&gt; TypeError: 'int' object is not callable
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51524874
has title: accessing Kafka metadata with Python KafkaConsumer
has body: I have a simple Kafka reader class. I really don't remember where I got this code. Could have found it, or my previous self may have created it from various examples. Either way, it allows me to quickly read a kafka topic. class KafkaStreamReader(): def __init__(self, schema_name, topic, server_list): self.schema = get_schema(schema_name) self.topic = topic self.server_list = server_list self.consumer = KafkaConsumer(topic, bootstrap_servers=server_list, auto_offset_reset = 'latest', security_protocol="PLAINTEXT") def decode(self, msg, schema): parsed_schema = avro.schema.parse(schema) bytes_reader = io.BytesIO(msg) decoder = avro.io.BinaryDecoder(bytes_reader) reader = avro.io.DatumReader(parsed_schema) record = reader.read(decoder) return record def fetch_msg(self): event = next(self.consumer).value record = self.decode(event, self.schema) return record To use it, I instantiate an object and loop forever reading data such as this: consumer = KafkaStreamReader(schema, topic, server_list) while True: message = consumer.fetch_msg() print message I'm sure there are better solutions, but this works for me. What I want to get out of this, is the meta data on the Kafka record. A coworker in another group used Java or Node and was able to see the following information on the record. { topic: 'clickstream-v2.origin.test', value: { schema:payload_data/jsonschema/1-0-3', data: [ [Object] ] }, offset: 16, partition: 0, highWaterOffset: 17, key: null, timestamp: 2018-07-25T17:01:36.959Z } } I want to access the timestamp field using the Python KafkaConsumer.
tagged with: metadata
type: Question
has answer: http://stackoverflow.com/a/51525076
tagged with: kafka-consumer-api
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51596851
tagged with: python-2.7
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90159832
has body: I have a DataFrame that I split into column Series (col_series in the snippet below)and use apply tests to each value in each Series. But I would like to report which row in the Series is affected when I detect and error. ... col_series.apply(self.testdatelimits, args= \ (datetime.strptime('2018-01-01', '%Y-%m-%d'), key)) def testlimits(self, row_id, x, lowerlimit, col_name): low_error = None d = float(x) if lowerlimit != 'NA' and d &lt; float(lowerlimit): low_error = 'Following record has column ' + col_name + ' lower than range check' if low_error is not None: self.set_error(col_index, row_id, low_error) Of course the above fails because x is a str and does not have the name property. I am thinking that maybe I can pass in the row index in the Series, but am not clear on how to do that? Edit: I switched to use a list comprehension to solve this issue rather than ps apply. It is significantly faster too col_series = col_series.apply(pd.to_datetime, errors='ignore') dfwithrow = pd.DataFrame(col_series) dfwithrow.insert(0, 'rowid', range(0, len(dfwithrow))) dfwithrow['lowerlimit'] = lowlimit dfwithrow['colname'] = 'fred' list(map(self.testdatelimits, dfwithrow['rowid'], dfwithrow[colvalue[0]], \ dfwithrow['lowerlimit'], dfwithrow['colname']))
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90820994
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/16476924
has comment: http://stackoverflow.com/comment/90159892
has title: How to get the row index for pandas apply function on a Series
type: Question

http://stackoverflow.com/comment/106803829
score: 0
type: AnswerComment
has text: it says unknown option to the stack name
type: Comment
comment on: http://stackoverflow.com/a/53677928

http://stackoverflow.com/q/51638418
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51638539
possible better answer: http://stackoverflow.com/a/51638511
type: Question
has answer: http://stackoverflow.com/a/51638511
has title: How to put a variable in text file?
answer count: 2
accepted answer: http://stackoverflow.com/a/51638539
has body: So i'm trying to insert a variable inside a text file and i've defined them as shown below: for filename in os.listdir("/home/gyanender/Desktop/s1d_gyanender"): if filename.endswith("_s1d_A.fits"): df = pd.DataFrame.from_dict(SN_dic,orient='index') df = df.mean() out_name = s1d_header['OBJECT'] +'-' + s1d_header['DATE-OBS'] +'.ares' mine_opt = '/home/gyanender/bin/ARES/mine.opt' file_opt=open(mine_opt,'w') file_opt.writelines(("specfits=filename","\n","fileout=out_name","\n","rejt=df")) file_opt.close() So in the end what i got is something like this, i got name of the variables in the text but what i want is the values of those variables in my text file as i've to give that file as an input to another code. specfits='filename' fileout='out_name' rejt=df As filename = HARPS.2016-04-01T09:44:43.034_s1d_A.fits out_name = Moon-2016-04-01T09:44:43.034.ares rejt = 166.6 (As the values of df is 166.6) So my ideal file should look like something like this: specfits='HARPS.2016-04-01T09:44:43.034_s1d_A.fits' fileout='Moon-2016-04-01T09:44:43.034.ares' rejt= 166.6 So can someone tell me where i'm making the mistake?

http://stackoverflow.com/comment/90208146
type: QuestionComment
has text: Please fix your formatting and indentation
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51621278

http://stackoverflow.com/q/51568156
has body: I have a list x=['b1','00','00','10','10','F5','D1','01','01'...] # sample data I am trying to remove duplicates of '10' only when they are adjacent. Till now I have tried my_list= [x[i] for i in range(len(x)) if (i==0) or ( x[i] !=x[i-1])] # current implementation This removes all adjacent duplicates but I want to keep '00','00' and '01' and just remove duplicates of '10' How do I achieve this using a list comprehension?
has comment: http://stackoverflow.com/comment/90102688
tagged with: python
has comment: http://stackoverflow.com/comment/90105892
has answer: http://stackoverflow.com/a/51568519
accepted answer: http://stackoverflow.com/a/51568519
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/90102672
has comment: http://stackoverflow.com/comment/90102611
has comment: http://stackoverflow.com/comment/90103217
type: Question
tagged with: duplicates
has comment: http://stackoverflow.com/comment/90102736
tagged with: python-2.7
score: 0
has title: Python remove specific adjacent duplicates from list
answer count: 1

http://stackoverflow.com/a/51638749
answers question: http://stackoverflow.com/q/51636461
has comment: http://stackoverflow.com/comment/90242371
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90270735
has body: Actually, passlib is a separate library. It should not be in flask. Try installing it: pip install passlib

http://stackoverflow.com/comment/90020969
has text: `TypeError: Object of type odict_items is not JSON serializable` ? `json.dumps(list(price_dict.items()))`?
comment on: http://stackoverflow.com/a/51526127
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90172928
has text: When I enter that it automatically became `http://localhost:8000/question6/test-question/?no_rep=1` with the `/`, but it didn't work either.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51603430

http://stackoverflow.com/q/51496523
answer count: 1
has body: i have a code to run a timer thread and its doing a job every x seconds and its has no problem import threading import datetime def starThread(): t = threading.Timer(0, Do_Analysis()) t.start() def Do_Analysis(): #define threading.Timer to do the job every x secound t=threading.Timer(1, Do_Analysis).start() print('datetime is : ',datetime.datetime.now()) print(threading.active_count) starThread() i need to terminate the thread at some point and i dont know how to do it can anyone please guide me
tagged with: multithreading
has title: how to terminate a timer thread in python
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51496853
score: 0
has comment: http://stackoverflow.com/comment/89961410
has answer: http://stackoverflow.com/a/51496853

http://stackoverflow.com/comment/89959878
comment on: http://stackoverflow.com/q/51495609
type: Comment
type: QuestionComment
has text: You need to handle static HTML code source. Selenium is not much suitable for this purpose
score: 0

http://stackoverflow.com/comment/90187033
type: Comment
type: QuestionComment
has text: @Tom Zych That helped with modifications. Thanks. :)
score: 0
comment on: http://stackoverflow.com/q/51602145

http://stackoverflow.com/comment/90075191
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51553928
has text: @zindarod Please don't answer in comments.
score: 2

http://stackoverflow.com/comment/90186922
comment on: http://stackoverflow.com/q/51610206
score: 0
has text: @WillemVanOnsem That was an intended error. :)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90144977
comment on: http://stackoverflow.com/q/51577966
type: QuestionComment
type: Comment
has text: More information would help here. How do you call the task, is celery logging anything interesting. Your example is not complete (i.e. imports are missing) so if I wanted to run it here I am not able to reproduce your problem.
score: 0

http://stackoverflow.com/comment/89968746
has text: `print(response)` throws out `{u'Images': [], 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': '1bc6cc41-d4d8-45f1-b176-24ac13ab90ff', 'HTTPHeaders': {'date': 'Tue, 24 Jul 2018 13:45:14 GMT', 'content-length': '219', 'content-type': 'text/xml;charset=UTF-8', 'server': 'AmazonEC2'}}}`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51497324

http://stackoverflow.com/comment/90026788
comment on: http://stackoverflow.com/q/51529158
type: Comment
type: QuestionComment
has text: I downloaded the Build Tools again and I ran the same commands from Visual Studio Developer Command Prompt and recieved this error: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'x86', but I am sure I downloaded the right Visual Studio (x64) for my 64-bit computer.
score: 0

http://stackoverflow.com/comment/90060303
comment on: http://stackoverflow.com/q/51546235
score: 0
type: Comment
type: QuestionComment
has text: Your "desired output" is a one line dataframe that doesn't explain what you want to do with the NaNs...I don't get why this is so confusing for you

http://stackoverflow.com/comment/90131978
has text: What version of django are you using?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51583300

http://stackoverflow.com/comment/90154489
score: 0
type: QuestionComment
type: Comment
has text: Possible duplicate of [Search for String in all Pandas DataFrame columns and filter](https://stackoverflow.com/questions/26640129/search-for-string-in-all-pandas-dataframe-columns-and-filter)
comment on: http://stackoverflow.com/q/51594169

http://stackoverflow.com/q/51611735
tagged with: pool
answer count: 2
has answer: http://stackoverflow.com/a/51612823
has comment: http://stackoverflow.com/comment/90190788
has answer: http://stackoverflow.com/a/51612363
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/90189121
score: 0
type: Question
has title: ThreadPool and Pool for parallel processing
has body: Is there a way to use both ThreadPool and Pool in python to parallelise a loop by specifying the number of CPUs and cores you wish to use? For example I would have a loop execute as: from multiprocessing.dummy import Pool as ThreadPool from tqdm import tqdm import numpy as np def my_function(x): return x + 1 pool = ThreadPool(4) my_array = np.arange(0,1e6,1) results = list(tqdm(pool.imap(my_function, my_array),total=len(my_array))) For 4 cores but it I wanted to spread these out on multiple CPUs as well, is there a simple way to adapt the code?

http://stackoverflow.com/q/51512733
tagged with: python
has answer: http://stackoverflow.com/a/51512850
type: AnsweredQuestion
has body: I need help to do the combination of nested loop output from two iteration. This is my nested while code: iteration=0 while (iteration &lt; 2): count = 0 bit=5 numbers = [] while (count &lt; bit): Zero = 0 One = 1 IV=(random.choice([Zero, One])) numbers.append(IV) count= count + 1 print ('List of bit:', numbers) iteration=iteration + 1 print ("End of iteration",iteration) And this is the result: List of bit: [1, 0, 1, 1, 0] End of iteration 1 List of bit: [1, 0, 0, 1, 1] End of iteration 2 However, I would like to combine the result of the loop. Supposedly, the result may produce something like this: Combination of bit:[1, 0, 1, 1, 0 ,1 , 0, 0, 1, 1] Hopefully someone may help me to do this. Thank you so much.
has title: How to combine the result of nested loop in Python
has answer: http://stackoverflow.com/a/51512952
has answer: http://stackoverflow.com/a/51512848
type: Question
possible better answer: http://stackoverflow.com/a/51512839
tagged with: nested-loops
score: 0
has answer: http://stackoverflow.com/a/51513007
accepted answer: http://stackoverflow.com/a/51513007
has answer: http://stackoverflow.com/a/51512839
answer count: 5

http://stackoverflow.com/comment/90078733
has text: Your English is perfectly understandable, don't worry. But don't use English, use copy-paste (of the error trace, diagnostic code and output, etc.). Take a look at some similar questions with upvotes to see how to do it better.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51554414
type: Comment

http://stackoverflow.com/a/51550603
upvote count: 5
type: AcceptedAnswer
downvote count: 0
has body: The solution is to execute Dash in another thread, when executing it in another thread you could have problems, but using this answer you get the following: import sys import threading from PyQt5 import QtWidgets import dash import dash_core_components as dcc import dash_html_components as html def run_dash(data, layout): app = dash.Dash() app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='example-graph', figure={ 'data': data, 'layout': layout }) ]) app.run_server(debug=False) class MainWindow(QtWidgets.QMainWindow): pass if __name__ == '__main__': data = [ {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'}, {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'}, ] layout = { 'title': 'Dash Data Visualization' } threading.Thread(target=run_dash, args=(data, layout), daemon=True).start() app = QtWidgets.QApplication(sys.argv) mainWin = MainWindow() mainWin.show() sys.exit(app.exec_())
type: Answer
accepted answer of: http://stackoverflow.com/q/51522463
answers question: http://stackoverflow.com/q/51522463
score: 5

http://stackoverflow.com/q/51575647
type: Question
tagged with: replace
answer count: 2
has body: I have a strange requirement where I need to manipulate the contents of a list based on certain rules. My list is as below: lst = [ '%s###timestamp', "TRANSLATE(%s, ',', '')###sales", "TRANSLATE(%s, ',', '')###units", "TRANSLATE(%s, ',', '')###counting_units", "TRANSLATE(%s, ',', '')###standard_units"] As per the requirement, every '%s' has to be replaced by 'SPLIT(expld ' and the final result has to be like below: res = [ """SPLIT(expld, "###")[0] AS timestamp""", """TRANSLATE(SPLIT(expld, "###")[1], ',', '') AS sales""", """TRANSLATE(SPLIT(expld, "###")[2], ',', '') AS units""", """TRANSLATE(SPLIT(expld, "###")[3], ',', '') AS counting_units""", """TRANSLATE(SPLIT(expld, "###")[4], ',', '') AS standard_units"""] where [0],[1],[2] and so on represents the index of the list. Why I need to create the 'res' like this because I need this list later to construct a Hive Query. In my attempt so far, I have just been able to replace '%s' value with 'SPLIT(expld ' which was straightforward. splitExpr = [w.replace('%s', 'SPLIT(expld ') for w in lst] I'm still trying to figure out how can I get the desired result in this case.
downvote count: 0
accepted answer: http://stackoverflow.com/a/51575738
has comment: http://stackoverflow.com/comment/90117167
favorite count: 0
has title: Manipulating elements in a Python List
tagged with: python
has comment: http://stackoverflow.com/comment/90117123
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51575836
tagged with: list
has comment: http://stackoverflow.com/comment/90117135
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51575738
possible better answer: http://stackoverflow.com/a/51575836

http://stackoverflow.com/comment/90051389
comment on: http://stackoverflow.com/a/51531178
type: Comment
has text: Thanks for you help. I got it working when I added the os.path.join to all places with the audio_file variable.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51575927
type: AnsweredQuestion
has body: I am attempting to build a function which will pull data for any stock and then plot a regression. However, I am running into issues with the source data. My question is - how do I take a time series in a pandas data frame and plot the linear trend over time? My code below: This code will produce the regression: import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np rng = np.random.RandomState(1) x = 10 * rng.rand(50) y = 2 * x - 5 + rng.randn(50) plt.scatter(x, y); plt.show() from sklearn.linear_model import LinearRegression model = LinearRegression(fit_intercept=True) model.fit(x[:, np.newaxis], y) xfit = np.linspace(0, 10, 1000) yfit = model.predict(xfit[:, np.newaxis]) plt.scatter(x, y) plt.plot(xfit, yfit); plt.show() This is my attempt to pass the data via a dataframe from datetime import datetime import pandas_datareader.data as web start = datetime(2017, 8, 1) end = datetime(2018, 7, 30) data_SP = web.DataReader('JPM', 'iex', start, end) y = dates # not sure how to get here? plt.scatter(data['close'], y); plt.show() from sklearn.linear_model import LinearRegression model = LinearRegression(fit_intercept=True) model.fit(data['close'][:, np.newaxis], y) xfit = np.linspace(0, 10, 1000) yfit = model.predict(xfit[:, np.newaxis]) plt.scatter(data['close'], y) plt.plot(xfit, yfit); plt.show()
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51576099
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90117792
linked to: http://stackoverflow.com/q/14946371
tagged with: numpy
answer count: 3
linked to: http://stackoverflow.com/q/40217369
tagged with: pandas
downvote count: 0
score: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/51576119
has answer: http://stackoverflow.com/a/51576119
has answer: http://stackoverflow.com/a/51576099
tagged with: python
has answer: http://stackoverflow.com/a/51581158
has title: Python Regression Modeling with Pandas Data Reader

http://stackoverflow.com/q/51519351
upvote count: 3
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: pickle
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/51519954
accepted answer: http://stackoverflow.com/a/51519954
has title: TypeError on pickle.load with class derived from SimpleNamespace
tagged with: inheritance
has body: Consider this Python (version 3.5) code: import pickle from types import SimpleNamespace class MyClass1(list): def __init__(self, x): self.append(x) class MyClass2(SimpleNamespace): def __init__(self, x): self.x = x a0 = SimpleNamespace(x=99) a1 = MyClass1(99) a2 = MyClass2(99) print('* SimpleNamespace:', pickle.loads(pickle.dumps(a0))) print('* MyClass1:', pickle.loads(pickle.dumps(a1))) print('* MyClass2:', pickle.loads(pickle.dumps(a2))) This works fine for the first two (a0 and a1), but upon handling a2 I get an error: * SimpleNamespace: namespace(x=99) * MyClass1: [99] Traceback (most recent call last): File "./picktest.py", line 20, in &lt;module&gt; print('* MyClass2:', pickle.loads(pickle.dumps(a2))) TypeError: __init__() missing 1 required positional argument: 'x' Observations: SimpleNamespace can be pickled. A class derived from a different type (list) can be (un)pickled. A class derived from SimpleNamespace cannot be unpickled if it has an __init__ requiring arguments. (The error occurs in pickle.loads) Note that I tried replacing self.x = x by just pass and that didn't change anything. Is there a way to make this work other than by reimplementing MyClass2 without inheritance?

http://stackoverflow.com/q/51612463
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has body: As I mentioned in the title I need batches with special structure: 1111 5555 2222 Each digit represent feature-vector. So there are N=4 vectors of each classes {1,2,5} (M=3) and batch size is NxM=12. To accomplish this task I'm using Tensorflow Dataset API and tfrecords: build tfrecord with features, 1 file for each class create instance of Dataset for each class, and initialise iterator for each of them to produce batch I sample M random iterators from list of iterators and from each iterator produce N feature-vectors then I stack features together ... batch ready My concern is that I have hundreds (and maybe thousands in the feature) of classes and storing iterator for each class doesn't look good (from memory and performance perspective). Is there a better way?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51618093
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
tagged with: dataset
has title: Build tensorflow dataset iterator that produce batches with special structure
has answer: http://stackoverflow.com/a/51618093

http://stackoverflow.com/comment/90050936
type: Comment
has text: Please post the code in your question
type: QuestionComment
comment on: http://stackoverflow.com/q/51541452
score: 3

http://stackoverflow.com/a/51611393
type: AcceptedAnswer
has body: One solution is to reverse the order of your MultiIndex levels: df = df.swaplevel(0, 1) Optionally, you may also wish to sort your new MultiIndex. Here's a minimal example: df = pd.DataFrame([[0, 1, 2], [0, 2, 3], [1, 3, 4], [1, 1, 5]], columns=['idx1', 'idx2', 'col']) df = df.set_index(['idx1', 'idx2']) df = df.swaplevel(0, 1).sort_index() print(df) idx2 idx1 1 0 2 1 5 2 0 3 3 1 4
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51611222
answers question: http://stackoverflow.com/q/51611222
upvote count: 1

http://stackoverflow.com/comment/89968220
comment on: http://stackoverflow.com/q/51498881
has text: @WillemVanOnsem ok i change it
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51567095
type: Answer
has body: Version 1: with open("input.txt") as f: for line in f: result = sum(int(x or 0) for x in line.split(",")) print(result) This handles the empty string case (since int("" or 0) == int(0) == 0), and is fairly short, but is otherwise not exceedingly robust. Version 2: with open("input.txt") as f: for line in f: total = 0 for item in line.split(","): try: total += int(item) except ValueError: pass print(total) This is more robust to malformed inputs (it will skip all invalid items rather than throwing an exception). This may be useful if you're parsing messy (e.g. hand-entered) data.
score: 0
answers question: http://stackoverflow.com/q/51567009

http://stackoverflow.com/comment/90222054
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51628161
score: 0
has text: changed 1 lakhs into 100 thousand and 99lakhs into 9.9 milllion

http://stackoverflow.com/q/51525331
tagged with: python
has comment: http://stackoverflow.com/comment/90019621
has body: I am making a program which could take information from any website. But the program is not working. Example-- the website is naukri.com and we have to collect all the hyperlinks of a page: import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl isc = ssl.create_default_context() isc.check_hostname = False isc.verify_mode = ssl.CERT_NONE open = urllib.request.urlopen('https://www.naukri.com/job-listings-Python- Developer-Cloud-Analogy-Softech-Pvt-Ltd-Noida-Sector-63-Noida-1-to-2-years-250718003152src=jobsearchDesk&amp;sid=15325422374871&amp;xp=1&amp;px=1&amp;qp=python%20developer &amp;srcPage=s', context = isc).read() soup = BeautifulSoup(open, 'html.parser') tags = soup('a') for tag in tags: print(tag.get('href', None))
has comment: http://stackoverflow.com/comment/90019954
downvote count: 2
has comment: http://stackoverflow.com/comment/90019583
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90019617
has comment: http://stackoverflow.com/comment/90019851
has comment: http://stackoverflow.com/comment/90020230
score: -1
has title: Scraping website and collect all the hyperlinks using python
has answer: http://stackoverflow.com/a/51526823
answer count: 1
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion

http://stackoverflow.com/comment/90034275
has text: @darkhorse - If still error, it means in some row in something different like this dictionary. Can you check it?
comment on: http://stackoverflow.com/a/51533204
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51571346
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51571630
type: Question
answer count: 2
tagged with: python
score: -2
downvote count: 2
upvote count: 0
type: UnansweredQuestion
has body: &gt;&gt;&gt; list =[] &gt;&gt;&gt; list=input() 32 323 32 42 323 When I'm doing this I have get the result only as a single string I need it to be like this how can I do that? &gt;&gt;&gt; list ['32','323','32','42','323']
has answer: http://stackoverflow.com/a/51571417
has title: How to create a list by giving its values in one line?

http://stackoverflow.com/comment/90091054
comment on: http://stackoverflow.com/q/51562009
type: Comment
has text: Possible duplicate of [Get a list of numbers as input from the user](https://stackoverflow.com/questions/4663306/get-a-list-of-numbers-as-input-from-the-user)
type: QuestionComment
score: 1

http://stackoverflow.com/comment/90002618
type: AnswerComment
has text: @Mr.T In case of people asking "does not work" questions without specifying *in how far* it doesn't, there are three options (1) Start arguing about the SO guidelines in the comments (2) Closevote and move on (3) Answer and show that it *does* work. I chose (3) here, because reading that question I could not believe it not working and hence tried it out. I then thought that I could as well share my attempt because it may be useful to see (also for others) that in fact it does work as expected.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51516736

http://stackoverflow.com/comment/90014455
type: QuestionComment
comment on: http://stackoverflow.com/q/51522734
score: 1
type: Comment
has text: The script does nothing but **defining** two functions. You should run them.

http://stackoverflow.com/q/51527846
tagged with: rpc
tagged with: python
has title: RPC over TCP with multiple clients on same machine
score: 0
tagged with: tcp
answer count: 2
possible better answer: http://stackoverflow.com/a/51528128
has answer: http://stackoverflow.com/a/51528128
has answer: http://stackoverflow.com/a/51528059
type: AnsweredQuestion
tagged with: msgpack
accepted answer: http://stackoverflow.com/a/51528059
has body: I'm building an RPC Server in golang that uses msgpack. The client is built in python using the mprpc library (msgpack over TCP with gevent). My issue is, being an absolute noob in networking, I discovered that I can't use the same address/port with multiple clients running at once on the same computer (socket already bound i guess, it just stalls and timeouts). I have looked around quite a bit but I'm not sure what I should be doing to be able to have multiple clients on the same machine talk to a server (msgpack back and forth). Is this a case where I need to use ZeroMQ ? Or requests over HTTP ? Thanks !
type: Question
tagged with: sockets

http://stackoverflow.com/comment/90216028
type: Comment
type: QuestionComment
has text: Print `args` after parsing so you have a clear idea of the the parser has done.
comment on: http://stackoverflow.com/q/51625407
score: 0

http://stackoverflow.com/comment/90034961
type: Comment
has text: How big are your test files? A 1kb chuck is very tiny. Depending on your filesystem, your HD might be using 512 byte blocks, or on more modern systems 2kb blocks. In either case, you're wasting a lot of time slicing the file up into such tiny chunks. Try a larger chunk size, eg 64kb. IME, that gives good results (but I have a very old 32 bit machine), and you may notice some improvements with chunk sizes up to a megabyte, or even larger, depending on your hardware.
type: QuestionComment
comment on: http://stackoverflow.com/q/51533512
score: 0

http://stackoverflow.com/a/51733978
type: AcceptedAnswer
has body: I ended up going through the OAuth 2.0 setup for a web application instead of an installed application, and using google_auth_oauthlib. The Flow object has a class method from_client_config() which can be used like so (cf. https://developers.google.com/identity/protocols/OAuth2WebServer): from django.conf import settings from django.shortcuts import redirect import google.oauth2.credentials import google_auth_oauthlib.flow # Client configuration for an OAuth 2.0 web server application # (cf. https://developers.google.com/identity/protocols/OAuth2WebServer) CLIENT_CONFIG = {'web': { 'client_id': settings.GOOGLE_CLIENT_ID, 'project_id': settings.GOOGLE_PROJECT_ID, 'auth_uri': 'https://accounts.google.com/o/oauth2/auth', 'token_uri': 'https://www.googleapis.com/oauth2/v3/token', 'auth_provider_x509_cert_url': 'https://www.googleapis.com/oauth2/v1/certs', 'client_secret': settings.GOOGLE_CLIENT_SECRET, 'redirect_uris': settings.GOOGLE_REDIRECT_URIS, 'javascript_origins': settings.GOOGLE_JAVASCRIPT_ORIGINS}} # This scope will allow the application to manage your calendars SCOPES = ['https://www.googleapis.com/auth/calendar'] def get_authorization_url(): # Use the information in the client_secret.json to identify # the application requesting authorization. flow = google_auth_oauthlib.flow.Flow.from_client_config( client_config=CLIENT_CONFIG, scopes=SCOPES) # Indicate where the API server will redirect the user after the user completes # the authorization flow. The redirect URI is required. flow.redirect_uri = 'http://localhost:8000' # Generate URL for request to Google's OAuth 2.0 server. # Use kwargs to set optional request parameters. authorization_url, state = flow.authorization_url( # Enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Enable incremental authorization. Recommended as a best practice. include_granted_scopes='true') return authorization_ur…
has comment: http://stackoverflow.com/comment/112407474
upvote count: 5
answers question: http://stackoverflow.com/q/51601915
type: Answer
accepted answer of: http://stackoverflow.com/q/51601915
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/130467032

http://stackoverflow.com/q/51634368
upvote count: 1
type: Question
answer count: 2
has title: Pandas group-by / pivot data while entries of one column become new lables
downvote count: 0
possible better answer: http://stackoverflow.com/a/51634527
has answer: http://stackoverflow.com/a/51634527
has answer: http://stackoverflow.com/a/51634510
tagged with: pandas
favorite count: 0
linked to: http://stackoverflow.com/q/51623539
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
accepted answer: http://stackoverflow.com/a/51634510
has body: I would like to sum-up the capacities of power plants by technology with python + pandas (previous question). For this task the data must be grouped / pivoted while the column entries in column "Technology" should become column labels This is my input: Plant Name,Nameplate Capacity,Technology,... Barry,153.1,Natural Gas Steam Turbine,.. Barry,153.1,Natural Gas Steam Turbine,.. Barry,403.7,Conventional Steam Coal,.. Barry,788.8,Conventional Steam Coal,.. Barry,195.2,Natural Gas Fired Combined Cycle,.. Barry,195.2,Natural Gas Fired Combined Cycle,.. And the desired output: Plant Name,Natural Gas Steam Turbine,Conventional Steam Coal,Natural Gas Fired Combined Cycle,.. Barry,306.2,1192.5,390.4,.. I've tried a few commands, but nothing worked out: df.groupby(['Plant Name', 'Technology']).sum().pivot('Plant Name', 'Technology').fillna(0) or #with numpy as np res = df.pivot_table(index=["Plant Name"], columns=["Plant Name"], values=["Technology"], aggfunc=np.sum) An additional question How can I find out the largest entry (e.g. "Conventional Steam Coal" in my example) for each row as a new column?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/64330740
score: 1

http://stackoverflow.com/a/55219917
answers question: http://stackoverflow.com/q/51502539
has body: I solved the same problem using @ChristopherPaterson solution but removing --quantize_weights=true worked for me. The command is: tflite_convert --graph_def_file=optimized_graph.pb \ --output_file=output/optimized_graph_quantized.tflite \ --output_format=TFLITE \ --input_shape=1,299,299,3 \ --input_array=Mul \ --output_array=final_result \ --inference_type=QUANTIZED_UINT8 \ --std_dev_values=128 --mean_values=128 \ --default_ranges_min=-6 --default_ranges_max=6
score: 0
type: Answer

http://stackoverflow.com/q/51600182
has body: I am trying to associate my testing frame with my log file to figure out which instances pass and which ones fail. To explain better, here's an example : I have a list: data = ['F','P'] # first test pass, second test fail and Here's my log file: USER INPUT : “clear” ------ SYSTEM RESPONSE: “Hello! How are you?” | Fail USER INPUT : “Good thank you” | SYSTEM RESPONSE: "Okay" ------ USER INPUT : “clear” ------ SYSTEM RESPONSE: “Hello! How are you?” | USER INPUT : “I am good, Thank you!” | Pass SYSTEM RESPONSE: "Great!" | USER INPUT : “Good” ------ So every instance of "clear" shows a new log, therefor I want for the first "clear" till the next clear occurs to be associated with P, I am using html to build the code and whenever P occurs it will be green in color and every time F occurs, the code with be red So far what I have is : for line in lines : for i in cc: if (data[i]== 'P'): n = """&lt;p style="color:green;&gt;""" + line + '&lt;/p&gt;' else: n = """&lt;p style="color:red;&gt;""" + line + '&lt;/p&gt;' I am really unsure of the structure. how to find every time "clear" is occuring and assigning it a specific color until the next instance occurs. Please feel free to ask me any questions regarding this or to further clarify! Thanks a ton!
has comment: http://stackoverflow.com/comment/90167373
has title: Python: For every time "clear" occurs, I want the text to be associated with a list
has comment: http://stackoverflow.com/comment/90166663
has comment: http://stackoverflow.com/comment/90166735
type: Question
has comment: http://stackoverflow.com/comment/90166792
has answer: http://stackoverflow.com/a/51600285
accepted answer: http://stackoverflow.com/a/51600839
upvote count: 2
tagged with: python-2.7
answer count: 2
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51600839
tagged with: python
possible better answer: http://stackoverflow.com/a/51600285
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/51594270
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51594341
upvote count: 1
downvote count: 1
type: Question
tagged with: indexing
tagged with: group-by
has body: I'm using the following function: first_last = df.groupby(['stock', Grouper(freq='D')])['price'].agg(['first','last']) , which gives me a dataframe with the first non-nan and the last non-nan prices per day per stock. Could you please hel me, how can I add two columns to the created "first_last" df, so that they contain the original indices of dataframe "df", from which first&amp;last values are taken? The original df is of the following form: Index price stock 2016-10-21 17:00:00 150 85 2016-10-21 17:30:00 100 85 2016-10-21 17:00:00 50 88 -- I need to have "Index" in front of each value of first and last price values in df "first_last".
accepted answer: http://stackoverflow.com/a/51594341
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
has title: Column of original indices in groupby pandas
tagged with: python

http://stackoverflow.com/q/51599699
has comment: http://stackoverflow.com/comment/90171277
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: c++
has title: C++ embedding Python using Boost.Python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/90244166
tagged with: boost
has comment: http://stackoverflow.com/comment/90246726
type: Question
has body: So I'm writing a Windows DLL for use in another program, and I want to have certain C++ functions call Python functions in a Python script. The C++ functions are in an instantiated object; when the object calls the script, the script should be able to call that object's functions as well. I've been trying to do this through Boost.Python but the documentation for Boost.Python is pretty vague on how I'd accomplish this, and the few tutorials I've found have been equivalents of "... and then draw the rest of the owl." (I've also heard things about using pybind, but I'm restricted to MSVC 9.0 and pre-C11 at this stage of development). It's been a pretty rough slog uphill just to get to where I'm at, which isn't far. So basically, I'm (very roughly) looking along the lines of: BOOST_PYTHON_MODULE(PythonModule) { class_&lt;CPythonModule, boost::noncopyable&gt;("Functions", boost::python::no_init) .def("foo", &amp;CPythonModule::foo) } void CPythonModule::foo(string message) { some_function_that_prints_things(message); } int main_module_method() { Py_Initialize(); ??? call_python_script_function(script.py, bar); } And then the script: import PythonModule def bar: PythonModule.Functions.foo("Foo bar") I assume I'd need to pass the instance of the C++ object to the Python script, and ideally the script or the Python interpreter would be an object that I'd keep around until the DLL is unloaded. I'm also pretty vague about the actual details of calling that script. My searches have been frustratingly fruitless. EDIT: With some fiddlework, it looks like my biggest unknown is figuring out how to send my current instance of the object to the Python script and calling that object's functions, without creating a new object within Python. With this line, I can make the object uninitializable: class_&lt;CPythonModule, boost::noncopyable&gt;("Functions", boost::python::no_init) However, I also then can't call the functions in the class, because Python requires an instance of the class…
downvote count: 0
linked to: http://stackoverflow.com/q/5055443
tagged with: boost-python
tagged with: visual-c++
has comment: http://stackoverflow.com/comment/90196442
has comment: http://stackoverflow.com/comment/90243961
favorite count: 0

function
tags question: http://stackoverflow.com/q/51626227
tags question: http://stackoverflow.com/q/51583944
tags question: http://stackoverflow.com/q/51582436
tag name: function
tags question: http://stackoverflow.com/q/51507698
tags question: http://stackoverflow.com/q/51584954
tags question: http://stackoverflow.com/q/51493095
tags question: http://stackoverflow.com/q/51549860
tags question: http://stackoverflow.com/q/51567134
tags question: http://stackoverflow.com/q/51604235
tags question: http://stackoverflow.com/q/51621278
tags question: http://stackoverflow.com/q/51582040
tags question: http://stackoverflow.com/q/51600018
tags question: http://stackoverflow.com/q/51567675
tags question: http://stackoverflow.com/q/51502479
tags question: http://stackoverflow.com/q/51606675
tags question: http://stackoverflow.com/q/51602174
tags question: http://stackoverflow.com/q/51516589
tags question: http://stackoverflow.com/q/51527516
tags question: http://stackoverflow.com/q/51504196
tags question: http://stackoverflow.com/q/51582593
tags question: http://stackoverflow.com/q/51622452
type: Tag
tags question: http://stackoverflow.com/q/51577524
tags question: http://stackoverflow.com/q/51619020
tags question: http://stackoverflow.com/q/51533808
tags question: http://stackoverflow.com/q/51510640
tags question: http://stackoverflow.com/q/51571112
tags question: http://stackoverflow.com/q/51583924
tags question: http://stackoverflow.com/q/51563548
tags question: http://stackoverflow.com/q/51614375
tags question: http://stackoverflow.com/q/51590633
tags question: http://stackoverflow.com/q/51530216
tags question: http://stackoverflow.com/q/51598961
tags question: http://stackoverflow.com/q/51544505
tags question: http://stackoverflow.com/q/51622363
tags question: http://stackoverflow.com/q/51589573
tags question: http://stackoverflow.com/q/51510371
tags question: http://stackoverflow.com/q/51560126
tags question: http://stackoverflow.com/q/51506845
tags question: http://stackoverflow.com/q/51527164
tags question: http://stackoverflow.com/q/51561426
tags question: http://stackoverflow.com/q/51577894
tags question: http://stackoverflow.com/q/51599776

http://stackoverflow.com/a/51590693
type: Answer
has body: You should be able to use np.intersect1d to create a mask where the length of that intersection is two or more and boolean flip it to only retain desired elements from your original dataframe. df[~df.model.apply(lambda L: len(np.intersect1d(L, same_elements)) &gt;= 2)] Which'll give you identical output as per your existing code: model result 1 [A, B, C, E] 39 2 [A, B, C, F] 62 7 [A, B, E, F] 10 13 [A, C, E, F] 28 20 [B, C, D, E] 38 21 [B, C, D, F] 33 24 [B, C, E, G] 9 25 [B, C, F, G] 11 26 [B, D, E, F] 73 29 [B, E, F, G] 1 30 [C, D, E, F] 96 33 [C, E, F, G] 77
accepted answer of: http://stackoverflow.com/q/51590334
has comment: http://stackoverflow.com/comment/90148240
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51590334
downvote count: 0

http://stackoverflow.com/a/51544531
downvote count: 0
score: 5
type: Answer
answers question: http://stackoverflow.com/q/51544427
upvote count: 5
has body: Perform a groupby on the 'ID' column and use filter: df = df.groupby('ID').filter(lambda grp: grp['Yurt'].eq('-').sum() == 2) Output: ID % Yurt 4 lmn789 0.837 Mickey's 5 lmn789 0.856 Chopped Cheese 6 lmn789 0.813 - 7 lmn789 0.812 -

http://stackoverflow.com/q/51527851
accepted answer: http://stackoverflow.com/a/51527912
has answer: http://stackoverflow.com/a/51527974
tagged with: web-scraping
has body: Python beginner here. I'm stumped on part of this code for a bot I'm writing. I am making a reddit bot using Praw to comb through posts and removed a specific set of characters (steam CD keys). I made a test post here: https://www.reddit.com/r/pythonforengineers/comments/91m4l0/testing_my_reddit_scraping_bot/ This should have all the formats of keys. Currently, my bot is able to find the post using a regex expression. I have these variables: steamKey15 = (r'\w\w\w\w\w.\w\w\w\w\w.\w\w\w\w\w') steamKey25 = (r'\w\w\w\w\w.\w\w\w\w\w.\w\w\w\w\w.\w\w\w\w\w.\w\w\w\w\w.') steamKey17 = (r'\w\w\w\w\w\w\w\w\w\w\w\w\w\w\w\s\w\w') I am finding the text using this: subreddit = reddit.subreddit('pythonforengineers') for submission in subreddit.new(limit=20): if submission.id not in steamKeyPostID: if re.search(steamKey15, submission.selftext, re.IGNORECASE): searchLogic() saveSteamKey() So this is just to show that the things I should be using in a filter function is a combination of steamKey15/25/17, and submission.selftext. So here is the part where I am confused. I cant find a function that works, or is doing what I want. My goal is to remove all the text from submission.selftext(the body of the post) BUT the keys, which will eventually be saved in a .txt file. Any advice on a good way to go around this? I've looked into re.sub and .translate but I don't understand how the parts fit together. I am using Python 3.7 if it helps.
type: AnsweredQuestion
tagged with: praw
has answer: http://stackoverflow.com/a/51527912
tagged with: python-3.x
type: Question
answer count: 2
tagged with: python
has title: How to filter out specific strings from a string
possible better answer: http://stackoverflow.com/a/51527974
score: 0

http://stackoverflow.com/q/51609643
tagged with: conv-neural-network
tagged with: recurrent-neural-network
tagged with: lstm
type: Question
has title: ML sequence classification
has body: I am working on a problem for classifying a specific type of Rock (rock_type) in a log consisting of 8 columns. The logs are a sequence with one column being depth. E.g. depth f_1 f_2 ... f_n rock_type 0 0.4 0.3 14.5 0 1.3 0.2 0.1 13.8 0 2.4 0.8 0.3 9.7 1 3.2 1.4 0.3 12.5 1 4.9 1.8 2.6 15.2 1 I have a training set as listed above with labels at each point. The problem is that the rock types generally occur in batches/chunks. Meaning that you will have the same rocktype multiple times after each other (not just at one depth point). The approach I have taken so far is using normal ML classification models (RF/XGBoost) which gives a fair performance, but the model doesn't take into account that this is a time series problem as I see it - because if point t-1 is rock_type 0, it is likely that the next point (t) is rock_type 0 as well). And I have therefore thought of using LSTM (Keras/tensorflow) or similar models for this. The test set I have is a continuous sequence where I want to divide certain parts of the sequence into different types of rocks. (e.g. depth from 300-450 m is rock 0, depth from 700-780 is rock 1 etc). I have also though of using CNN for this. Identifying parts of the sequence as specific rock types. Anyone have a suggestion on how to tackle this problem?
answer count: 1
tagged with: keras
has answer: http://stackoverflow.com/a/51609914
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51609914
type: AnsweredQuestion

http://stackoverflow.com/comment/89973718
comment on: http://stackoverflow.com/q/51502615
score: 0
type: Comment
type: QuestionComment
has text: Can you post what have you tried as well?

http://stackoverflow.com/q/51503974
answer count: 2
has comment: http://stackoverflow.com/comment/89977185
favorite count: 0
has answer: http://stackoverflow.com/a/51504036
has comment: http://stackoverflow.com/comment/89976754
has comment: http://stackoverflow.com/comment/89976735
tagged with: python
upvote count: 0
has title: Python packages on Ubuntu server
has comment: http://stackoverflow.com/comment/89977136
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89976872
has answer: http://stackoverflow.com/a/51504063
downvote count: 1
score: -1
tagged with: ubuntu
type: Question
has body: For a project I want to get httplib2, os, base64, and sys on an Ubuntu server. I got pip on the server, but when I tried to download the packages/modules I get this. Installing collected packages: httplib2 Could not install packages due to an EnvironmentError: [Errno 13] Permission den ied: '/usr/local/lib/python2.7/dist-packages/httplib2-0.11.3.dist-info' Consider using the `--user` option or check the permissions. ubuntu@ip-172-31-30-97:~$ pip install os Collecting os Could not find a version that satisfies the requirement os (from versions: ) No matching distribution found for os ubuntu@ip-172-31-30-97:~$ pip install base64 Collecting base64 Could not find a version that satisfies the requirement base64 (from versions: ) No matching distribution found for base64 ubuntu@ip-172-31-30-97:~$ pip install sys Collecting sys Could not find a version that satisfies the requirement sys (from versions: ) No matching distribution found for sys I am also not sure if my python scripts will then be able to find the packages once they are downloaded onto the server. Maybe I am asking the wrong question, but my code needs these packages to run. Thanks!

http://stackoverflow.com/comment/89999540
type: Comment
has text: Thank you very much @xdze2. Your answer solved my question and will help me a lot.
type: AnswerComment
comment on: http://stackoverflow.com/a/51515357
score: 0

http://stackoverflow.com/a/51495186
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/90018805
has comment: http://stackoverflow.com/comment/90017666
has comment: http://stackoverflow.com/comment/89994340
downvote count: 0
has body: The basic idea is to write code that generates the __init__ method for you, with all the parameters specified explicitly rather than via *args and/or **kwargs, and without even needing to repeat yourself with all those self.arg1 = arg1 lines. And, ideally, it can make it easy to add type annotations that PyCharm can use for popup hints and/or static type checking.1 And, while you're at it, why not build a __repr__ that displays the same values? And maybe even an __eq__, and a __hash__, and maybe lexicographical comparison operators, and conversion to and from a dict whose keys match the attributes for each JSON persistence, and… Or, even better, use a library that takes care of that for you. Python 3.7 comes with such a library, dataclasses. Or you can use a third-party library like attrs, that works with Python 3.4 and (with some limitations) 2.7. Or, for simple cases (where your objects are immutable, and you want them to work like a tuple of their attributes in specified order), you can use namedtuple, which works back to 3.0 and 2.6. Unfortunately, dataclasses doesn't quite work for your use case. If you just write this: from dataclasses import dataclass @dataclass class Parent: arg1: str opt_arg1: str = 'opt_arg1_default_val' opt_arg2: str = 'opt_arg2_default_val' opt_arg3: str = 'opt_arg3_default_val' opt_arg4: str = 'opt_arg4_default_val' @dataclass class Child(Parent): arg2: str … you'll get an error, because it tries to place the mandatory parameter arg2 after the default-values parameters opt_arg1 through opt_arg4. dataclasses doesn't have any way to reorder parameters (Child(arg1, arg2, opt_arg1=…), or to force them to be keyword-only parameters (Child(*, arg1, opt_arg1=…, arg2)). attrs doesn't have that functionality out of the box, but you can add it. So, it's not quite as trivial as you'd hope, but it's doable. But if you wanted to write this yourself, how would you create the __init__ function dynamically? The simplest option is exec. You've probably …
has comment: http://stackoverflow.com/comment/89960218
has comment: http://stackoverflow.com/comment/89985984
has comment: http://stackoverflow.com/comment/90017802
score: 4
accepted answer of: http://stackoverflow.com/q/51494723
has comment: http://stackoverflow.com/comment/89985923
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51494723
has comment: http://stackoverflow.com/comment/89985583
has comment: http://stackoverflow.com/comment/90037067
has comment: http://stackoverflow.com/comment/89975776
has comment: http://stackoverflow.com/comment/89998367

http://stackoverflow.com/comment/89981505
type: QuestionComment
score: 1
has text: @R.Randi, if `./runyrun.py` gave that error, that means the script didn't have a proper shebang; if it started with `#!/usr/bin/env python` as the first line, then `python` would be invoked to execute it.
comment on: http://stackoverflow.com/q/51506200
type: Comment

http://stackoverflow.com/q/51611168
type: Question
tagged with: matplotlib
score: 0
answer count: 1
tagged with: histogram
has answer: http://stackoverflow.com/a/51611325
accepted answer: http://stackoverflow.com/a/51611325
tagged with: python
tagged with: plot
type: AnsweredQuestion
has title: Python:Normalized histogram with bin definition
has body: def histg(x,bins): n, bins = plt.hist(x, bins,normed=True) plt.show() return (plt) I want to create bins by dividing the min and max of the data in to equal intervals. Considering a sample data X : 67 45 22 48 91 46 52 61 58. How do i do it in the function?

http://stackoverflow.com/comment/90000844
type: QuestionComment
comment on: http://stackoverflow.com/q/51515832
has text: Thank you for data, what is expected output?
score: 0
type: Comment

http://stackoverflow.com/a/51622249
answers question: http://stackoverflow.com/q/51622161
score: 3
type: AcceptedAnswer
has body: You might want to look at the "intermixed" options of argparser https://docs.python.org/3/library/argparse.html#intermixed-parsing Otherwise, positional arguments always come before optional arguments.
has comment: http://stackoverflow.com/comment/90210164
upvote count: 3
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/90210183
accepted answer of: http://stackoverflow.com/q/51622161

http://stackoverflow.com/q/51602694
has body: I have an excel file that is 20x50000. It is around 13mb in size. However calling this line alone: openpyxl.load_workbook(FILENAME, read_only=True) takes up over a gigabyte of RAM. This is causing issues in my environment. Any idea what might be causing this? I read from another poster that he had a similar issue and it was a misformatted cell but he hasn't posted for a year now so I doubt I'll see how he fixed it. What could cause this? Let me know if any extra information is needed.
has comment: http://stackoverflow.com/comment/90203404
has comment: http://stackoverflow.com/comment/90203691
has comment: http://stackoverflow.com/comment/90203479
answer count: 0
type: UnansweredQuestion
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/90171565
tagged with: python
linked to: http://stackoverflow.com/q/39263563
tagged with: excel
has title: Opening 13mb file in openPyXl uses 1.2 gb of memory
has comment: http://stackoverflow.com/comment/90172892
type: Question
has comment: http://stackoverflow.com/comment/90203871
has comment: http://stackoverflow.com/comment/90203750
has comment: http://stackoverflow.com/comment/90171411
score: 0

myo
tag name: myo
type: Tag
tags question: http://stackoverflow.com/q/51625881

http://stackoverflow.com/q/51583539
tagged with: python
has title: Error in Tensorflow
has comment: http://stackoverflow.com/comment/90166101
upvote count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90139273
has comment: http://stackoverflow.com/comment/90132606
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/37568980
has comment: http://stackoverflow.com/comment/90186412
tagged with: deep-learning
has body: I have tried below code but while running the session on test data I am getting error Run time Error: Attempted to use a closed Session. Code with tf.Session() as session: epochs = 10 batch_size = 3 session.run(init) session.run(local_init) num_batches = int(matrix.shape[0] / batch_size) matrix = np.array_split(matrix, num_batches) for i in range(epochs): avg_cost = 0 for batch in matrix: _, l = session.run([optimizer, loss], feed_dict={X: batch}) avg_cost += l avg_cost /= num_batches print("Epoch: {} Loss: {}".format(i + 1, avg_cost)) print("Predictions...") matrix = np.concatenate(matrix, axis=0) preds = session.run(decoder_op, feed_dict={X: matrix}) predictions = predictions.append(pd.DataFrame(preds)) predictions = predictions.stack().reset_index(name='quantity') predictions.columns = ['user_id', 'product_id', 'quantity'] predictions['user_id'] = predictions['user_id'].map(lambda value: users[value]) predictions['product_id'] = predictions['product_id'].map(lambda value: items[value]) #print(predictions) print("Filtering out items in training set") keys = ['user_id', 'product_id'] i1 = predictions.set_index(keys).index i2 = df.set_index(keys).index recs = predictions[~i1.isin(i2)] recs = recs.sort_values(['user_id', 'quantity'], ascending=[True, False]) recs = recs.groupby('user_id').head(10) recs.to_csv('C:\\Users\\ayush.kumar.jain\\Desktop\\deler\\recs.tsv', sep='\t', index=False, header=True) print(type(recs)) test = test.sort_values(['user_id', 'quantity'], ascending=[True, False]) #test = test.groupby('user').head(k) #.reset_index(drop=True) #test_list = test.as_matrix(columns=['item']).reshape((-1)) #recs_list = recs.groupby('user').head(k).as_matrix(columns=['item']).reshape((-1)) print("Evaluating...") p = 0.0 for user_id in users[:10]: test_list = test[(test.user_id == user_id)].head(k).as_matrix(columns=['product_id']).flatten() print(test_list) recs_list = recs[(recs.user_id == user_id)].head(k).as_matrix(columns=['product_id']).flatten() print(recs_l…
downvote count: 0
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90132604
has comment: http://stackoverflow.com/comment/90139337
has comment: http://stackoverflow.com/comment/90134522

http://stackoverflow.com/q/51622736
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: multithreading
has body: Short version: Context: The start of my training data input pipeline is a tf.data.Dataset.from_generator call. I am running into unexpectedly poor performance when using a buffered staging area rather than streaming data directly through a python generator. The buffered staging area is filled by multiple producers (in C++), and consumed via python generator. Performance is substantially better when streaming the data through the python generator in a single-thread synthesize-data-as-needed fashion, despite the higher raw throughput of the buffered generator. I'm not sure why this is the case. Context &amp; (semi)Specifics: We are using synthetic images created in C++ as sample data for training. The data synthesis program is thread-safe, so throughput can be improved with concurrent generation. Python (CPython) has its nasty GIL, so we implemented a buffered staging area in C++. This staging area is filled by multiple producers, and consumed from via our python generator (C++ -> python transition using ctypes). The intent behind this program structure is to improve the speed of data IO by minimizing the work being done in the python generator. This works great in simple cases when testing the raw throughput of the python generator. It also functions appropriately when working within the context of a trivial Tensorflow program, which just creates a dataset from this generator and iterates through N examples. When plugged into our actual training pipeline, however, the buffered generator appears to function far less appropriately. The producer threads fill the buffer very quickly into the lifetime of the Tensorflow training program, and are just waiting around most of the time (not busy waiting). My understanding is that IO in this pipeline would be trivial once the buffered area is full, as all the python generator needs to do is pull one sample from its nice supply of pre-formatted samples and yield it on over to the Tensorflow runtime (via tf.data.Dataset.from_gene…
upvote count: 1
tagged with: tensorflow
type: Question
score: 1
downvote count: 0
has title: Dataset `from_generator` poor performance with buffered staging area
tagged with: tensorflow-datasets
favorite count: 0

http://stackoverflow.com/a/51527976
upvote count: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90125613
downvote count: 0
has comment: http://stackoverflow.com/comment/90124226
accepted answer of: http://stackoverflow.com/q/51509141
type: Answer
has comment: http://stackoverflow.com/comment/90134671
answers question: http://stackoverflow.com/q/51509141
has comment: http://stackoverflow.com/comment/90125141
has body: There are plenty of ways to form a greatest-n-per-group query, but in this case you could form a union of top-n queries of all users: contents = Content.objects.\ none().\ union(*[Content.objects. filter(user_id=uid). order_by('-id')[:25] for uid in user_ids], all=True) Using prefetch_related() you could then produce a queryset that fetches the users and injects an attribute of latest content: users = User.objects.\ filter(id__in=user_ids).\ prefetch_related(models.Prefetch( 'content_set', queryset=contents, to_attr='latest_content'))
has comment: http://stackoverflow.com/comment/90134751
has comment: http://stackoverflow.com/comment/90125471
score: 4

http://stackoverflow.com/q/51485494
upvote count: 1
downvote count: 1
answer count: 1
favorite count: 0
tagged with: measure
tagged with: python
has comment: http://stackoverflow.com/comment/90088476
has comment: http://stackoverflow.com/comment/89967124
type: AnsweredQuestion
tagged with: image-processing
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/89954046
has body: The following image is of a coin (for reference) and a pill. I need to measure the pill's dimensions. The objects are back-illuminated. I followed pyimagesearch.com tutorial for object height and width measurement. The coin has a diameter of 24.97 mm, and the actual dimensions of the pill are 9.43 mm x 19.33 mm. I am getting results with some error ranging from 0.5 mm to 2 mm. As mentioned on the website this is because of distortion and it is to be corrected. Can someone help me in calibrating the camera to remove the distortion effect so that I can measure correct dimensions in mm? I have also tried camera calibration but that is also not working.
has title: Object dimension measurement
has answer: http://stackoverflow.com/a/51561235
accepted answer: http://stackoverflow.com/a/51561235
has comment: http://stackoverflow.com/comment/90076744
score: 0

http://stackoverflow.com/comment/90119686
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51577133
has text: An example of profile_text?
score: 0

http://stackoverflow.com/a/51566499
has body: If I understand your problem, what you want to do is pretty easy with some help from the stdlib. First, open the file: with open(path) as f: Then attach a csv.reader, which turns it from an iterable of lines to an iterable of row lists: rows = csv.reader(f, delimiter=' ') Each of these rows is a list of columns as strings. You obviously need to convert them to int or float or something else to do math on them: rows = (map(float, row) for row in rows) Now you need to convert that into an iterable of adjacent pairs of rows. If you look at the Recipes in the itertools docs, there's a pairwise function that does this for any iterable. But it's simple enough to just do manually: it1, it2 = itertools.tee(rows) next(it2) pairs = zip(it1, it2) Now, pairs is an iterable of pairs of rows. So we can loop over it: for xrow, yrow in pairs: I'm not sure what you wanted to do with these pairs of rows. Maybe you wanted, I don't know, the square root of the squares of the differences of the columns? Whatever you want should be pretty easy: diffs = (x - y for x, y in zip(xrow, yrow)) sumsquares = sum(diff*diff for diff in diffs) print(sumsquares**0.5) This will print out: 0.0 11.832159566199232 11.269427669584644 … which I'm sure isn't what you want, because you wanted to do some different math than the math I picked out of thin air, but hopefully it's obviously why this is the result, and how to use the same structure for your actual problem.
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51566436
type: Answer

http://stackoverflow.com/comment/89973064
comment on: http://stackoverflow.com/a/51502232
has text: Thanks lenik. That was it. I am still trying to get used to Python. This is quite different from many other languages that I've worked with in the past. How did you figure that out? I am using Spyder. I selected all text, hit Ctrl+F11, and nothing happened. On the Debug Menu, Ctrl+F11 is supposed to let a user step into the code, but it actually does nothing.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90563102
comment on: http://stackoverflow.com/a/51541184
type: Comment
score: 7
type: AnswerComment
has text: restarting vs code fixed this for me after installing pylint

http://stackoverflow.com/comment/90259929
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51589416
has text: bquan@ubuntu:~/python$ pip3 install PyMySQL <snip> Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/cryptography-2.3.dist-info' Consider using the `--user` option or check the permissions.

http://stackoverflow.com/a/53381309
has comment: http://stackoverflow.com/comment/96169753
downvote count: 0
has comment: http://stackoverflow.com/comment/103473383
type: Answer
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/97550132
has comment: http://stackoverflow.com/comment/99502391
answers question: http://stackoverflow.com/q/51588186
has body: I found that there are a couple of workarounds, depending on various context: Using clear_session() function: from keras import backend as K Then do following at the beginning or at the end of the function, after predicting all the data: K.clear_session() Calling _make_predict_function(): After you load your trained model call: model._make_predict_function() See explanation Disable threading: If you are running django server use this command: python manage.py runserver --nothreading For flask use this: flask run --without-threads If none of the above solutions work, check these links keras issue#6462, keras issue#2397

http://stackoverflow.com/q/51632540
upvote count: 2
has comment: http://stackoverflow.com/comment/90229480
has comment: http://stackoverflow.com/comment/90230538
type: UnansweredQuestion
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90230297
has comment: http://stackoverflow.com/comment/90230483
score: 1
has comment: http://stackoverflow.com/comment/90252645
has comment: http://stackoverflow.com/comment/90229994
has comment: http://stackoverflow.com/comment/90229852
has body: I've written this usual fibonacci python code in python official idle; def fib(n): a, b = 0, 1 while a &lt; n: print(a, end=' ') a, b = b, a+b print() fib(10000000) When i increased n,like i did in exemple, in idle it've taken around 30s-60s to finish it, after this, I saved the python file as fibo.py and I ve opened it on cmd by importing module after opening python in cmd with -py extension. Even if you put a very big number n in cmd, the process ends in less than 2 seconds always. Its a very very very high speed, but this isn't same for python idle, Any answer would be appriciated.
has comment: http://stackoverflow.com/comment/90229245
has comment: http://stackoverflow.com/comment/90229599
linked to: http://stackoverflow.com/q/2212722
has comment: http://stackoverflow.com/comment/90229924
has comment: http://stackoverflow.com/comment/90230160
has comment: http://stackoverflow.com/comment/90229940
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/2212722
has title: How does cmd work way faster(like 10x) than python idle?
tagged with: python
tagged with: python-idle
tagged with: cmd
has comment: http://stackoverflow.com/comment/90230416
has comment: http://stackoverflow.com/comment/90229305
has comment: http://stackoverflow.com/comment/90229681
answer count: 0

http://stackoverflow.com/a/51518245
has body: You can use list comprehension: for files in [f for f in os.listdir(path) if f.endswith("geneclusters.txt")]:
upvote count: 1
answers question: http://stackoverflow.com/q/51518201
score: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/51585599
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51585727
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51671945
score: 2
has title: Error using OLS in statsmodel
has body: I'm getting the error, IndexError: boolean index did not match indexed array along dimension 1; dimension is 52 but corresponding boolean dimension is 184 from running the following code: y = dat2['WaterWithdMunicipal'] X = dat2['WaterWithdIndustrial'] model = sm.OLS(y,X, data=dat2, missing='drop') p = model.fit() print(p.summary()) I know that the 2 arrays are different sizes (they contain different numbers of NaNs) but shouldn't the missing = 'drop' take care of that?
downvote count: 0
tagged with: linear-regression

http://stackoverflow.com/comment/90022933
has text: When I try it I get this error: ValueError: Could not convert object to NumPy timedelta
comment on: http://stackoverflow.com/q/51527011
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51512061
score: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89994189
has title: Pandas index datetime formatting is not giving desired output Python3
has body: I have tried the following: df.index= pd.to_datetime(df.index,format="%Y.%m.%d %HH:%MM:%SS") df.tail() The output was: open high low close Time 2018-07-24 16:25:00 1.16963 1.16976 1.16952 1.16952 2018-07-24 16:26:00 1.16952 1.16952 1.16938 1.16939 2018-07-24 16:27:00 1.16939 1.16940 1.16896 1.16908 2018-07-24 16:28:00 1.16909 1.16929 1.16908 1.16929 2018-07-24 16:29:00 1.16930 1.16932 1.16919 1.16925 I was expecting that the Time index of the dataframe shoud be in the format as shown in the following output: open high low close Time 2018.07.24 16:25:00 1.16963 1.16976 1.16952 1.16952 2018.07.24 16:26:00 1.16952 1.16952 1.16938 1.16939 2018.07.24 16:27:00 1.16939 1.16940 1.16896 1.16908 2018.07.24 16:28:00 1.16909 1.16929 1.16908 1.16929 2018.07.24 16:29:00 1.16930 1.16932 1.16919 1.16925 Kindly, help me get through this.
answer count: 1
has comment: http://stackoverflow.com/comment/89993552
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51512094
tagged with: python-3.x

http://stackoverflow.com/q/51537178
type: Question
score: 3
tagged with: pyspark
tagged with: spark-structured-streaming
has answer: http://stackoverflow.com/a/51538745
tagged with: apache-spark
tagged with: apache-bahir
has body: I try to use MQTT together with PySpark Structured Streaming. from pyspark.sql import SparkSession from pyspark.sql.functions import explode from pyspark.sql.functions import split spark = SparkSession \ .builder \ .appName("Test") \ .master("local[4]") \ .getOrCreate() # Custom Structured Streaming receiver lines = spark\ .readStream\ .format("org.apache.bahir.sql.streaming.mqtt.MQTTStreamSourceProvider")\ .option("topic","uwb/distances")\ .option('brokerUrl', 'tcp://127.0.0.1:1883')\ .load() # Split the lines into words words = lines.select(explode(split(lines.value, ' ')).alias('word')) # Generate running word count wordCounts = words.groupBy('word').count() # Start running the query that prints the running counts to the console query = wordCounts \ .writeStream \ .outputMode('complete') \ .format('console') \ .start() query.awaitTermination() Error message: Logical Plan: Aggregate [word#7], [word#7, count(1) AS count#11L] +- Project [word#7] +- Generate explode(split(value#2, )), false, [word#7] +- StreamingExecutionRelation org.apache.bahir.sql.streaming.mqtt.MQTTTextStreamSource@383ccec1, [value#2, timestamp#3] at org.apache.spark.sql.execution.streaming.StreamExecution.org$apache$spark$sql$execution$streaming$StreamExecution$$runStream(StreamExecution.scala:295) at org.apache.spark.sql.execution.streaming.StreamExecution$$anon$1.run(StreamExecution.scala:189) Caused by: java.lang.AssertionError: assertion failed: DataFrame returned by getBatch from org.apache.bahir.sql.streaming.mqtt.MQTTTextStreamSource@383ccec1 did not have isStreaming=true I do not understand what is wrong in my code. Moreover, according to this post Structured Streaming 2.1.0 is actually supported by Bahir MQTT. I also tried Spark 2.2.1 and got the same issue. This is how I run the code: spark-submit \ --jars lib/spark-streaming-mqtt_2.11-2.2.1.jar, \ lib/spark-sql-streaming-mqtt_2.11-2.2.1.jar, \ lib/org.eclipse.paho.client.mqttv3-1.2.0.jar \ TestSpark.py How can I solve this issue?
answer count: 1
downvote count: 0
favorite count: 0
has title: DataFrame returned by getBatch from MQTTTextStreamSource did not have isStreaming=true
type: UnansweredQuestion
tagged with: python
upvote count: 3

http://stackoverflow.com/comment/90575979
type: AnswerComment
type: Comment
has text: Oh It means I am doing something wrong here, let me try to figure it out thanks again!
comment on: http://stackoverflow.com/a/51778769
score: 0

http://stackoverflow.com/comment/90112018
type: QuestionComment
comment on: http://stackoverflow.com/q/51571540
score: 0
has text: I tested some more and it seems to be a problem only when plots are arranged vertically. Horizontally aranged, the same problem does not occure.
type: Comment

http://stackoverflow.com/a/51485295
has comment: http://stackoverflow.com/comment/89941708
has comment: http://stackoverflow.com/comment/89940265
has body: The problem appears to be that primefac uses its own multiprocessing.Pool. Unfortunately, while PyPI is down, I can't find the source to the module—but I did find various forks on GitHub, like this one, and they all have multiprocessing code. So, your apparently simple example isn't all that simple—because it's importing and running non-simple code. By default, all Pool processes are daemonic, so you can't create more child processes from inside another Pool. Usually, attempting to do so is a mistake. If you really do want to multiprocess the factors even though some of them are going to multiprocess their own work (quite possibly adding more contention overhead without adding any parallelism), then you just have to subclass Pool and override that—as explained in the related question that you linked. But the simplest thing is to just not use multiprocessing here, if primefac is already using your cores efficiently. (If you need quasi-concurrency, getting answers as they come in instead of getting them in sequence, I suppose you could do that with a thread pool, but I don't think there's any advantage to that here—you're not using imap_unordered or explicit AsyncResult anywhere.) Alternatively, if it's not using all of your cores most of the time, only doing so for the "tricky remainders" at the end of factoring some numbers, while you've got 7 cores sitting idle for 60% of the time… then you probably want to prevent primefac from using multiprocessing at all. I don't know if the module has a public API for doing that. If so, of course, just use it. If not… well, you may have to subclass or monkeypatch some of its code, or, at worst, monkeypatching its import of multiprocessing, and that may not be worth doing. The ideal solution would probably be to refactor primefac to push the "tricky remainder" jobs onto the same pool you're already using. But that's probably by far the most work, and not that much more benefit. As a side note, this isn't your problem, but you sh…
type: Answer
upvote count: 22
score: 21
answers question: http://stackoverflow.com/q/51485212
accepted answer of: http://stackoverflow.com/q/51485212
has comment: http://stackoverflow.com/comment/89939626
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/comment/89989806
has text: @Chad: Oh. Well, I showed you how to find out how many dates there are for each customer--try using `np.arange()` for each customer from the start date to the end date.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51488538

http://stackoverflow.com/q/51498123
answer count: 1
has answer: http://stackoverflow.com/a/51521386
score: 1
favorite count: 0
has body: how to download the image from google and rename the image with keywords at the same time when using google-images-download? While using this package, the name is generated from the Image URL what I except is that the image can be named with the Item name Could anyone help me ? here is code: from google_images_download import google_images_download response = google_images_download.googleimagesdownload() arguments = {"keywords":"cat, dog, pig", "limit":1, "print_urls":True, "image_directory":'home1', "size":"large"} absolute_image_paths = response.download(arguments)
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89964539
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89965051
accepted answer: http://stackoverflow.com/a/51521386
tagged with: web-crawler
type: Question
tagged with: google-crawlers
downvote count: 0
has title: how to download the image from google and rename the image with keywords at the same time in google-images-download

http://stackoverflow.com/comment/90005949
has text: Possible duplicate of [Removing a sublist from a list](https://stackoverflow.com/questions/42881650/removing-a-sublist-from-a-list)
type: QuestionComment
comment on: http://stackoverflow.com/q/51518601
type: Comment
score: 2

http://stackoverflow.com/comment/90125274
score: 0
comment on: http://stackoverflow.com/q/51579868
type: Comment
type: QuestionComment
has text: If I replace the nan values with zeros then I will find a wrong mean. I want to compute the mean from the existing values from each row.

http://stackoverflow.com/comment/90241114
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51635977
has text: @TheCrystalShip How important is it to tie into the press and release, rather than click? Does the colored widget (partially transparent?) cover up the image you are painting?

http://stackoverflow.com/q/51489784
has title: Why are scipy and librosa different for reading wav file?
tagged with: wav
has comment: http://stackoverflow.com/comment/89975421
has comment: http://stackoverflow.com/comment/89987083
has comment: http://stackoverflow.com/comment/89975519
has comment: http://stackoverflow.com/comment/89983394
answer count: 1
downvote count: 0
tagged with: librosa
has body: So I'm trying to get the samples from a wave file and I noticed that it's a different value depending on whether I use scipy or librosa. sampleFloats, fs = librosa.load('hi.wav', sr=48000) print('{0:.15f}'.format(sampleFloats[len(sampleFloats)-1])) from scipy.io.wavfile import read as wavread # from python_speech_features import mfcc [samplerate, x] = wavread('hi.wav') # x is a numpy array of integer, representing the samples # scale to -1.0 -- 1.0 if x.dtype == 'int16': nb_bits = 16 # -&gt; 16-bit wav files elif x.dtype == 'int32': nb_bits = 32 # -&gt; 32-bit wav files max_nb_bit = float(2 ** (nb_bits - 1)) samples = x / (max_nb_bit + 1.0) # samples is a numpy array of float representing the samples print(samples[len(samples)-1]) The print statements read: 0.001251220703125 0.001274064182641886 The sample rate for the file is 48000. Why might they be different? Is librosa using a different normalization?
tagged with: wave
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/56476151
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/42544661
has comment: http://stackoverflow.com/comment/89964886
has comment: http://stackoverflow.com/comment/89975622
upvote count: 1
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/89967117
accepted answer: http://stackoverflow.com/a/56476151
has comment: http://stackoverflow.com/comment/89988651

http://stackoverflow.com/a/51638392
accepted answer of: http://stackoverflow.com/q/51551056
has body: You need to use sys.argv instead of sys.stdin.read(): two_digits.py import sys args = sys.argv # a list of the arguments provided (str) print("running two_digits.py", args) a, b = int(args[1]), int(args[2]) print(a, b, a + b) command line / jupyter magic line: %run two_digits 3 5 or, with a slightly different output: Note: this uses a ! prefix to indicate command line to jupyter !ipython two_digits.py 2 3 output: (using magic line %run) running two_digits.py ['two_digits.py', '2', '3'] 2 3 5
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51551056
score: 27
upvote count: 27
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/124256038

http://stackoverflow.com/comment/90282476
has text: @Humbalan No Worries I got it working !
score: 0
comment on: http://stackoverflow.com/q/51626229
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90215948
type: Comment
comment on: http://stackoverflow.com/a/51610392
score: 0
type: AnswerComment
has text: `gamma` is not a variable of the integration but a parameter. The `args` option is used to pass extra parameters to the function, so `gamma`

http://stackoverflow.com/comment/107965871
type: AnswerComment
comment on: http://stackoverflow.com/a/61027090
type: Comment
score: 2
has text: Welcome! Please note that the [policy](https://stackoverflow.blog/2009/07/23/non-english-question-policy/) is that [questions and answers need to be in English](https://meta.stackexchange.com/questions/13676/do-posts-have-to-be-in-english-on-stack-exchange).

http://stackoverflow.com/comment/90074796
comment on: http://stackoverflow.com/a/51553555
type: AnswerComment
has text: I tried that but still doesnt work. Running this code, it appends the first line to the first line.
score: 0
type: Comment

http://stackoverflow.com/q/51589224
type: Question
has comment: http://stackoverflow.com/comment/90143916
has comment: http://stackoverflow.com/comment/90143958
tagged with: python-2.7
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90144109
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
has body: I have a problem with this particular webstite link to website I'm trying to create a script that can go through all entries but with the condition that it has "memory" so it can continue from the page it last was on. That means I need to know current page number AND a direct url to that page. Here is what I have so far: current_page_el = driver.find_element_by_xpath("//ul[contains(@class, 'pagination')]/li[@class='disabled']/a") current_page = int(current_page_el.text) current_page_url = current_page_el.get_attribute("href") That code will result with current_page_url = 'javascript:void(0);' Is there a way to get current url from sites like this? Also, when you click to get to the next page, link just remains the same like what I posted in the beginning.
answer count: 0
has title: Figuring out page url in Selenium (javascript:void(0);)
type: UnansweredQuestion
tagged with: selenium

http://stackoverflow.com/comment/90205477
has text: avoid regex, just split the string on `_`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51619889
type: Comment

http://stackoverflow.com/comment/90138433
has text: But if you give it `Let me tell you what I am sad about`, that get lowercased, then transformed into `let me tell you what YOU ARE sad about`, and _that_ matches the pattern with spaces so it becomes `I'M SORRY TO HEAR THAT YOU ARE sad`, and that doesn't match the next pattern because there is no space after `sad`.
score: 0
comment on: http://stackoverflow.com/q/51586305
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51589897
tagged with: django
has comment: http://stackoverflow.com/comment/90147213
type: Question
has comment: http://stackoverflow.com/comment/90147504
has title: How to handle multiple notifications model in Django?
has comment: http://stackoverflow.com/comment/90147699
has comment: http://stackoverflow.com/comment/90146329
score: 0
tagged with: python
has body: I'm trying to build website which monitor multiple websites for changes. For example - if keyword [XYZ] occurs on website A then send notification to user. Currently I'm stuck on adding more notification channels without creating mess in my code. I want to create a abstract class with args target, message, methods like send_message and then inherence from it to SMSNotification, PusherNotification, EmailNotification. Where should I put that logic into project? I was thinking about adding it to models.py, but I'm not sure if this won't cause troubles during further development. What's the proper approach for this?
has comment: http://stackoverflow.com/comment/90151876
has comment: http://stackoverflow.com/comment/90151240
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90122940
type: QuestionComment
comment on: http://stackoverflow.com/q/51578739
type: Comment
has text: @mklucz sure, this is the url http://127.0.0.1:8000/blog/2018/07/22/one-more-post/
score: 0

http://stackoverflow.com/a/51808972
has comment: http://stackoverflow.com/comment/108721376
answers question: http://stackoverflow.com/q/51618127
type: Answer
has comment: http://stackoverflow.com/comment/108710703
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/108650767
type: AcceptedAnswer
has body: As per the gspread documentation, the gspread.authorize method only supports credential objects that are created by the oauth2client library. To work with the new google-auth one, gspread should add support for it. A possible workaroud, if you don't want to use the oauthclient2 that is deprecated, is to use authlib leveraging the session parameter of the gspread.Client class. There is a nice tutorial on how to do this here. Update April 27 2020 Starting from version 3.4.0 gspread is now supporting google-auth. You can find all the details in the dedicated documentation. Here is an official statement from the author: Older versions of gspread have used oauth2client. Google has deprecated it in favor of google-auth. If you’re still using oauth2client credentials, the library will convert these to google-auth for you, but you can change your code to use the new credentials to make sure nothing breaks in the future.
accepted answer of: http://stackoverflow.com/q/51618127
upvote count: 5

http://stackoverflow.com/a/60518275
has body: I found that specifying both steps_per_epoch and batch_size raises error. You can find correspondent code lines in the code linked below (seek if steps is not None and batch_size is not None:). Thus, we need to implement a data generator in order to realize such a behavior. https://github.com/keras-team/keras/blob/1cf5218edb23e575a827ca4d849f1d52d21b4bb0/keras/engine/training_utils.py
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51623191
downvote count: 0

rectangles
tags question: http://stackoverflow.com/q/51574829
tag name: rectangles
type: Tag

http://stackoverflow.com/q/51490700
has comment: http://stackoverflow.com/comment/89987212
has answer: http://stackoverflow.com/a/55165355
has comment: http://stackoverflow.com/comment/89986965
has body: I do not have admin rights on my work laptop. Have got python and pip installed on my machine, version numbers as below: C:\Users\banand\AppData\Local\Programs\Python\Python36\Scripts&gt;python --version Python 3.6.1 C:\Users\banand\AppData\Local\Programs\Python\Python36\Scripts&gt;pip --version pip 9.0.1 from c:\users\banand\appdata\local\programs\python\python36\lib\site-packages (python 3.6) I need a way to make use of various python modules available online. An example is - colorama As per the instructions, I tried the below command without any success: C:\Users\banand\AppData\Local\Programs\Python\Python36\Scripts&gt;pip install colorama --user Collecting colorama Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000001D431204F28&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/colorama/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000001D431204A58&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/colorama/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000001D431204780&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/colorama/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnecti…
answer count: 3
upvote count: 7
tagged with: windows
has comment: http://stackoverflow.com/comment/89952385
tagged with: admin-rights
favorite count: 0
has comment: http://stackoverflow.com/comment/89950158
has comment: http://stackoverflow.com/comment/89986988
has comment: http://stackoverflow.com/comment/89987151
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89952475
has comment: http://stackoverflow.com/comment/89953967
tagged with: installation
downvote count: 0
has answer: http://stackoverflow.com/a/59576644
score: 7
has comment: http://stackoverflow.com/comment/89968196
accepted answer: http://stackoverflow.com/a/55165355
has answer: http://stackoverflow.com/a/65927250
type: Question
possible better answer: http://stackoverflow.com/a/59576644
has title: Install python modules on windows without admin rights

http://stackoverflow.com/comment/90160863
comment on: http://stackoverflow.com/q/51597222
score: 0
type: Comment
has text: @PM2Ring yes, i just want to change the number in the dictionary
type: QuestionComment

http://stackoverflow.com/a/51539501
type: Answer
answers question: http://stackoverflow.com/q/51523270
has body: Lacking any builtin methods to solve this problem I've made changes to cbFun(). It has now a few additional lines that contain re.search() and pattern is OID (so when pattern is not matched, i.e. nextCmd goes to another level (node), it just does return). I've made it simple and as there was already constructed string with response print(' = '.join([x.prettyPrint() for x in varBind])), I've added if condition and assigned result of code above to a variable, so I've made it possible to implement this check. As an another possible solution it is also possible to use approach described in this example - using varBindHead and comparing them. Feel free to add your solutions.
accepted answer of: http://stackoverflow.com/q/51523270
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/51537673
tagged with: python
accepted answer: http://stackoverflow.com/a/51537735
score: 2
type: AnsweredQuestion
type: Question
downvote count: 0
tagged with: dataframe
has title: Pandas replace substring from dict of values
has answer: http://stackoverflow.com/a/51537735
tagged with: pandas
has body: Below is sample Dataframe data = {'A': ['hi UK','hi IN','hi US']} df = pd.DataFrame(data) I wanted to update UK, IN values for A column from matching dict below abs = {'U': 'UK -- extra', 'UK': 'test Kingdom', 'IN':'India'} then I used replace function (pandas.DataFrame.replace) df['A'] = df['A'].replace(to_replace = abs, regex=True) print(df) A 0 hi test Kingdom -- extraK 1 hi India 2 hi test Kingdom -- extraS Its replacing U first by UK -- extra and again UK with test kingdom so final result is hi test Kingdom -- extraK idially it should give test kingdom The expected output is A 0 hi test Kingdom 1 hi India 2 hi US Am i missing any thing or is there anyway to achieve above result. Thanks in advance.
answer count: 1
favorite count: 0
upvote count: 2

http://stackoverflow.com/q/51630434
has comment: http://stackoverflow.com/comment/90225195
has title: How can I input the formula and get the result?
has answer: http://stackoverflow.com/a/51630921
tagged with: python
duplicate of: http://stackoverflow.com/q/2371436
has comment: http://stackoverflow.com/comment/90225805
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90225116
has body: What I want to do is to input a formula, like 1+1, and print: The Answer of question n is : (The answer of the formula). For 1+1, it should print: The Answer of Question 1 is: 2 But what I get is, when I input 1+1, it prints: The Answer of Question 1 is: '1+1' def prefix(): typein=int(input("How many questions do you want to ask:")) number=1 while number&lt;typein+1: a=input("Question %r you want to ask"%(number)) print(a) print("The Answer of Question %r is: %r" %(number,a)) number+=1 prefix() When I add print(a) after a=input("Question %r you want to ask"%(number)) It shows that a is 1+1, not 2. So how can I let a become the answer of the formula but not the formula itself? --------------------------Edit----------------------- It asks people to input an int ,and some formulas. There is no problem for us to input an int for the first part of the code. But for the second part of the code, which asks as to input the formula, it comes wrong.
type: Question
has comment: http://stackoverflow.com/comment/90225422
accepted answer: http://stackoverflow.com/a/51630921
linked to: http://stackoverflow.com/q/2371436
score: 0
answer count: 1

http://stackoverflow.com/comment/89971031
type: Comment
comment on: http://stackoverflow.com/a/51493234
score: 3
type: AnswerComment
has text: I am getting `No Reverse match` error. I am using `Model.__meta.app_label` value for `applabel` and for `modelname` the actual model name in lowercase. I wrote `download-file` just like you did. Did I miss something?

http://stackoverflow.com/comment/89955816
score: 1
comment on: http://stackoverflow.com/a/51493675
type: AnswerComment
type: Comment
has text: Thanks. I believe this will do.

http://stackoverflow.com/a/51505917
has body: Include len each element in the sort key slist.sort(key=lambda x: (sequence.find(x), len(x)))
upvote count: 6
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51505875
answers question: http://stackoverflow.com/q/51505875
type: Answer
downvote count: 0
score: 6

http://stackoverflow.com/a/76809740
type: Answer
has comment: http://stackoverflow.com/comment/135411079
has body: Since the C++ function fooc() is running through Python's foop() and the C++ code itself is not directly accessible from Python, it is challenging to directly interrupt the C++ code using Python's signal handling mechanisms. import multiprocessing import time # C++ function wrapped by foop() def fooc(): time.sleep(10) # Simulate a long-running C++ computation (10 seconds) return "Done" # Wrapper function to run fooc() with a timeout def foop_with_timeout(timeout=5): result_queue = multiprocessing.Queue() def fooc_wrapper(queue): try: result = fooc() queue.put(result) except Exception as e: queue.put(e) process = multiprocessing.Process(target=fooc_wrapper, args=(result_queue,)) process.start() process.join(timeout) if process.is_alive(): process.terminate() process.join() return None # Return None if the timeout was reached result = result_queue.get() if isinstance(result, Exception): raise result return result if __name__ == "__main__": try: result = foop_with_timeout(5) if result is None: print("Function timed out.") else: print("Result:", result) except Exception as e: print("An error occurred:", e)
answers question: http://stackoverflow.com/q/51547126
score: 0

http://stackoverflow.com/comment/90198715
type: QuestionComment
has text: Of course that's where the error is. That's where you call your function. What's the actual error? Post a traceback
comment on: http://stackoverflow.com/q/51616550
score: 0
type: Comment

http://stackoverflow.com/a/51577968
has comment: http://stackoverflow.com/comment/90121612
has comment: http://stackoverflow.com/comment/90121562
has comment: http://stackoverflow.com/comment/90122450
has comment: http://stackoverflow.com/comment/90123154
answers question: http://stackoverflow.com/q/51577885
score: 0
accepted answer of: http://stackoverflow.com/q/51577885
has comment: http://stackoverflow.com/comment/90123190
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90122330
type: Answer
has body: Your np arrays are converted to lists when storing the dataframe as a .json. To feed them to your Keras model, you need to have them in one array of shape (images, height, width, channels): X_train = np.array(train['images'].tolist())

http://stackoverflow.com/comment/89959909
score: 0
has text: @JON,Can you please check the answer timeline?
type: Comment
comment on: http://stackoverflow.com/a/51494622
type: AnswerComment

http://stackoverflow.com/comment/90028847
score: 0
has text: Are the other portions of the filename constant? i.e. they always begin with `tx` and end with `.data`?
type: Comment
comment on: http://stackoverflow.com/q/51530358
type: QuestionComment

http://stackoverflow.com/a/51585911
has comment: http://stackoverflow.com/comment/90141628
has comment: http://stackoverflow.com/comment/90153111
answers question: http://stackoverflow.com/q/51585881
has comment: http://stackoverflow.com/comment/90140780
upvote count: 3
downvote count: 1
has body: In your child template add this to the top {% extends 'base.html' %} This will allow you to "inherit" the context variable. Alternatively, if you only want to pass say just the user data to the template, you could do the following in your base.html {% include 'header.html' with my_user=user %} This answer summarises the differences between extend and include functionality quite well. Edit: In response to your comments and updated question, you aren't accessing the user object correctly. To do so you must use {{ request.user }}. This is because there is a context processor that passes the user object to every template. As an aside, if you were to explicitly send the user from the view, you could then access the user with {{ user }} as you have done. However, this is obviously quite unnecessary.
type: Answer
has comment: http://stackoverflow.com/comment/90141786
has comment: http://stackoverflow.com/comment/90139880
score: 2

http://stackoverflow.com/a/51600017
score: 0
answers question: http://stackoverflow.com/q/51599750
type: Answer
has body: I created a generator, which takes one argument, an iterable and yields values that are within range of min, max of this iterable. The product is computed as usual: from itertools import chain def values(iterable): lst = list(int(i) for i in chain.from_iterable(i.split() for i in n)) _min, _max = min(lst), max(lst) for i in lst: if _min &lt; i &lt; _max: yield i n = ['7 5 -1 3 9', '3 14 -9 4 -5 1 -12 4', '-5 1 2 3 4 5 6 7 8 -3'] p = 1 for i in values(n): p *= i print(p) Output: -1234517760000

visualization
tags question: http://stackoverflow.com/q/51627530
tags question: http://stackoverflow.com/q/51522500
tag name: visualization
tags question: http://stackoverflow.com/q/51549344
tags question: http://stackoverflow.com/q/51588717
tags question: http://stackoverflow.com/q/51629256
tags question: http://stackoverflow.com/q/51637646
tags question: http://stackoverflow.com/q/51524969
type: Tag
tags question: http://stackoverflow.com/q/51495927

http://stackoverflow.com/a/51499751
has body: Unless the bot has the user in a mutual server or the DM function is placed before the actual bot.ban, you won't be able to send the DM to the user.
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51491883
accepted answer of: http://stackoverflow.com/q/51491883

http://stackoverflow.com/comment/89939675
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51485285
score: 0
has text: Whenever a program is running and the user presses Ctrl+C, a `KeyboardInterrupt` is raised. Try this in a Python IDE: `while True: print(1)`. Press enter, wait a few seconds, then press Ctrl+C and see what happens.

http://stackoverflow.com/comment/89978215
type: QuestionComment
comment on: http://stackoverflow.com/q/51504535
score: 0
has text: I have normalized the entire data before splitting into test and train sets. I have a definition created in which the user can enter specific values for the columns used for testing and training. I then want to do the .predict() and the same for the probability on the user inputted data. The only issue is that data that the user entered is not in the scale of 0-1 like the data being used to train and test. I feel that this would lead to very bad performance of my model if the features are completely different. I am using XGBoost as my classifier if that helps.
type: Comment

http://stackoverflow.com/q/51488681
has title: pandas query with a column consisting of array entries
tagged with: dataframe
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51488727
downvote count: 0
linked to: http://stackoverflow.com/q/40374384
favorite count: 0
tagged with: series
has answer: http://stackoverflow.com/a/51489007
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89946337
tagged with: python
has answer: http://stackoverflow.com/a/51488927
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/89946251
type: Question
has body: ykp.data Out[182]: state action reward 0 [41] 5 59 1 [5] 52 48 2 [46] 35 59 3 [42] 16 12 4 [43] 37 48 5 [36] 5 59 6 [49] 52 48 7 [39] 11 23 I would like to find the row that matches [42] in the state entry so I ran ykp.data.query('state == [42]') but I get Empty DataFrame Columns: [state, action, reward] Index: [] when I should be seeing [42], 16, 12. Can someone please tell me how I can workaround this? I need my state-values to be stored as arrays.

http://stackoverflow.com/q/51520410
tagged with: python
score: 11
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51520512
tagged with: dataframe
linked to: http://stackoverflow.com/q/24475094
type: Question
answer count: 2
upvote count: 11
tagged with: linear-algebra
possible better answer: http://stackoverflow.com/a/51520512
tagged with: pandas
has answer: http://stackoverflow.com/a/51520449
accepted answer: http://stackoverflow.com/a/51520449
has body: Given a pandas Series with an index: import pandas as pd s = pd.Series(data=[1,2,3],index=['a','b','c']) How can a Series be used to fill the diagonal entries of an empty DataFrame in pandas version >= 0.23.0? The resulting DataFrame would look like: a b c a 1 0 0 b 0 2 0 c 0 0 3 There is a prior similar question which will fill the diagonal with the same value, my question is asking to fill the diagonal with varying values from a Series. Thank you in advance for your consideration and response.
has title: Fill the diagonal of Pandas DataFrame with elements from Pandas Series
favorite count: 0
tagged with: python-3.x
downvote count: 0

http://stackoverflow.com/q/51488156
type: Question
score: 0
tagged with: elementtree
has comment: http://stackoverflow.com/comment/89945790
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89945734
has comment: http://stackoverflow.com/comment/89945387
answer count: 0
has body: Using POST request i recieve this one respond <?xml version="1.0" encoding="UTF-8"?> description description description description description description description description Here is code of request: my_request = urllib2.Request(url, message) response_xml = urllib2.urlopen(my_request) my_response = response_xml.read() Then i convert string to dictionary: def etree_to_dict(t): d = {t.tag: {} if t.attrib else None} children = list(t) if children: dd = defaultdict(list) for dc in map(etree_to_dict, children): for k, v in dc.iteritems(): dd[k].append(v) d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.iteritems()}} if t.attrib: d[t.tag].update(('@' + k, v) for k, v in t.attrib.iteritems()) if t.text: text = t.text.strip() if children or t.attrib: if text: d[t.tag]['#text'] = text else: d[t.tag] = text return d my_result = ET.fromstring(my_response.decode('ascii', 'ignore')) d = globalvars.etree_to_dict(my_result) Then i try to save some data from dictionary to data base. When i try to save name="accom1", everythig works fine: my_data=d['response']['accommodations']['accommodation'] for n in my_data.get('accommodation'): p = XMLData( name = n.get('@name') ) But when i try to save board name, i've got an error: list indices must be integers, not str my_data=d['response']['accommodations']['accommodation']['concepts'] for n in my_data: p = XMLData( board = n['@name'] ) I don't get why does it happen. Can you help me with it? Thanks a lot.
has title: 'list indices must be integers, not str' after converting string to dictionary

http://stackoverflow.com/comment/90027653
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51529619
has text: `data.apply(lambda x: ci_lower_bound(x['won_A'], x['lost_A']))`

http://stackoverflow.com/q/51594501
has answer: http://stackoverflow.com/a/51594774
accepted answer: http://stackoverflow.com/a/51594774
has body: I have a a Dataframe with two columns and I want to set each of the columns median value to zero. How can i do this without changing the standard deviation ? Or better is this the right way to do that ? suppose I have: df = pd.DataFrame(np.random.randn(100, 2)) #first column df0=df[0] #set median to zero test=abs(df0-df.median()) Since I again looked for test.median() it is printing me not zero but a different value as above. Do I have a mistake in thought?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90155091
type: Question
has comment: http://stackoverflow.com/comment/90155066
tagged with: dataframe
tagged with: statistics
has title: set median of a column to zero pandas Dataframe
possible better answer: http://stackoverflow.com/a/51594770
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51594770

http://stackoverflow.com/comment/90101763
type: Comment
has text: and that I write to you in the init file?
comment on: http://stackoverflow.com/a/51567669
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92151123
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51604125
score: 0
has text: What version of Whoosh was the index created with? Before 2.5 it would also save and load field caches, which could be very big.

http://stackoverflow.com/comment/90009012
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51520082
has text: which version of pip are you using?

http://stackoverflow.com/a/51570738
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: In essence, you are repeating or chaining values according to your column. So you can use np.repeat and itertools.chain as appropriate. The solution is efficient for a small number of columns, as in your example. import numpy as np from itertools import chain # set up dataframe df = pd.DataFrame({'from': ['abc', 'def', 'gfhi'], 'to': ['xyz', 'uvw', 'rst'], 'obj': [['foo', 'bar'], ['gee'], ['foo', 'bar', 'baz']]}) # calculate length of each list in obj lens = df['obj'].map(len) # calculate result, repeating or chaining as appropriate res = pd.DataFrame({'from': np.repeat(df['from'], lens), 'to': np.repeat(df['to'], lens), 'obj': list(chain.from_iterable(df['obj']))}) print(res) from to obj 0 abc xyz foo 0 abc xyz bar 1 def uvw gee 2 gfhi rst foo 2 gfhi rst bar 2 gfhi rst baz
has comment: http://stackoverflow.com/comment/90115767
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51570474
answers question: http://stackoverflow.com/q/51570474

http://stackoverflow.com/a/51574362
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51574243
has body: Try this: html = s.get('http://example-site/forauthorizedusers.html', auth=HTTPBasicAuth('admin', 'password'), headers={'User-Agent': 'Mozilla/5.0'}) http://docs.python-requests.org/en/master/user/authentication/

http://stackoverflow.com/comment/111127905
type: Comment
type: AnswerComment
has text: Bizarrely, I couldn't get the example to work at all by bypassing the .env file. I just put the token in the script as a string. and it didn't like it as it had none of the string attributes or methods like strip().
comment on: http://stackoverflow.com/a/60983697
score: 0

http://stackoverflow.com/q/51639041
type: Question
has title: Running a shell script from Python which requires user input
has body: I have a shell command which needs some user confirmation from stdin like below support@vrni-platform:/tmp$ patronictl -c /etc/patroni/patroni.yml remove arkin +---------+--------+------+------+-------+-----------+ | Cluster | Member | Host | Role | State | Lag in MB | +---------+--------+------+------+-------+-----------+ +---------+--------+------+------+-------+-----------+ Please confirm the cluster name to remove: arkin You are about to remove all information in DCS for arkin, please type: "Yes I am aware": Yes I am aware The last two lines require user input. Can someone let me know how can I automate the above using Python 2.7 which requires no user input?
has comment: http://stackoverflow.com/comment/90242676
tagged with: python-2.7
score: 0
linked to: http://stackoverflow.com/q/37116442
tagged with: python
has comment: http://stackoverflow.com/comment/90242647
answer count: 0
duplicate of: http://stackoverflow.com/q/37116442
type: UnansweredQuestion

http://stackoverflow.com/q/51623246
tagged with: django-urls
has comment: http://stackoverflow.com/comment/90211812
type: Question
has body: I'm a noob in django and i watched some tutorial but I ran into an error that I can't really fix, and just here to ask if anyone can help me out. I'm using mac with bash, python 3.7.0, sublime text, and the tutorial is in youtube, I really need someone who could solve this problem for me thanks Performing system checks... Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x10ed24378&gt;Traceback (most recent call last): File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors=check(app_configs=app_configs) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/urls/resolvers.py", line 399, in check for pattern in self.url_patterns: File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__ res=instance.__dict__[self.name]=self.func(instance) File "/Users/evangui88/Dev/trydjango/lib/python3.7/site-packages/django/urls/resolvers.py", line 540, in url_patterns patterns…
score: 0
possible better answer: http://stackoverflow.com/a/51646657
tagged with: importerror
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51646657
downvote count: 1
favorite count: 0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51623410
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51623410
has title: Can some one help me on django with this ImportError: cannot import name 'product_detial_view' from 'products.views'

http://stackoverflow.com/q/51495087
tagged with: web-crawler
type: Question
has title: how to rename the crawler file with the search keyword in python icrawler
tagged with: google-image-search
has body: I am using crawler to download some images from google, but I find the download files are named with 000001.jpg, 000002.jpg. But what I except is that when the image downloads and at the same time change its name to the keyword(such as Coláiste Íosagáin,jpg, Mount Anville Secondary School.jpg, St Laurence College.jpg) from icrawler.builtin import GoogleImageCrawler google_crawler = GoogleImageCrawler( parser_threads=2, downloader_threads=4, storage={'root_dir': 'images'}) for keyword in ['Coláiste Íosagáin', 'Mount Anville Secondary School', 'St Laurence College']: google_crawler.crawl( keyword=keyword, max_num=1, min_size=(800, 800), max_size=(1200, 1200))
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59252511
tagged with: python
score: 1
upvote count: 1
tagged with: web-scraping

http://stackoverflow.com/a/51516845
has comment: http://stackoverflow.com/comment/90003160
type: Answer
answers question: http://stackoverflow.com/q/51516684
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90003594
has comment: http://stackoverflow.com/comment/90003038
upvote count: 2
has body: I'd advise against using chr. Ascii can be confusing, instead just use a string of all capital ascii characters (which is a sequence of characters, and can be handily found in the string module). import string def contalpha(n): for i in range(n, 0, -1): print(*string.ascii_uppercase[:i], sep=' ') contalpha(5) outputs: A B C D E A B C D A B C A B A

pygobject
type: Tag
tags question: http://stackoverflow.com/q/51485852
tag name: pygobject

http://stackoverflow.com/comment/90121612
type: AnswerComment
score: 0
type: Comment
has text: You are right. Try: `X_train = np.array(train['images'].tolist())`. I will edit my answer.
comment on: http://stackoverflow.com/a/51577968

http://stackoverflow.com/q/51571121
score: 2
tagged with: dataframe
has title: How to select rows which values start and end with a specific value in pandas?
type: Question
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51571209
tagged with: series
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/51571209
tagged with: python
favorite count: 0
has body: I have a pandas DataFrame, and I want to select rows which values start and end with a specific value. For example, in dataFrame df, I want to select rows that column state start and end with 1. That is row 2 5 8 10. and output two dataframes. import pandas as pd data = [['a1',0,'low'], ['a1',0,'low'], ['a1',1,'high'], ['a1',1,'low'], ['a1',1,'low'], ['a1',1,'high'], ['a1',0,'low'], ['a1',0,'low'], ['a2',1,'high'], ['a2',1,'low'], ['a2',1,'low'], ['a2',0,'low'], ['a2',0,'low']] df = pd.DataFrame(data,columns=['id','state','type']) df out : id state type 0 a1 0 low 1 a1 0 low 2 a1 1 high 3 a1 1 low 4 a1 1 low 5 a1 1 high 6 a1 0 low 7 a1 0 low 8 a2 1 high 9 a2 1 low 10 a2 1 low 11 a2 0 low 12 a2 0 low Finally, I want two dataframes, like this: df1 id state type code 2 a1 1 high start 8 a2 1 high start df2 id state type code 5 a1 1 high end 10 a2 1 low end
tagged with: indexing
type: AnsweredQuestion

http://stackoverflow.com/comment/90226048
comment on: http://stackoverflow.com/q/51630858
score: 0
type: Comment
type: QuestionComment
has text: you can, by simply first constructing an object, and then passing it with `instance=my_object` in the `Form`.

http://stackoverflow.com/a/51548326
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51548198
type: Answer
upvote count: 1
has body: In [114]: df['t+1'] = df['Speed'].shift(-1) # NOTE: ^ ^ In [115]: df Out[115]: date wind_P Speed t t+1 0 2012-01-01 01:00:00 0.000000 0.000000 0 2.252262 1 2012-01-01 02:00:00 0.034542 2.252262 1 1.440785 2 2012-01-01 03:00:00 0.020621 1.440785 2 0.991745 3 2012-01-01 04:00:00 0.001867 0.991745 3 0.711795 4 2012-01-01 05:00:00 0.015174 0.711795 4 0.928245 5 2012-01-01 06:00:00 0.012905 0.928245 5 1.677769 6 2012-01-01 07:00:00 0.022311 1.677769 6 2.963995 7 2012-01-01 08:00:00 0.014925 2.963995 7 5.062572 8 2012-01-01 09:00:00 0.096465 5.062572 8 7.065042 9 2012-01-01 10:00:00 0.284445 7.065042 9 NaN
answers question: http://stackoverflow.com/q/51548198
score: 1
has comment: http://stackoverflow.com/comment/90064483
type: AcceptedAnswer

http://stackoverflow.com/q/51636753
linked to: http://stackoverflow.com/q/16486252
tagged with: pandas
has answer: http://stackoverflow.com/a/51637043
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90237906
has title: How to sort strings with numbers in Pandas?
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51637043
linked to: http://stackoverflow.com/q/13838405
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/90238057
linked to: http://stackoverflow.com/q/23279238
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51636938
tagged with: sorting
score: 4
has answer: http://stackoverflow.com/a/51636938
has body: I have a Python Pandas Dataframe, in which a column named status contains three kinds of possible values: ok, must read x more books, does not read any books yet, where x is an integer higher than 0. I want to sort status values according to the order above. Example: name status 0 Paul ok 1 Jean must read 1 more books 2 Robert must read 2 more books 3 John does not read any book yet I've found some interesting hints, using Pandas Categorical and map but I don't know how to deal with variable values modifying strings. How can I achieve that?

http://stackoverflow.com/a/51506779
score: 0
has comment: http://stackoverflow.com/comment/89984259
answers question: http://stackoverflow.com/q/51506656
type: Answer
has comment: http://stackoverflow.com/comment/89983200
has body: This should work for you st='**Amount** : $25k **Name** : James' stage1=re.sub(r"\**","",st) re.sub(r'(?&lt;=\:\s\S\S\S\S\s)',",",stage1) The output will be 'Amount : $25k , Name : James' to match regex you must look at the online regex testers like this one

http://stackoverflow.com/comment/90016863
score: 0
type: Comment
type: QuestionComment
has text: Again, why are you not actually using `b` for anything?
comment on: http://stackoverflow.com/q/51523938

http://stackoverflow.com/comment/90142707
score: 0
has text: I want to build the forest dynamically in a file not dump a ready forest
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51588326

tuples
tags question: http://stackoverflow.com/q/51501469
tags question: http://stackoverflow.com/q/51623355
tags question: http://stackoverflow.com/q/51592889
tags question: http://stackoverflow.com/q/51567059
tags question: http://stackoverflow.com/q/51583820
tags question: http://stackoverflow.com/q/51604147
tags question: http://stackoverflow.com/q/51484967
tag name: tuples
tags question: http://stackoverflow.com/q/51613105
tags question: http://stackoverflow.com/q/51627134
tags question: http://stackoverflow.com/q/51527379
tags question: http://stackoverflow.com/q/51522685
tags question: http://stackoverflow.com/q/51523380
tags question: http://stackoverflow.com/q/51540399
tags question: http://stackoverflow.com/q/51500633
type: Tag
tags question: http://stackoverflow.com/q/51484937

http://stackoverflow.com/q/51611963
has comment: http://stackoverflow.com/comment/90189127
has comment: http://stackoverflow.com/comment/90189635
type: AnsweredQuestion
tagged with: selenium
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/90189171
has title: Scraping using Selenium and python
type: Question
has comment: http://stackoverflow.com/comment/90189256
has answer: http://stackoverflow.com/a/51619205
has comment: http://stackoverflow.com/comment/90188958
linked to: http://stackoverflow.com/q/52332877
score: 0
has comment: http://stackoverflow.com/comment/90191919
answer count: 1
has body: I am trying to get numbers such as 14,401. I tried something like WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='wiz-iframe-intent']"))) WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="highcharts-5tawcvw-0"]/svg/g[8]/g[1]/text/tspan[1]'))).text getting TimeOut Exception.
linked to: http://stackoverflow.com/q/41829000
favorite count: 0
accepted answer: http://stackoverflow.com/a/51619205
upvote count: 2
downvote count: 2
tagged with: python

http://stackoverflow.com/q/51560617
has body: I can't import tensorflow in pycharm, it raises the following error: ImportError: Could not find 'cudart64_90.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Download and install CUDA 9.0 from this URL: https://developer.nvidia.com/cuda-toolkit I checked this cudart file and its added in %PATH% It is working on CLI and python shell perfectly. I have CUDA v9.0 cuDNN v7.0.5 tensorflow-gpu v1.9 echo %PATH% C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin; C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\libnvvp; C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\extras\CUPTI\libx64; Directory of cudar64_90.dll: 07/27/2018 02:53 PM &lt;DIR&gt; . 07/27/2018 02:53 PM &lt;DIR&gt; .. 09/02/2017 03:45 PM 163,840 bin2c.exe 07/27/2018 02:28 PM &lt;DIR&gt; crt 05/16/2018 11:18 PM 55,161,856 cublas64_90.dll 09/02/2017 03:45 PM 347,136 cuda-memcheck.exe 09/02/2017 03:45 PM 3,930,112 cudafe++.exe 09/02/2017 03:45 PM 4,226,048 cudafe.exe 09/02/2017 03:46 PM 299,520 cudart32_90.dll 09/02/2017 03:46 PM 373,760 cudart64_90.dll 11/16/2017 07:51 PM 286,877,184 cudnn64_7.dll 09/02/2017 03:46 PM 131,197,952 cufft64_90.dll 09/02/2017 03:46 PM 199,680 cufftw64_90.dll 09/02/2017 03:46 PM 3,575,808 cuinj32_90.dll 09/02/2017 03:46 PM 4,495,360 cuinj64_90.dll 09/02/2017 03:45 PM 1,411,072 cuobjdump.exe 09/02/2017 03:46 PM 48,057,344 curand64_90.dll 09/02/2017 03:46 PM 75,222,016 cusolver64_90.dll 09/02/2017 03:46 PM 54,782,464 cusparse64_90.dll 09/02/2017 03:45 PM 246,784 fatbinary.exe 09/02/2017 03:46 PM 1,274,880 gpu-library-advisor.exe 09/02/2017 03:46 PM 205,824 nppc64_90.dll 09/02/2017 03:46 PM 9,744,384 nppial64_90.dll 09/02/2017 03:46 PM 3,953,664 nppicc64_90.dll 09/02/2017 03:46 PM 1,035,264 nppicom64_90.dll 09/02/2017 03:46 PM 7,291,392 nppidei64_90.dll 09/02/2017 03:46 PM 55,641,088 nppif64_90.dll 09/02/2017 03:46 PM 26,491,904 nppig64_90.dll 09/02/2017 03:46 PM 4,767,232 nppim64_90.dll 09/02…
tagged with: tensorflow
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/90089019
has comment: http://stackoverflow.com/comment/90088993
has comment: http://stackoverflow.com/comment/90089659
answer count: 1
tagged with: python
tagged with: cudnn
favorite count: 0
tagged with: pycharm
accepted answer: http://stackoverflow.com/a/51561508
has title: Tensorflow-gpu 1.9 is not working on Pycharm
has comment: http://stackoverflow.com/comment/90088545
type: AnsweredQuestion
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90089593
has answer: http://stackoverflow.com/a/51561508

http://stackoverflow.com/comment/90177236
has text: thanks @arnt for help
score: 0
comment on: http://stackoverflow.com/q/51596061
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51620874
has body: Here is one way: &gt;&gt;&gt; l = [['a', 10, 'b'], ['c', -2, 'd'], ['e', 5, 'f']] &gt;&gt;&gt; sorted(l, key=lambda sublist: abs(sublist[1])) [['c', -2, 'd'], ['e', 5, 'f'], ['a', 10, 'b']]
upvote count: 2
has comment: http://stackoverflow.com/comment/90307396
type: Answer
answers question: http://stackoverflow.com/q/51620828
score: 2
downvote count: 0

http://stackoverflow.com/q/51517905
tagged with: mongodb
has body: When requesting data from Pythons MongoClient (with connection to the same database and requesting from the same collection) i get less in my result (with or without filtering) for example requesting db.collection.find({}) in the shell gives me 12 results and the same query in pymongo gives me 8, with 4 missing, using filtering i get one result instead of 4 (for those missing) Are anyone else having troubles with pythons mongoclient? when running (in shell) db.test.find() i get the result { "_id" : ObjectId("5b581e4bd8624400b4138044"), "account" : "1234", "job_id" : ObjectId("5b473177310ea1023a4f434f"), "start" : false, "tag" : "hello", "time" : ISODate("2018-07-25T22:00:58.780Z") } { "_id" : ObjectId("5b581e4bd8624400b4138045"), "account" : "12345", "job_id" : ObjectId("5b3f36df42db3e021a3b2689"), "start" : false, "tag" : "hello", "time" : ISODate("2018-07-25T22:00:58.929Z") } { "_id" : ObjectId("5b581e4bd8624400b4138046"), "account" : "32124", "job_id" : ObjectId("5b43bf9a51dac70058ffa43c"), "start" : false, "tag" : "hello", "time" : ISODate("2018-07-25T22:00:58.856Z") } { "_id" : ObjectId("5b581e4bd8624400b4138047"), "account" : "44112", "job_id" : ObjectId("5b4a464c94e89c00cb61d001"), "start" : false, "tag" : "hello", "time" : ISODate("2018-07-26T04:00:58.803Z") } { "_id" : ObjectId("5b581e4bd8624400b4138049"), "account" : "44115", "job_id" : ObjectId("5b56d464d862440046ccf1fa"), "start" : false, "tag" : "hello", "time" : ISODate("2018-07-25T22:00:58.764Z") } { "_id" : ObjectId("5b581e4bd8624400b413804a"), "account" : "414141", "job_id" : ObjectId("5b473ea7310ea10827c4886b"), "start" : false, "tag" : "hello", "time" : ISODate("2018-07-25T22:00:58.986Z") } { "_id" : ObjectId("5b58623a89ca2c00755e12d7"), "account" : "444444", "job_id" : ObjectId("5b58623989ca2c00b695283f"), "area" : "238428477", "start" : false, "tag" : "nice", "time" : ISODate("2018-07-25T22:00:50.009Z") } { "_id" : ObjectId("5b58624189ca2c00755e12da"), "account" : "444444", "job_id" : ObjectId("…
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/90007148
has comment: http://stackoverflow.com/comment/90005725
type: UnansweredQuestion
tagged with: python
has title: Pymongo Client find not working properly
answer count: 0
tagged with: pymongo
tagged with: pymongo-3.x
type: Question
has comment: http://stackoverflow.com/comment/90004791
has comment: http://stackoverflow.com/comment/90004364

http://stackoverflow.com/comment/89957418
type: QuestionComment
has text: You can try to apply some morphological process to be able to make the tails more visible. For example, apply dilation process after you find the edges, so that maybe it may join the small patches of the tail
type: Comment
comment on: http://stackoverflow.com/q/51491771
score: 0

http://stackoverflow.com/comment/90140811
type: QuestionComment
comment on: http://stackoverflow.com/q/51587601
type: Comment
score: 1
has text: @jezrael I agree that, while the linked answer may be used to answer the OP, a complete answer requires more bits and pieces than the linked one.

http://stackoverflow.com/comment/90162365
comment on: http://stackoverflow.com/q/51597984
has text: Could you please concentrate on one question and provide [MVCE](https://stackoverflow.com/help/mcve)?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/51512306
type: Tag
tags question: http://stackoverflow.com/q/51549448
tags question: http://stackoverflow.com/q/51537931
tags question: http://stackoverflow.com/q/51506165
tags question: http://stackoverflow.com/q/51486125
tags question: http://stackoverflow.com/q/51564391
tags question: http://stackoverflow.com/q/51591705
tags question: http://stackoverflow.com/q/51567135
tags question: http://stackoverflow.com/q/51624803
tags question: http://stackoverflow.com/q/51601709
tags question: http://stackoverflow.com/q/51497299
tags question: http://stackoverflow.com/q/51632283
tags question: http://stackoverflow.com/q/51637301
tags question: http://stackoverflow.com/q/51574995
tag name: csv
tags question: http://stackoverflow.com/q/51508274
tags question: http://stackoverflow.com/q/51632848
tags question: http://stackoverflow.com/q/51584192
tags question: http://stackoverflow.com/q/51584754
tags question: http://stackoverflow.com/q/51601140
tags question: http://stackoverflow.com/q/51635981
tags question: http://stackoverflow.com/q/51566284
tags question: http://stackoverflow.com/q/51501389
tags question: http://stackoverflow.com/q/51499948
tags question: http://stackoverflow.com/q/51486227
tags question: http://stackoverflow.com/q/51616001
tags question: http://stackoverflow.com/q/51546624
tags question: http://stackoverflow.com/q/51494558
tags question: http://stackoverflow.com/q/51571615
tags question: http://stackoverflow.com/q/51487332
tags question: http://stackoverflow.com/q/51620367
tags question: http://stackoverflow.com/q/51501469
tags question: http://stackoverflow.com/q/51483375
tags question: http://stackoverflow.com/q/51605154
tags question: http://stackoverflow.com/q/51615916
tags question: http://stackoverflow.com/q/51503490
tags question: http://stackoverflow.com/q/51631439
tags question: http://stackoverflow.com/q/51556281
tags question: http://stackoverflow.com/q/51635417
tags question: http://stackoverflow.com/q/51544953
tags question: http://stackoverflow.com/q/51556188
tags question: http://stackoverflow.com/q/51623539
tags question: http://stackoverflow.com/q/51598801
tags question: http://stackoverflow.com/q/51597416
tags question: http://stackoverflow.com/q/51542959
tags question: http://stackoverflow.com/q/51597979
tags question: http://stackoverflow.com/q/51563673
tags question: http://stackoverflow.com/q/51620278
tags question: http://stackoverflow.com/q/51522375
tags question: http://stackoverflow.com/q/51539204
tags question: http://stackoverflow.com/q/51555643
tags question: http://stackoverflow.com/q/51634368
tags question: http://stackoverflow.com/q/51490693
tags question: http://stackoverflow.com/q/51504958
tags question: http://stackoverflow.com/q/51585272
tags question: http://stackoverflow.com/q/51498790
tags question: http://stackoverflow.com/q/51574431
tags question: http://stackoverflow.com/q/51548902
tags question: http://stackoverflow.com/q/51493116
tags question: http://stackoverflow.com/q/51496215
tags question: http://stackoverflow.com/q/51489128
tags question: http://stackoverflow.com/q/51586207
tags question: http://stackoverflow.com/q/51571530
tags question: http://stackoverflow.com/q/51493842
tags question: http://stackoverflow.com/q/51608043
tags question: http://stackoverflow.com/q/51483217
tags question: http://stackoverflow.com/q/51603442
tags question: http://stackoverflow.com/q/51515902
tags question: http://stackoverflow.com/q/51639170
tags question: http://stackoverflow.com/q/51558747
tags question: http://stackoverflow.com/q/51594084
tags question: http://stackoverflow.com/q/51564344
tags question: http://stackoverflow.com/q/51483396
tags question: http://stackoverflow.com/q/51491903
tags question: http://stackoverflow.com/q/51494322
tags question: http://stackoverflow.com/q/51567058
tags question: http://stackoverflow.com/q/51629009
tags question: http://stackoverflow.com/q/51538264
tags question: http://stackoverflow.com/q/51509196

http://stackoverflow.com/q/51621428
tagged with: list
tagged with: performance
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/90208537
answer count: 2
has answer: http://stackoverflow.com/a/51621655
accepted answer: http://stackoverflow.com/a/51621655
downvote count: 0
has body: I'm making a program which completes the following: When inputted a list a, it will subtract consecutive elements (starting from the beginning) if the results are non-negative numbers. For example, if a=[3,2,1] then consecutive numbers will be subtracted, so a=[1,1], and then a=[0]. Also, in the result, all numbers must be ascending (for example a 2,1 cannot be in the list). Another example: a=[1, 10, 7, 3, 2] [1, 3, 3, 2] #10-7 (10 and 7 get replaced with 3) [1, 0, 2] #3-3 (precedence goes to the left: 3-3 gets subtracted, not 3-2) [1, 2] #1-0 Here is my current code (where a is being generated randomly): import random a=[random.randint(1,10) for e in range(20)] print(a) loop=1 while True: try: #print(loop,a) subloop=0 while subloop&lt;loop: if a[loop-subloop]&lt;=a[loop-1-subloop]: a[loop-1-subloop]=a[loop-1-subloop]-a.pop(loop-subloop) if loop!=1: loop-=1 subloop+=1 if a[loop]&lt;=a[loop-1]: a[loop-1]=a[loop-1]-a.pop(loop) else: loop+=1 except IndexError: break print(a) This code feels kind of long/ineffiecient. Is there a better or more short/efficient way to do this?
upvote count: 2
possible better answer: http://stackoverflow.com/a/51622050
has comment: http://stackoverflow.com/comment/90208549
tagged with: subtraction
has title: Subtracting consecutive elements in a list when the first element is great than the next - Python
has comment: http://stackoverflow.com/comment/90208550
favorite count: 0
has comment: http://stackoverflow.com/comment/90208744
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51622050

http://stackoverflow.com/comment/90042312
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51537338
has text: Then you should clarify the question like "How to convert Matlab (x:y) into python". Besides, is the M1 a matrix?

http://stackoverflow.com/a/51483273
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51483214
upvote count: 3
has comment: http://stackoverflow.com/comment/89935668
has body: You're passing a single argument composed of all those characters. script_args = ['-a', 'test', ..., '23'] subprocess.Popen(['/home/pi/bash/bash_script.sh'] + script_args)
score: 3
answers question: http://stackoverflow.com/q/51483214
type: AcceptedAnswer

http://stackoverflow.com/a/51551491
type: Answer
score: 0
type: AcceptedAnswer
has body: Since there's no algorithmic difference between the two, the only way to answer this question is to test it. Of course it's hard to benchmark a program that includes an input, so first I timed how long it took me to type my desired sentence, then I replaced that with a constant assignment and a time.sleep(7.8). Both versions took well under 8 seconds. And most of the time outside the 7.8 seconds was spent in print. But, according to %timeit, version 1 was about 0.0005 seconds faster than version 2, for a speedup of about 0.006%. (By the way, you get more speedup than that changing from str.format to %.) I'm pretty sure almost all of the difference comes down to having more parameters to str.format, not to the difference between if statements and if expressions. But of course the details probably depend on your chosen Python implementation, and maybe your version and platform, and on what input string you give it, and, more than anything else, how fast you can type. So, if this 0.006% difference actually matters for something, you really need to test it yourself.
accepted answer of: http://stackoverflow.com/q/51550926
answers question: http://stackoverflow.com/q/51550926

http://stackoverflow.com/a/51507594
answers question: http://stackoverflow.com/q/51506025
has body: You are storing session value to fdata first_name__icontains = fdata instead of 'fdata' with quotation Another tip- use Q to concatinate query.
type: Answer
has comment: http://stackoverflow.com/comment/89985239
has comment: http://stackoverflow.com/comment/89993866
has comment: http://stackoverflow.com/comment/90070701
has comment: http://stackoverflow.com/comment/90013770
score: 0

http://stackoverflow.com/comment/90678616
comment on: http://stackoverflow.com/q/51633927
score: 0
type: Comment
has text: Why `shell=True`? It contradicts passing the `command` as list, and it's unnecessary to put a shell between your process and the one you start.
type: QuestionComment

http://stackoverflow.com/a/51528079
downvote count: 0
has body: IIUC l = [df for df in dfs if df.columns.size == 6] Then pd.concat(l)
type: Answer
answers question: http://stackoverflow.com/q/51528065
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51528065
type: AcceptedAnswer

http://stackoverflow.com/q/51584385
has answer: http://stackoverflow.com/a/51584643
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51584443
accepted answer: http://stackoverflow.com/a/51584443
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90134377
has comment: http://stackoverflow.com/comment/90134155
has comment: http://stackoverflow.com/comment/90134447
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Lift up all occurrences of a type in a nested dictionary to a top level key
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51584643
has body: I have a need in a project to find all of a given type in a nested dictionary and move them all to a top level key in the same dictionary. So far I have the below code, which seems to work. In the example I'm looking for all the items that are integers and moving them to a 'numbers' key. I'd prefer it if the lift_numbers_to_top function made and returned a copy of the dictionary rather than editing it in place, but I haven't been able to work out a nice way to pass the copy and the numbers back from the recursive function to itself, if that makes sense. a_dictionary = { "one": 1, "two": 2, "text": "Hello", "more_text": "Hi", "internal_dictionary": { "three": 3, "two": 2, "even_more_text": "Hey", "another_internal_dictionary": { "four": 4, "five": 5, "last_text": "howdy" } } } def extract_integers(dictionary, level_key=None): numbers = {} for key in dictionary: if type(dictionary[key]) == int: numbers[level_key + "__" + key if level_key else key] = dictionary[key] return numbers def lift_numbers_to_top(dictionary, level_key=None): numbers = {} if type(dictionary) == dict: numbers = extract_integers(dictionary, level_key) for key in numbers: keyNumber = key.split('__')[-1] del dictionary[keyNumber] for key in dictionary: numbers = {**numbers, **lift_numbers_to_top(dictionary[key], key)} return numbers a_dictionary['numbers'] = lift_numbers_to_top(a_dictionary) print(a_dictionary) Result: { 'text': 'Hello', 'more_text': 'Hi', 'internal_dictionary': { 'even_more_text': 'Hey', 'another_internal_dictionary': { 'last_text': 'howdy' }, }, 'numbers': { 'one': 1, 'two': 2, 'internal_dictionary__two': 2, 'internal_dictionary__three': 3, 'another_internal_dictionary__four': 4, 'another_internal_dictionary__five': 5, } }

http://stackoverflow.com/a/78664196
answers question: http://stackoverflow.com/q/51504144
score: 0
has body: I don't have enough reputation to comment, but for those who use the setUpTestData class method, switching to TransactionTestCase does not work. Somehow django just clears the database out so it results in failed test cases that used to work.. In that case you would need to use the setUp method instead.
type: Answer

http://stackoverflow.com/comment/90098930
type: AnswerComment
has text: The value is only printed after the figure is closed.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51559696

http://stackoverflow.com/q/51606284
has title: ImportError: cannot import name 'pybindIETFXMLEncoder'
type: UnansweredQuestion
tagged with: python
has body: I am new to Python, I am using pytest to run a test script. I don't know how to fix this. I have tried install pip install pyangbind it says - requirement already satisfied. I am kind of stuck what to do next. However, I am facing this issue - #pytest test.py Hint: make sure your test modules/packages have valid Python names. Traceback: test.py:12: in &lt;module&gt; from config.generator import NcConfig ../config/generator.py:4: in &lt;module&gt; from .base import PybBase ../config/base.py:9: in &lt;module&gt; from pyangbind.lib.serialise import pybindIETFXMLEncoder E ImportError: cannot import name 'pybindIETFXMLEncoder' The python freeze tells me - Here are the dependencies on my virtual py environ $pip freeze asn1crypto==0.24.0 atomicwrites==1.1.5 attrs==18.1.0 bcrypt==3.1.4 bitarray==0.8.3 certifi==2018.4.16 cffi==1.11.5 chardet==3.0.4 cryptography==2.3 defusedxml==0.5.0 enum34==1.1.6 idna==2.7 jira==1.0.15 lxml==4.2.3 more-itertools==4.2.0 ncclient==0.5.4 oauthlib==2.1.0 paramiko==2.4.1 pathlib2==2.3.2 pbr==4.0.4 pluggy==0.6.0 py==1.5.4 pyang==1.7.5 pyangbind==0.8.1 pyasn1==0.4.4 pycparser==2.18 PyNaCl==1.2.1 pytest==3.5.1 regex==2018.7.11 requests==2.19.0 requests-oauthlib==1.0.0 requests-toolbelt==0.8.0 six==1.11.0 tabulate==0.8.2 urllib3==1.23 The python version is 3.5.2. $python --version Python 3.5.2
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51606733

wkhtmltopdf
tags question: http://stackoverflow.com/q/51515397
tags question: http://stackoverflow.com/q/51539689
tags question: http://stackoverflow.com/q/51623424
type: Tag
tag name: wkhtmltopdf

http://stackoverflow.com/comment/90047008
type: Comment
type: QuestionComment
has text: The brackets in your example don't match, did you copy-paste everything?
comment on: http://stackoverflow.com/q/51535921
score: 0

pyodbc
tags question: http://stackoverflow.com/q/51561134
tags question: http://stackoverflow.com/q/51618170
tags question: http://stackoverflow.com/q/51633759
type: Tag
tags question: http://stackoverflow.com/q/51623732
tags question: http://stackoverflow.com/q/51617367
tags question: http://stackoverflow.com/q/51632243
tags question: http://stackoverflow.com/q/51633117
tags question: http://stackoverflow.com/q/51489632
tags question: http://stackoverflow.com/q/51500345
tag name: pyodbc

http://stackoverflow.com/a/51619225
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51619046
has body: I believe that format with = and 3D is called quoted printable. https://en.wikipedia.org/wiki/Quoted-printable You could try using quopri.decodestring(string). https://docs.python.org/2/library/quopri.html
answers question: http://stackoverflow.com/q/51619046
type: Answer

http://stackoverflow.com/q/51556188
has comment: http://stackoverflow.com/comment/90079089
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/5214578
has body: I'm new to Python and I'm trying to turn multiple csv files extracted form a relational database into a Json doc. I've found a code that turns a single csv into a json doc but I want to maintain the relationships in the csv files and structure my Json doc according to that import csv import json input_file = 'Test3.csv' output_file_template = 'Test.json' with open(input_file, 'r', encoding='utf8') as csvfile: reader = csv.DictReader(csvfile, delimiter=',') rows = list(reader) for i in range(len(rows)): out = json.dumps(rows[1*i:1*(i+1)]) with open(output_file_template.format(i), 'w') as f: f.write(out) CSV1 - Student details Studentid, Studentname, dob 001, Mark Johns, 21/04/2010 002, Jenny King, 20/01/2009 003, Steve Brown, 02/09/2010 CSV2- modules Moduleid, Modulename 01, Maths 02, Science 03, Art 04, Geometry CSV3 - class details classid, classname 01, Goldfish room 02, Hawkins room CSV4- timetable details moduleid1, classid, studentid 01, 01, 003 01, 01, 002 02, 02, 001 I want to write into json document in the structure below: "timetable details" "header":{ "moduleid":, "locationid" }, "body": { "moduleid", "Modules":{ "moduleid":, "modulename": }, "classid":, "class details":{ "classid":, "classname": }, "studentid", "studentdetails":{ "studentid":, "studnetname":, "dob": } }
has answer: http://stackoverflow.com/a/51556286
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/90082600
type: Question
has title: converting multiple csv files into a Json document using Python
score: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90079052
answer count: 1

mysql-connect
tag name: mysql-connect
type: Tag
tags question: http://stackoverflow.com/q/51590245

http://stackoverflow.com/a/55242243
has body: I encountered the same error. Since the code we were both running is from an introductory doc page on the robobrowser website that means that robobrowser is no longer maintained. I switched to mechanicalsoup. It is a Python module which works great and seems to be maintained (after a hiatus when it was not.) You can install it using pip. Plus, the syntax of mechanicalsoup is simpler. For instance, you don't have to use ".value" when setting form values. So my advice is to forget about robobrowser and switch to mechanicalsoup.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51543266

http://stackoverflow.com/comment/90063832
comment on: http://stackoverflow.com/a/51546925
type: Comment
type: AnswerComment
score: 0
has text: Sorry, a bit of a newb, but where am I supposed to put that code?

http://stackoverflow.com/comment/90023906
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51525462
has text: Thank you, I have the jquery script source in the header but it doesn't seem to work. I will try to figure it out. Regarding the googling, I would have googled it if I knew about the developer console that you told me about. Without the console, I had no idea what was going on. So, thank you twice.

http://stackoverflow.com/q/51566555
tagged with: python
linked to: http://stackoverflow.com/q/27754891
has comment: http://stackoverflow.com/comment/90133975
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51566765
has body: I have gone through all posts on the website and am not able to find solution to my problem. I have a dataframe with 15 columns. Some of them come with None or NaN values. I need help in writing the if-else condition. If the column in the dataframe is not null and nan, I need to format the datetime column. Current Code is as below for index, row in df_with_job_name.iterrows(): start_time=df_with_job_name.loc[index,'startTime'] if not df_with_job_name.isna(df_with_job_name.loc[index,'startTime']) : start_time_formatted = datetime(*map(int, re.split('[^\d]', start_time)[:-1])) The error that I am getting is if not df_with_job_name.isna(df_with_job_name.loc[index,'startTime']) : TypeError: isna() takes exactly 1 argument (2 given)
has title: Find if a column in dataframe has neither nan nor none
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51566761
tagged with: pandas

http://stackoverflow.com/q/51501517
upvote count: 1
score: 1
tagged with: pyspark
has body: How do I get a yarn application ID from within a mapper? It looks like I can get the CONTAINER_ID from an environment variable with the same name, and it looks like the format of the containerID is similar to the application ID, but it is not the same. Is there a better way to do this? &gt;&gt;&gt; sc.applicationId 'application_1531947999592_0024' &gt;&gt;&gt; sc.parallelize([1]).map(lambda v:os.environ['CONTAINER_ID']).collect() ['container_1531947999592_0024_01_000008'] &gt;&gt;&gt;
type: Question
downvote count: 0
favorite count: 0
tagged with: apache-spark
tagged with: python
has title: How do I get the YARN application ID from within a Mapper?
answer count: 0
type: UnansweredQuestion
tagged with: hadoop-yarn

qemu
tag name: qemu
type: Tag
tags question: http://stackoverflow.com/q/51606613

http://stackoverflow.com/comment/90208122
comment on: http://stackoverflow.com/q/51621281
has text: "I can't quite follow the documentation" - do you want us to read the documentation for you?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90394852
comment on: http://stackoverflow.com/q/51573298
has text: IIRC 0xC0000005 means access violation, but judging by the `quandl`s source code, it's pure python - are you sure it's `quandl` and not some dependency? Can you at least try `import numpy, pandas` first to see if those work?
type: Comment
type: QuestionComment
score: 0

python-babel
tags question: http://stackoverflow.com/q/51511222
type: Tag
tag name: python-babel

http://stackoverflow.com/a/51577223
downvote count: 5
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51576949
answers question: http://stackoverflow.com/q/51576949
has body: You seem to think that String messagetype = socketOutput.toString(); performs I/O. It doesn't, so printing it or even calling it does nothing and proves nothing. You need to read from the socket input stream. BTW clientSocket.isConnected() cannot possibly be false at the point you are testing it. If the connect had failed, an exception would have been thrown. Similarly, clientSocket.isClosed() cannot possibly be true at the point you are testing it, because you haven't closed the socket you just created. Further, if isClosed() was true it would not mean 'connection failed', and isConnected() being false does not entail isClosed() being true. Remove all this.
upvote count: 5

web-scraping
tags question: http://stackoverflow.com/q/51580869
tags question: http://stackoverflow.com/q/51513894
tags question: http://stackoverflow.com/q/51539989
tags question: http://stackoverflow.com/q/51539818
tags question: http://stackoverflow.com/q/51637310
tags question: http://stackoverflow.com/q/51613439
tags question: http://stackoverflow.com/q/51578683
tags question: http://stackoverflow.com/q/51599798
tags question: http://stackoverflow.com/q/51581264
tags question: http://stackoverflow.com/q/51591849
tags question: http://stackoverflow.com/q/51488486
tags question: http://stackoverflow.com/q/51598471
tags question: http://stackoverflow.com/q/51580190
tags question: http://stackoverflow.com/q/51517209
tags question: http://stackoverflow.com/q/51529482
tags question: http://stackoverflow.com/q/51527402
tags question: http://stackoverflow.com/q/51553467
tags question: http://stackoverflow.com/q/51623984
tags question: http://stackoverflow.com/q/51615479
tags question: http://stackoverflow.com/q/51575188
tags question: http://stackoverflow.com/q/51546730
tags question: http://stackoverflow.com/q/51552363
tags question: http://stackoverflow.com/q/51630571
tags question: http://stackoverflow.com/q/51495087
tags question: http://stackoverflow.com/q/51637504
tags question: http://stackoverflow.com/q/51528810
tags question: http://stackoverflow.com/q/51582031
tags question: http://stackoverflow.com/q/51520256
tags question: http://stackoverflow.com/q/51499962
tags question: http://stackoverflow.com/q/51609620
tags question: http://stackoverflow.com/q/51483171
tags question: http://stackoverflow.com/q/51491656
tags question: http://stackoverflow.com/q/51498133
tags question: http://stackoverflow.com/q/51572132
tags question: http://stackoverflow.com/q/51573673
tags question: http://stackoverflow.com/q/51507047
tags question: http://stackoverflow.com/q/51586003
tags question: http://stackoverflow.com/q/51507882
tags question: http://stackoverflow.com/q/51568732
tags question: http://stackoverflow.com/q/51522281
tags question: http://stackoverflow.com/q/51507558
tags question: http://stackoverflow.com/q/51527851
tags question: http://stackoverflow.com/q/51628695
tags question: http://stackoverflow.com/q/51590811
tag name: web-scraping
tags question: http://stackoverflow.com/q/51550838
tags question: http://stackoverflow.com/q/51638963
tags question: http://stackoverflow.com/q/51592114
tags question: http://stackoverflow.com/q/51533619
tags question: http://stackoverflow.com/q/51497107
tags question: http://stackoverflow.com/q/51508532
tags question: http://stackoverflow.com/q/51625776
tags question: http://stackoverflow.com/q/51544103
type: Tag
tags question: http://stackoverflow.com/q/51592631
tags question: http://stackoverflow.com/q/51546865
tags question: http://stackoverflow.com/q/51577228
tags question: http://stackoverflow.com/q/51496232
tags question: http://stackoverflow.com/q/51611963
tags question: http://stackoverflow.com/q/51502329
tags question: http://stackoverflow.com/q/51577841
tags question: http://stackoverflow.com/q/51577886
tags question: http://stackoverflow.com/q/51572720
tags question: http://stackoverflow.com/q/51632860
tags question: http://stackoverflow.com/q/51585383
tags question: http://stackoverflow.com/q/51604230
tags question: http://stackoverflow.com/q/51533363
tags question: http://stackoverflow.com/q/51541372
tags question: http://stackoverflow.com/q/51572802
tags question: http://stackoverflow.com/q/51638468
tags question: http://stackoverflow.com/q/51482697

http://stackoverflow.com/comment/89994830
has text: Thank you ! :) the solution in the link (which works) is to use `StyleFrame` library which works wtih xlsx files and actually lets you modify the width of cells. Thanks
comment on: http://stackoverflow.com/q/51512550
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89990166
comment on: http://stackoverflow.com/q/51510669
type: Comment
type: QuestionComment
has text: https://ibb.co/kKD2r8 It seems I fixed my issue, my pasting the same loop x3 it removes what I want, for some reason at the start it removes every 2nd so if you paste the loop two more times eventually it removes it all. This is one ugly way and help to make it better is appreciated
score: 0

http://stackoverflow.com/comment/114760045
comment on: http://stackoverflow.com/a/51571827
type: Comment
has text: I worked but now they're tiny even if I set the figsize. How could I fix the size?
score: 0
type: AnswerComment

http://stackoverflow.com/a/51584196
score: 7
answers question: http://stackoverflow.com/q/51584100
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90133911
type: Answer
has comment: http://stackoverflow.com/comment/90133960
has comment: http://stackoverflow.com/comment/90133977
has body: You just need to define at least one of the functions: __lt__(), __le__(), __gt__(), or __ge__() In addition, the class should supply an __eq__() method. Then you use the decorator like so: from functools import total_ordering @total_ordering class BankAccount: """ Simple BankAccount class """ def __init__(self, balance=0): """Initialize account with balance""" self.balance = balance def __lt__(self, other): return self.balance &lt; other.balance def __eq__(self,other): return self.balance == other.balance
has comment: http://stackoverflow.com/comment/90133881
accepted answer of: http://stackoverflow.com/q/51584100
upvote count: 7

http://stackoverflow.com/comment/133898763
comment on: http://stackoverflow.com/a/75909038
type: AnswerComment
has text: Not sure about the librarys, just used it for my app and does the job very well
score: 0
type: Comment

http://stackoverflow.com/q/51615388
upvote count: 4
has answer: http://stackoverflow.com/a/51622826
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/49942713
score: 4
has title: Retrieve data from db & set to textinput fields and image widget in Kivy for a multiscreen app! AttributeError
tagged with: sqlite
tagged with: python
tagged with: kivy
favorite count: 0
accepted answer: http://stackoverflow.com/a/51622826
tagged with: python-3.x
has body: I'm learning kivy by cobbling together a small application to understand the behavior of different widgets. What works: The app accepts text and images as input &amp; stores to the database, stored data is correctly displayed on buttons using RecycleView. Problem: On pressing the buttons on the RecycleView the app crashes with the error: AttributeError: 'super' object has no attribute 'getattr' What I've tried: I understand from this post, that initialization may not be complete and tried scheduling with kivy clock but this throws a new error AttributeError:'float' object has no attribute 'index'. Expected behavior: On button click set selected button data (text &amp; image values) in their respective widgets. I have not been able to understand why this is not working in a multiscreen environment. The full code is as follows. main.py import sqlite3 from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.button import Button from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty from kivy.uix.recyclegridlayout import RecycleGridLayout from kivy.uix.behaviors import FocusBehavior from kivy.uix.recycleview.layout import LayoutSelectionBehavior from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.accordion import Accordion from kivy.clock import Clock from tkinter.filedialog import askopenfilename from tkinter import Tk class Manager(ScreenManager): screen_one = ObjectProperty(None) screen_two = ObjectProperty(None) class ScreenTwo(BoxLayout, Screen, Accordion): data_items = ListProperty([]) def __init__(self, **kwargs): super(ScreenTwo, self).__init__(**kwargs) # Clock.schedule_once(self.populate_fields) self.create_table() self.get_table_column_headings() self.get_users() def populate_fields(self, instance): # NEW columns = self.data_items[instance.index]['range'] self.ids.no.text = self.data_items[columns[0]]['text'] self.user_na…
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/90135910
score: 0
type: Comment
has text: Ah true. Keep forgetting that the session provided by Flask-SQLA has some customizations in place.
type: QuestionComment
comment on: http://stackoverflow.com/q/51584811

http://stackoverflow.com/q/51557176
type: Question
tagged with: opencv
has body: Are there any libraries in python that allow the input of a video file and then output 4 equal quadrants of that video files (eg: top left, top right, bottom left, bottom right)? At the moment I have only seen examples that split the video in terms of length (eg: a 20 minute video into 5 minute sections) I know its probably possible by using something like opencv to split the video into frames and then split each frame into 4 and the make the individual frames back into the video but I think this is very resource hungry and not the most efficient solution. Any suggestions or examples will be appreciated.
tagged with: split
has answer: http://stackoverflow.com/a/51557417
upvote count: 2
has title: How to split video in python into 4 equal sections?
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
linked to: http://stackoverflow.com/q/49376779
score: 2
tagged with: video
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/51557417

http://stackoverflow.com/a/51569543
has body: So here's a working implementation. As you can see you will have to add an optional second parameter (called element here) to dictionaryCall and then pass it to the selected method. class stack(): def __init__(self): self.items = [] def push(self,item): self.items.append(item) def pop(self): print(self.items.pop()) def isEmpty(self): # I dropped the `return` here due to syntax error print (self.items == []) def getStack(self): # I dropped the `return` here due to syntax error print (self.items) s = stack() switcher = { '1' : s.push, '2' : s.pop, '3' : s.isEmpty, '4' : s.getStack, } # I added an optional parameter for the `push` method def dictionaryCall(key, element = None): method = switcher[key] # call the method with element if it exists if element == None: method() else: method(element) # call from command line if __name__ == '__main__': while(1): key = input('enter choice 1.push 2. pop 3.isEmpty 4 getStack 5.exit: ') if key == '5': break print ('&gt; {0}'.format(key)) if key == '1': element = input('enter an element to push onto the stack: ') dictionaryCall(key, element) else: dictionaryCall(key) EXAMPLE: enter choice 1.push 2. pop 3.isEmpty 4 getStack 5.exit: '1' &gt; 1 enter an element to push onto the stack: 'foo' enter choice 1.push 2. pop 3.isEmpty 4 getStack 5.exit: '3' &gt; 3 False enter choice 1.push 2. pop 3.isEmpty 4 getStack 5.exit: '4' &gt; 4 ['foo'] enter choice 1.push 2. pop 3.isEmpty 4 getStack 5.exit: A couple of things you need to pay attention to: return print (...) is not valid syntax (just write print (...)) arguments read from the command line via input are evaluated (that means you have to enter e.g. '1' to push an element since your dictionary has string keys to run a python program from the command line you need to wrap it in if __name__ == '__main__': ... otherwise the file will be parsed but not executed as @Pm2Ring said in the comments, pop should print the popped element
has comment: http://stackoverflow.com/comment/90105897
has comment: http://stackoverflow.com/comment/90105354
type: Answer
has comment: http://stackoverflow.com/comment/90105444
has comment: http://stackoverflow.com/comment/90112554
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90105270
has comment: http://stackoverflow.com/comment/90112546
has comment: http://stackoverflow.com/comment/90105620
has comment: http://stackoverflow.com/comment/90112079
has comment: http://stackoverflow.com/comment/90106370
upvote count: 1
has comment: http://stackoverflow.com/comment/90105393
answers question: http://stackoverflow.com/q/51569308
has comment: http://stackoverflow.com/comment/90105646

http://stackoverflow.com/q/51576237
type: Question
has title: Python: Using recursive methods to get Binary Search Tree Height
has comment: http://stackoverflow.com/comment/90118441
tagged with: binary-search
score: 0
has comment: http://stackoverflow.com/comment/90121583
has comment: http://stackoverflow.com/comment/90118373
tagged with: python-3.x
tagged with: binary-search-tree
type: UnansweredQuestion
tagged with: python
answer count: 0
has body: for my assignment, I am trying to get height of the Binary Search Tree through linear time. The prof specified that he wants us to keep track of the height in our recursive insertion and removal methods, yet mine never works during the test. The prof's requirement is: "Add an attribute to the __Node class to store the height of the subtree rooted at that node. Just before returning a node reference at the end of a recursive call, update that node's height field to be correct." My thought is, instead of making changes at a root, if the insertion or removal moves down left or right, the height increases/decrease by one (but I'm not sure how it works if there is still something left at level-n). I have attached my code over here: class Binary_Search_Tree: class __BST_Node: def __init__(self, value): self.value = value self.left=None self.right=None self.height=0 def __init__(self): self.__root = None def __recur_ins(self, val,root): if root is None: root = Binary_Search_Tree.__BST_Node(val) elif root.value &gt; val: root.left = self.__recur_ins(val,root.left) root.height += 1 elif root.value &lt; val: root.right =self. __recur_ins(val,root.right) root.height += 1 return root def __get_min(self,node): walker=node while walker.left is not None: walker=walker.left return walker def __recur_rem(self, val, root): if root is None: raise ValueError if root.value == val: if root.left is None: cur = root.right root = None return cur elif root.right is None: cur = root.left root = None return cur elif (root.left is not None) and (root.right is not None): cur = self.__get_min(root.right) root.value = cur.value root.right = self.__recur_rem(cur.value, root.right) elif val &lt; root.value: root.left=self.__recur_rem(val,root.left) root.height -= 1 elif val &gt; root.value: root.right=self.__recur_rem(val, root.right) root.height -= 1 return root def __actual_height(self,bst_node): if bst_node is None: return 0 else: return self.__root.height def get_height(self): return self.__actu…

http://stackoverflow.com/q/51506404
type: Question
has body: I am currently working on a program that would take the previous 4000 days of stock data about a particular stock and predict the next 90 days of performance. The way I've elected to do this is with an RNN that makes use of LSTM layers to use the previous 90 days to predict the next day's performance (when training, the previous 90 days are the x-values and the next day is used as the y-value). What I would like to do however, is use the previous 90-180 days to predict all the values for the next 90 days. However, I am unsure of how to implement this in Keras as all the examples I have seen only predict the next day and then they may loop that prediction into the next day's 90 day x-values. Is there any ways to just use the previous 180 days to predict the next 90? Or is the LSTM restricted to only predicting the next day?
tagged with: recurrent-neural-network
tagged with: lstm
score: 0
answer count: 1
tagged with: keras
tagged with: python
has comment: http://stackoverflow.com/comment/89982088
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90018684
has answer: http://stackoverflow.com/a/51526725
tagged with: tensorflow
has title: How to make RNN time-forecast multiple days using Keras?

http://stackoverflow.com/q/51544505
has answer: http://stackoverflow.com/a/51544557
has title: Why cant a function name and a variable name be called the same thing in a class?
possible better answer: http://stackoverflow.com/a/51544651
has answer: http://stackoverflow.com/a/51545086
favorite count: 0
answer count: 5
has body: My code currently looks like: class Employee: def __init__(self, first, last): self.first = first self.last = last self.email = first + '.' + last + '@email.com' def email(self): return '{}.{}@email.com'.format(self.first, self.last) def fullname(self): return '{} {}'.format(self.first, self.last) emp_1 = Employee('John', 'Smith') emp_1.first = 'Jim' print(emp_1.first) print(emp_1.email()) print(emp_1.fullname()) And my output gives: Jim Traceback (most recent call last): File "/home/djpoland/python-files/test.py", line 19, in &lt;module&gt; print(emp_1.email()) TypeError: 'str' object is not callable I understand that I can fix this issue by removing self.email or by changing the name of the email function. However, why can't a variable name and a function have the same name? Is this just a Python standard convention or is there an internal reason for this issue? I tried googling for why but I can't find any information.
tagged with: python
accepted answer: http://stackoverflow.com/a/51544557
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51544730
upvote count: 3
type: Question
tagged with: function
downvote count: 0
has answer: http://stackoverflow.com/a/51544651
has comment: http://stackoverflow.com/comment/90057200
has answer: http://stackoverflow.com/a/51544662

http://stackoverflow.com/comment/90119333
has text: You might be able to access the calling scope with `inspect.stack`. But it doesn't look like a good idea at all. https://docs.python.org/3/library/inspect.html#inspect.stack
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51576921

http://stackoverflow.com/comment/90194407
score: 1
type: AnswerComment
type: Comment
has text: This is elegant I think, would probably have written it as `np.where((df1'V3','V4' == 'Yes').any(1), 'Yes', 'No')`
comment on: http://stackoverflow.com/a/51614440

http://stackoverflow.com/q/51541570
tagged with: reportlab
type: Question
type: AnsweredQuestion
answer count: 2
score: 4
favorite count: 0
has answer: http://stackoverflow.com/a/53199157
accepted answer: http://stackoverflow.com/a/53199157
tagged with: python
upvote count: 4
has body: I have been trying to create a pdf using PyPDF2 and Reprortlab. I need to draw a flowable paragraph with huge chunk of text. The problem is the size of the paragraph may vary. I want to keep the top-left corner (start of the paragraph) of the paragraph fixed for all the pages. The problem is when I draw the paragraph at a fixed location (x,y on Canvas) the bottom left corner stays at this location (x,y). I guess this is the deafult behaviour of ReportLab. Is there a tweak or work around to start the paragraph from the top left instead of bottom left so that the paragraphs start from the same location irrespective of the size of the paragraph?
possible better answer: http://stackoverflow.com/a/70945844
has title: How to draw a paragraph from top to bottom on canvas?
has answer: http://stackoverflow.com/a/70945844
tagged with: pypdf
downvote count: 0

http://stackoverflow.com/q/51511145
score: 0
has comment: http://stackoverflow.com/comment/89991408
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: messagebox
linked to: http://stackoverflow.com/q/11418625
type: Question
has body: How to pop a message and don't disturb the following process in python, in case of the user needn't to click the accept button on the message box. I use tkinter.messagebox.showinfo('xyz Demo','happy new year'), but there is a accept button on the message box. I just want the message to be a information, and the following code don't be stopped by the message pop. Do you have any idea?
duplicate of: http://stackoverflow.com/q/11418625
has title: How to pop a message and don't disturb the following process in python？
has comment: http://stackoverflow.com/comment/90031134

http://stackoverflow.com/comment/90010936
comment on: http://stackoverflow.com/q/51521048
type: Comment
type: QuestionComment
has text: taskkill is a windows command. OSx equivalent is kill.
score: 2

http://stackoverflow.com/a/51527494
has comment: http://stackoverflow.com/comment/90025017
has comment: http://stackoverflow.com/comment/90024019
has body: create two item types: class Person(scrapy.Item): name = scrapy.Field() age = scrapy.Field() height = scrapy.Field() class Pet(scrapy.Item): name = scrapy.Field() pet = scrapy.Field() Then for each Person you can create multiple Pets
answers question: http://stackoverflow.com/q/51527402
has comment: http://stackoverflow.com/comment/90023939
has comment: http://stackoverflow.com/comment/90025080
has comment: http://stackoverflow.com/comment/90023988
has comment: http://stackoverflow.com/comment/90027990
has comment: http://stackoverflow.com/comment/90024736
score: 0
has comment: http://stackoverflow.com/comment/90024634
has comment: http://stackoverflow.com/comment/90024489
has comment: http://stackoverflow.com/comment/90024535
type: Answer

python-3.6
tags question: http://stackoverflow.com/q/51583968
tags question: http://stackoverflow.com/q/51531680
tags question: http://stackoverflow.com/q/51578145
tags question: http://stackoverflow.com/q/51605105
tags question: http://stackoverflow.com/q/51497714
tags question: http://stackoverflow.com/q/51576935
type: Tag
tags question: http://stackoverflow.com/q/51490814
tags question: http://stackoverflow.com/q/51578119
tags question: http://stackoverflow.com/q/51571191
tags question: http://stackoverflow.com/q/51500928
tags question: http://stackoverflow.com/q/51507768
tags question: http://stackoverflow.com/q/51531900
tags question: http://stackoverflow.com/q/51610959
tags question: http://stackoverflow.com/q/51504268
tags question: http://stackoverflow.com/q/51617423
tags question: http://stackoverflow.com/q/51616287
tag name: python-3.6
tags question: http://stackoverflow.com/q/51510870
tags question: http://stackoverflow.com/q/51502052
tags question: http://stackoverflow.com/q/51525604
tags question: http://stackoverflow.com/q/51531543
tags question: http://stackoverflow.com/q/51627721
tags question: http://stackoverflow.com/q/51489432
tags question: http://stackoverflow.com/q/51548112
tags question: http://stackoverflow.com/q/51495549
tags question: http://stackoverflow.com/q/51526605

http://stackoverflow.com/comment/90209973
has text: OK, thanks for checking
type: Comment
comment on: http://stackoverflow.com/q/51621899
type: QuestionComment
score: 0

http://stackoverflow.com/q/51550181
tagged with: numpy
tagged with: numpy-ndarray
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90069924
tagged with: python
has title: How to deal with this when I use numpy.array() to deal with 'list'？
has comment: http://stackoverflow.com/comment/90069259
has comment: http://stackoverflow.com/comment/90070388
has comment: http://stackoverflow.com/comment/90067797
has body: import cv2 import numpy list_pixel=[] list_label=[] for i in range(0,10): for j in range(0,10): list_pixel.append(cv2.imread("C:\\Users\\kimcho\\Desktop\\testdata\\testdata_"+str(i)+"_0"+str(j)+".png",0)) list_label.append(i) j=0 list_pixel.pop(0) list_label.pop(0) list_pixel=numpy.array(list_pixel) print(list_pixel) print(list_pixel.shape) print(list_pixel[0].shape) How to deal with this when I use numpy.array() to deal with 'list'？I wanna make datasets by imitating keras.But,the datasets I made didn't satisfy me.I want it to act like keras,to return a value like this: It can return a value of(60000,28,28) But as for my datasets,it can only return like this: Only return a value of(99,)—— I got 99 pictures and I want to load their pixel into list_pixel Here is my code: Hoping anyone can help me solve this problem.Deeply thank you!!!
downvote count: 2
has answer: http://stackoverflow.com/a/51552011
accepted answer: http://stackoverflow.com/a/51552011
type: AnsweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/90069090
type: Question

http://stackoverflow.com/comment/90215337
score: 0
comment on: http://stackoverflow.com/q/51625243
type: Comment
type: QuestionComment
has text: have you tried with django's `timezone.now()`, please refer this https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/

http://stackoverflow.com/q/51562870
answer count: 2
upvote count: 9
has answer: http://stackoverflow.com/a/72188704
has answer: http://stackoverflow.com/a/78162841
downvote count: 0
favorite count: 0
tagged with: django-annotate
has comment: http://stackoverflow.com/comment/94260570
has comment: http://stackoverflow.com/comment/135970858
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/115924172
has comment: http://stackoverflow.com/comment/115924336
linked to: http://stackoverflow.com/q/31682737
has comment: http://stackoverflow.com/comment/110745284
tagged with: orm
has title: Django annotate data by date for empty result
has body: Suppose I have a object model A, and it has a field called created, which is a datetime type field. If I use annotate to count how many A are created each day, I can use A.objects.annotate(date=Trunc('created', 'day', output_field=DateField()) ).values('date').order_by('date').annotate(count=Count('id')) After that, I can get the result, which looks like [{date: '2018-07-22', count:1 }, {date: '2018-07-23', count:1 }, {date: '2018-07-25', count:1 }] However, notice that I miss a 2018-07-24 because it didn't create any A in that day. Is there any way to let result to have {date: '2018-07-24', count:0 } inside that queryset?
linked to: http://stackoverflow.com/q/52290430
score: 9
type: Question

http://stackoverflow.com/q/51637195
answer count: 2
has answer: http://stackoverflow.com/a/51640036
possible better answer: http://stackoverflow.com/a/51637363
has answer: http://stackoverflow.com/a/51637363
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51640036
tagged with: django
tagged with: python
has body: I am making an app using Django2.0. But There are things that I do not know even if I investigate. There are models as follows. class Picture(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE) title = models.CharField(max_length=255) image = models.ImageField(upload_to='image/') using the following form class PictureForm(forms.ModelForm): class Meta: model = Picture fields = ['place', 'title', 'image'] And run following code on views.py obj = Picture() pic = PictureForm(request.POST, request.FILES, instance=obj) pic.save() I can add model peacefully. But in this way, I should select place and title on form every time. Beforehand I decide place and title, I will only select image on the form. It reduces my work. Since there are several place and title, I do not want to set them to default values. I succeeded in making a form. class PictureForm(forms.ModelForm): class Meta: model = Picture fields = ['image',] But I don't know how to add title and place on views.py I'm not good at English. Thank you for seeing the bad sentensecs to the end
has title: Django How to add a model other than a form
score: 0

http://stackoverflow.com/a/51599859
has body: You can use requests: from bs4 import BeautifulSoup as soup import requests, contextlib, re, os @contextlib.contextmanager def get_images(url:str): d = soup(requests.get(url).text, 'html.parser') yield [[i.find('img')['src'], re.findall('(?&lt;=\.)\w+$', i.find('img')['alt'])[0]] for i in d.find_all('a') if re.findall('/image/\d+', i['href'])] n = 3 #end value os.system('mkdir MARCO_images') #added for automation purposes, folder can be named anything, as long as the proper name is used when saving below for i in range(n): with get_images(f'https://marco.ccr.buffalo.edu/images?page={i}&amp;score=Clear') as links: print(links) for c, [link, ext] in enumerate(links, 1): with open(f'MARCO_images/MARCO_img_{i}{c}.{ext}', 'wb') as f: f.write(requests.get(f'https://marco.ccr.buffalo.edu{link}').content) Now, inspecting the contents of the MARCO_images directory yields: print(os.listdir('/Users/ajax/MARCO_images')) Output: ['MARCO_img_1.jpg', 'MARCO_img_10.jpg', 'MARCO_img_11.jpg', 'MARCO_img_12.jpg', 'MARCO_img_13.jpg', 'MARCO_img_14.jpg', 'MARCO_img_15.jpg', 'MARCO_img_16.jpg', 'MARCO_img_17.jpg', 'MARCO_img_18.jpg', 'MARCO_img_19.jpg', 'MARCO_img_2.jpg', 'MARCO_img_20.jpg', 'MARCO_img_21.jpg', 'MARCO_img_3.jpg', 'MARCO_img_4.jpg', 'MARCO_img_5.jpg', 'MARCO_img_6.jpg', 'MARCO_img_7.jpg', 'MARCO_img_8.jpg', 'MARCO_img_9.jpg']
has comment: http://stackoverflow.com/comment/90166178
accepted answer of: http://stackoverflow.com/q/51599798
has comment: http://stackoverflow.com/comment/90167885
type: Answer
answers question: http://stackoverflow.com/q/51599798
has comment: http://stackoverflow.com/comment/90167612
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90166201
has comment: http://stackoverflow.com/comment/90167526
has comment: http://stackoverflow.com/comment/90166328
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/90088448
has text: I don't really get what you are saying @user3483202, I am new to Python and pretty bad at math haha, I am just doing this to learn basics... What do you mean by float(10)/float(5)?
comment on: http://stackoverflow.com/q/51560724
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51601885
answers question: http://stackoverflow.com/q/51601742
has comment: http://stackoverflow.com/comment/90210686
has comment: http://stackoverflow.com/comment/90209898
score: 0
has comment: http://stackoverflow.com/comment/90209747
has comment: http://stackoverflow.com/comment/90211118
type: Answer
has body: When you just run "${SRC_DIR}/systemd_client.py", you're telling it to run that script the same way it would be run by the shell: by looking at the #! line and running it with whatever interpreter is specified there. Which is probably something like #! /usr/bin/python or #! /usr/bin/env python. If you want to run your script with a particular interpreter, you have to run that interpreter and pass it the script—just as you would at the shell. I'm pretty rusty with CMake, but I'd assume you do that like this: "${PYTHON_EXECUTABLE}" "${SRC_DIR}/amyconfig_service.py" Alternatively, since this is your code, maybe you want to use setuptools to programmatically generate scripts for your entry-points, which means it would create a #! line for them that runs whichever Python version was used to run setup.py.
has comment: http://stackoverflow.com/comment/90210613

http://stackoverflow.com/comment/89940761
type: Comment
has text: Changing it for Z1 I get `InvalidArgumentError (see above for traceback): Matrix size-incompatible: In[0]: [1,5], In[1]: [3,1]` and for Z2, `ValueError: Incompatible shapes between op input and calculated input gradient. Forward operation: softmax_cross_entropy_with_logits_sg. Input index: 1. Original input shape: (1, ?). Calculated input gradient shape: (3, 3)`
comment on: http://stackoverflow.com/a/51485750
score: 0
type: AnswerComment

http://stackoverflow.com/q/51578739
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51579386
has title: Django 404 Page Not Found blog.views.post_detail
accepted answer: http://stackoverflow.com/a/51579386
upvote count: 1
tagged with: django
has body: I'm new with django and I use mysql. I followed the tutorial to make blog with django. I made list and detail blog, but when I clicked the detail post of blog, the error comes Page Not Found (404) Raised by: blog.views.post_detail. These are my site urls.py, blog urls.py, models.py and views.py. Site urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), ] blog urls.py: from django.conf.urls import url,include from . import views urlpatterns = [ url(r'^$', views.PostListView.as_view(),name='post_list'), url(r'^(?P&lt;year&gt;\d{4})/(?P&lt;month&gt;\d{2})/(?P&lt;day&gt;\d{2})/'\ r'(?P&lt;post&gt;[-\w]+)/$', views.post_detail, name='post_detail'), ] models.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset()\ .filter(status='published') class Post(models.Model): STATUS_CHOICES = (('draft', 'Draft'), ('published', 'Published'),) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique_for_date='publish') author = models.ForeignKey(User,related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering=('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) views.py: …
has comment: http://stackoverflow.com/comment/90122900
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90122940
type: Question
answer count: 1
downvote count: 0
tagged with: web
favorite count: 0

http://stackoverflow.com/q/51566436
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51566562
score: -1
has answer: http://stackoverflow.com/a/51566499
answer count: 2
upvote count: 0
possible better answer: http://stackoverflow.com/a/51566499
has body: I have a csv file with couple of thousand rows and 4-64 coumns( I have about 50 CSV files and the number of columns may vary from file to file but each file has fixed number of columns). e.g 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0\n 1 2 3 4 5 6 7\n 0 0 0 0 0 0 1\n So, I need to first sum each row then add the two consecutive rows using some maths equation. What is the best pythonic way to do it? I can write the new value in a new file. So, the new file will have less number of rows than original file since it is merging value of two rows. e.g CSV1 after summing across different column the value in row 1 is 0 and row 2 is 0. So, new file row 1 will be 0+0 = 0 and third row in original file = 28 and row 4 =1 So, row 2 in new file = 28+1 = 29
favorite count: 0
tagged with: python
has title: adding two rows in a CSV file in python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51566562
tagged with: file

http://stackoverflow.com/comment/90194038
has text: I have edited to initialize the `cards` list in a relatively shorter way rather than writing all elements explicitly.
comment on: http://stackoverflow.com/a/51614158
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51502263
has comment: http://stackoverflow.com/comment/89973602
downvote count: 0
possible better answer: http://stackoverflow.com/a/75316885
favorite count: 0
has comment: http://stackoverflow.com/comment/89977168
has comment: http://stackoverflow.com/comment/89978282
has comment: http://stackoverflow.com/comment/89973841
has comment: http://stackoverflow.com/comment/89973703
has answer: http://stackoverflow.com/a/52552220
has comment: http://stackoverflow.com/comment/89973015
has comment: http://stackoverflow.com/comment/89977493
type: Question
has comment: http://stackoverflow.com/comment/89972877
has comment: http://stackoverflow.com/comment/89973293
has comment: http://stackoverflow.com/comment/89977140
has comment: http://stackoverflow.com/comment/89977454
tagged with: pandas
has body: I am trying to filter out the dataframe that contains a list of product. However, I am getting the error 'dataframe' object has no attribute 'str' whenever I run the code. Here is the line of code: include_clique = log_df.loc[log_df['Product'].str.contains("Product A")] Product is an object datatype. import pandas as pd import numpy as np data = pd.read_csv("FILE.csv", header = None) headerName = ["DRID", "Product", "M24", "M23", "M22", "M21"] data.columns = [headerName] log_df = np.log(1 + data"M24", "M23", "M22", "M21") copy = data"DRID", "Product".copy() log_df = copy.join(log_df) include_clique = log_df.loc[log_df['Product'].str.contains("Product A")] Here is the head: ID PRODUCT M24 M23 M22 M21 0 123421 A 0.000000 0.000000 1.098612 0.0 1 141840 A 0.693147 1.098612 0.000000 0.0 2 212006 A 0.693147 0.000000 0.000000 0.0 3 216097 A 1.098612 0.000000 0.000000 0.0 4 219517 A 1.098612 0.693147 1.098612 0.0
has comment: http://stackoverflow.com/comment/89977935
tagged with: python
has comment: http://stackoverflow.com/comment/89973286
has comment: http://stackoverflow.com/comment/89977236
score: 24
has comment: http://stackoverflow.com/comment/89973398
has comment: http://stackoverflow.com/comment/89974509
has comment: http://stackoverflow.com/comment/89977938
answer count: 2
has comment: http://stackoverflow.com/comment/89976805
has comment: http://stackoverflow.com/comment/89978004
has comment: http://stackoverflow.com/comment/89976795
has comment: http://stackoverflow.com/comment/89973022
has comment: http://stackoverflow.com/comment/89974284
upvote count: 24
has comment: http://stackoverflow.com/comment/89973565
has comment: http://stackoverflow.com/comment/89973072
accepted answer: http://stackoverflow.com/a/52552220
has comment: http://stackoverflow.com/comment/89973089
has title: AttributeError 'dataframe' object has no attribute 'str'
has comment: http://stackoverflow.com/comment/89973864
tagged with: indexing
has comment: http://stackoverflow.com/comment/89973933
tagged with: attributeerror
has comment: http://stackoverflow.com/comment/89978151
has comment: http://stackoverflow.com/comment/89978091
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89977418
has comment: http://stackoverflow.com/comment/89977284
has answer: http://stackoverflow.com/a/75316885
has comment: http://stackoverflow.com/comment/89973872
has comment: http://stackoverflow.com/comment/89972960
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89977941
has comment: http://stackoverflow.com/comment/89973173

http://stackoverflow.com/comment/99432992
has text: I'm working on something related. The axis are ABS_Y/ABS_X for the left stick, and ABS_Z/ABS_RZ for the right stick on my system, though that may vary. I think they were prefixed with EV_ on my other system.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51564667
type: QuestionComment

http://stackoverflow.com/comment/89984297
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51507592
has text: @zwer `str.casefold` is preferable because it handles other languages better.
type: Comment

http://stackoverflow.com/a/51549849
has body: The reason your RAM went crazy is because you're operating on f while you're extending f. Therefore, you're creating an infinite loop. You can instead operate on the copy of f like this: In [2]: f = [1, 2, 5, 10] In [3]: f.extend(i*3 for i in f.copy()) In [4]: f Out[4]: [1, 2, 5, 10, 3, 6, 15, 30] You're making the copy in your code with this line: k = list(f), which is why that version works and not the other one. If you simply do k = f, both k and f essentially point to the same list. Check it like this: f = [1, 2, 3] k = f k.append(4) print(f) print(k) The output will be [1, 2, 3, 4] for both. But do this: f = [1, 2, 3] k = f.copy() # or list(f) k.append(4) print(f) print(k) Output: [1, 2, 3] [1, 2, 3, 4]
has comment: http://stackoverflow.com/comment/90067217
type: Answer
accepted answer of: http://stackoverflow.com/q/51549816
has comment: http://stackoverflow.com/comment/90067243
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51549816

http://stackoverflow.com/comment/90041223
comment on: http://stackoverflow.com/a/51524749
type: AnswerComment
score: 0
type: Comment
has text: Thank you! It worked well. May I ask how to merge all the ROI into just 1 big ROI?

http://stackoverflow.com/q/51585502
has answer: http://stackoverflow.com/a/51585571
accepted answer: http://stackoverflow.com/a/51585571
tagged with: python
has title: when to use iloc and loc for boolean
type: AnsweredQuestion
has body: I'm a bit confusing when using boolean series for indexing for pandas Dataframe. Should I use iloc or loc? or any better solution? for example t1 = pd.DataFrame(np.ones([3,4])) t1.iloc[1:3,0]=3 this line will give correct answer t1.loc[:,(t1&gt;2).any()] but line with iloc wiill raise an error t1.iloc[:,(t1&gt;2).any()] I check https://pandas.pydata.org/pandas-docs/stable/indexing.html, the page says both iloc and loc accept a boolean array. Why does iloc not work in my example? When to use iloc and loc? or are there any better alternatives?
type: Question
tagged with: indexing
score: 4
has comment: http://stackoverflow.com/comment/90136637
has comment: http://stackoverflow.com/comment/90136657
upvote count: 4
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90237882
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51636537
has text: @ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000 tho `fix-yahoo-finance` seems to work ok
type: Comment

http://stackoverflow.com/comment/90061904
comment on: http://stackoverflow.com/q/51546898
has text: Using garbage credentials I get the same response: Your "success check" is faulty.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51611266
tagged with: multithreading
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51615074
type: Question
has body: I have a Flask-SocketIO server, which initialize a GUI in a separated thread. if __name__ == '__main__': if len(sys.argv) &gt; 1 and sys.argv[1] == 'dev': print "Running Flask-SocketIO on dev mode" else: print "Running Flask-SocketIO on production mode" print 'Running Graphical User Interface...' thread.start_new_thread(display_react.main, ()) print 'Initializing server' socketio.run(app, debug=False) The GUI is basically the cefpthon3 example which use the wxPython, but instead of being a normal browser, it only shows up a specific page served by the server. At the moment i want the whole app shutdown when i close the GUI. For the effect, i've created a route on the server which (when called) will shutdown the server. @app.route('/shutdown', methods=['GET']) def shutdown(): server_request.shutdown() socketio.stop() print "Trying to close..." return 'Server shutting down...' And this route is called when before close the wxPython. However, this error appears before the server shutdown: Can anyone help me solving or hiding this?
downvote count: 0
tagged with: wxpython
tagged with: flask
has title: Closing wxPython app on a separated thread runs into a window alert
answer count: 1
has answer: http://stackoverflow.com/a/51615074
favorite count: 0
tagged with: cefpython

http://stackoverflow.com/a/51583215
upvote count: 2
type: Answer
score: 2
has body: Vader is already quite sophisticated in terms of its workings, it takes into account negation words, and is specialised to social-media snippets (you'll notice it has things like smileys included in its lexicon). Vader, however, will not be able to capture the subtle nuances within language, as essentially it is just an advanced bag-of-words model. This article discusses the limitations of lexicon's versus machine-learning based methods more comprehensivley. You could try adding in other lexica to see if that improves results, however as vader is already trained in your domain I'm not sure how succesful that will be. My suggestion would be to examine snippets that are misclassified, and determine if adding a small list of extra words would be enough to increase your accuracy. However, don't worry if you're getting low-ish accuracy using the lexicon-based approach, thats simply due to the tradeoff between not having to manually label your data to make it suitable for machine learning, and the extra increase in accuracy that machine-learning can often yield.
downvote count: 0
answers question: http://stackoverflow.com/q/51518059

http://stackoverflow.com/a/51492232
score: 2
has comment: http://stackoverflow.com/comment/89991865
upvote count: 2
answers question: http://stackoverflow.com/q/51490297
downvote count: 0
has body: With 54000 columns I would use regular expression, which is fast: import re with open('sample.txt', 'r') as f_in, open('sample_out.txt', 'w', newline='') as f_out: for line in f_in.readlines(): g = re.findall(r'[^\s]+', line) if g: f_out.write(' '.join([g[1], g[0]] + g[2:]) + '\n')
type: Answer
has comment: http://stackoverflow.com/comment/89989790

http://stackoverflow.com/q/51527379
score: -3
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90023368
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/90023422
downvote count: 3
has answer: http://stackoverflow.com/a/51534877
type: Question
has comment: http://stackoverflow.com/comment/90023565
has title: Convert python dictionary to python list
upvote count: 0
has comment: http://stackoverflow.com/comment/90023589
has comment: http://stackoverflow.com/comment/90023665
has body: dictionary = {0:0.2, 9:0.4} pylist = [0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0.4] Which is the efficient way to convert dictionary to pylist ? The keys in dictionary form the index in the list, and respective values in the dictionary become the values in list. The keys in the dictionary are going to range between 0 to 9, inclusive. the length of the list would be fixed i.e. 10. pytuple = [ (0, 0.2), (9,0.4)] pylist = [0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0.4] Alternatively, Which is the efficient way to convert pytuple to pylist ? The first element in tuple form the index in the list, and respective second value in the tuple become the values in list. The keys in the dictionary are going to range between 0 to 9, inclusive. the length of the list would be fixed i.e. 10.
tagged with: tuples
has comment: http://stackoverflow.com/comment/90023693
has comment: http://stackoverflow.com/comment/90023373
answer count: 1
accepted answer: http://stackoverflow.com/a/51534877
has comment: http://stackoverflow.com/comment/90023384
favorite count: 0
has comment: http://stackoverflow.com/comment/90023460
has comment: http://stackoverflow.com/comment/90023620

http://stackoverflow.com/comment/90067912
type: Comment
comment on: http://stackoverflow.com/a/51549423
has text: @ juanpa.arrivillaga, yes I agree that `my_list*1` is more obscure, in fact my question came about in trying to understand someone else's code that is full of the `my_list*1` syntax!
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90200888
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51616686
has text: For example, you might write `out_temp = path(out, 'elements.*.insights.0.details').flatten()` to get this list. If this is something you’re interested in, you should search PyPI for dpath, kvc, and… I forget the other one, but look around and you should find it.
type: Comment

http://stackoverflow.com/q/51635713
type: Question
has body: I was wondering whether it is possible to instantiate namedtuples within a loop. The problem I am having is that I have individual files (>500), which each should be an instance of a namedtuple and I would like to use the filename, to access records. e.g. say I have a namedtuple with three attributes from collections import namedtuple import pandas as pd record_ids=["record1","record2"] reads=namedtuple("reads", "id length text") for record in record_ids: records=pd.read_table(record+".txt",dtype=None, header='infer') text=records.iloc[0:100] entry=[record,len(text),text) varname=reads._make(entry) Where record_ids are the filenames saved in a list. I would like varname to be the filename. So if my file is record1.txt, that I can access record1.length anywhere. My questions are: 1) Is this a sensible approach? I need to perform mathematical operations on larger datasets, this is not for record keeping. 2) Is this possible? Or is there a more pythonic alternative? Thanks a lot for any suggestions!
tagged with: python
tagged with: namedtuple
upvote count: 2
has comment: http://stackoverflow.com/comment/90242089
has answer: http://stackoverflow.com/a/51646865
answer count: 1
has comment: http://stackoverflow.com/comment/90241302
has comment: http://stackoverflow.com/comment/90241811
has comment: http://stackoverflow.com/comment/90241242
type: UnansweredQuestion
has title: Create instances of namedtuples as database records with loop
tagged with: numpy
has comment: http://stackoverflow.com/comment/90242116
score: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90074827
type: QuestionComment
comment on: http://stackoverflow.com/q/51554027
score: 0
has text: Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the [How to Ask](https://stackoverflow.com/help/how-to-ask) page for help clarifying this question.
type: Comment

http://stackoverflow.com/comment/90012954
type: QuestionComment
has text: yes, and your question is a duplicate of that question
comment on: http://stackoverflow.com/q/51506378
score: 0
type: Comment

http://stackoverflow.com/q/51526242
linked to: http://stackoverflow.com/q/40018398
tagged with: python-internals
has title: Why do two identical lists have a different memory footprint?
possible better answer: http://stackoverflow.com/a/51526419
score: 171
upvote count: 173
tagged with: python
has answer: http://stackoverflow.com/a/51526419
type: AnsweredQuestion
tagged with: memory-management
tagged with: list
accepted answer: http://stackoverflow.com/a/51526385
downvote count: 2
has body: I created two lists l1 and l2, but each one with a different creation method: import sys l1 = [None] * 10 l2 = [None for _ in range(10)] print('Size of l1 =', sys.getsizeof(l1)) print('Size of l2 =', sys.getsizeof(l2)) But the output surprised me: Size of l1 = 144 Size of l2 = 192 The list created with a list comprehension is a bigger size in memory, but the two lists are identical in Python otherwise. Why is that? Is this some CPython internal thing, or some other explanation?
type: Question
has comment: http://stackoverflow.com/comment/90021361
has comment: http://stackoverflow.com/comment/90021259
has answer: http://stackoverflow.com/a/51619941
answer count: 3
has answer: http://stackoverflow.com/a/51526385
favorite count: 0

http://stackoverflow.com/q/51547847
type: AnsweredQuestion
has body: This is the data User Date Status 1 1/1/2018 A 1 1/2/2018 B 1 1/3/2018 C 2 1/4/2018 D 2 1/5/2018 E 3 1/6/2018 F 3 1/7/2018 G 3 1/8/2018 H I'm trying to get to this User Date Status Previous 1 1/1/2018 A NaN 1 1/2/2018 B A 1 1/3/2018 C B 2 1/4/2018 D NaN 2 1/5/2018 E D 3 1/6/2018 F NaN 3 1/7/2018 G F 3 1/8/2018 H G I've tried to use the shift method but can't figure out what I'm doing wrong. df.sort_values(by=['user', 'date'], ascending=True, inplace=True) df.set_index(['user', 'date'], inplace=True) df['Previous'] = np.nan for idx in df.index.levels[0]: df.Previous[idx] = df.Status[idx].shift()
downvote count: 0
duplicate of: http://stackoverflow.com/q/26280345
type: Question
upvote count: 2
has title: Python Pandas - New column based on previous value in another column by group
answer count: 1
has comment: http://stackoverflow.com/comment/90063434
linked to: http://stackoverflow.com/q/26280345
tagged with: pandas
has answer: http://stackoverflow.com/a/51547867
accepted answer: http://stackoverflow.com/a/51547867
favorite count: 0
has comment: http://stackoverflow.com/comment/90063463
tagged with: python
score: 2

http://stackoverflow.com/q/51598727
tagged with: datetime
tagged with: python
has body: I have a column with datetime.datetime objects as its contents. I'm trying to use pyspark.sql.Window functionality, which requires a numeric type, not datetime or string. So my plan is to convert the datetime.datetime object to a UNIX timestamp: Setup: &gt;&gt;&gt; import datetime; df = sqlContext.createDataFrame( ... [(datetime.datetime(2018, 1, 17, 19, 0, 15),), ... (datetime.datetime(2018, 1, 17, 19, 0, 16),)], ['dt']) &gt;&gt;&gt; df DataFrame[dt: timestamp] &gt;&gt;&gt; df.dtypes [('dt', 'timestamp')] &gt;&gt;&gt; df.show(5, False) +---------------------+ |dt | +---------------------+ |2018-01-17 19:00:15.0| |2018-01-17 19:00:16.0| +---------------------+ Define a function to access the timestamp function of a datetime.datetime object: def dt_to_timestamp(): def _dt_to_timestamp(dt): return int(dt.timestamp() * 1000) return func.udf(_dt_to_timestamp) Apply that function: &gt;&gt;&gt; df = df.withColumn('dt_ts', dt_to_timestamp()(func.col('dt'))) &gt;&gt;&gt; df.show(5, False) +---------------------+-------------+ |dt |dt_ts | +---------------------+-------------+ |2018-01-17 19:00:15.0|1516237215000| |2018-01-17 19:00:16.0|1516237216000| +---------------------+-------------+ &gt;&gt;&gt; df.dtypes [('dt', 'timestamp'), ('dt_ts', 'string')] I'm not sure why this column defaults to string when the inner _dt_to_timestamp function returns an int, but let's try to cast these "string-integers" to IntegerTypes: &gt;&gt;&gt; df = df.withColumn('dt_ts', func.col('dt_ts').cast(IntegerType())) &gt;&gt;&gt; df.show(5, False) +---------------------+-----+ |dt |dt_ts| +---------------------+-----+ |2018-01-17 19:00:15.0|null | |2018-01-17 19:00:16.0|null | +---------------------+-----+ &gt;&gt;&gt; df.dtypes [('dt', 'timestamp'), ('dt_ts', 'int')] This seems to be only an issue for IntegerType coercion. For DoubleTypes, the conversion works, but I'd prefer integers... &gt;&gt;&gt; df = df.withColumn('dt_ts', dt_to_timestamp()(func.col('dt'))) &gt;&gt;&gt; df = df.withColumn(…
accepted answer: http://stackoverflow.com/a/51598764
upvote count: 1
type: AnsweredQuestion
score: 1
tagged with: pyspark
has title: PySpark: cast "string-integer" column to IntegerType
type: Question
has answer: http://stackoverflow.com/a/51598764
tagged with: types
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51574485
accepted answer: http://stackoverflow.com/a/51578052
tagged with: python
linked to: http://stackoverflow.com/q/51864822
has comment: http://stackoverflow.com/comment/90139458
type: AnsweredQuestion
has title: Match keywords in pandas column with another list of elements
type: Question
score: 5
linked to: http://stackoverflow.com/q/51589060
has answer: http://stackoverflow.com/a/51578052
upvote count: 5
has answer: http://stackoverflow.com/a/51574671
has body: I have a pandas dataframe as: word_list ['nuclear','election','usa','baseball'] ['football','united','thriller'] ['marvels','hollywood','spiderman'] .................... .................... .................... I also have multiple number of lists with categories names,something as:- movies=['spiderman','marvels','thriller']' sports=['baseball','hockey','football'], politics=['election','china','usa'] and many others categories. All I want to match the keywords of pandas column word_list with my categories lists and assign the corresponding lists name in seperate column if keywords gets matched together and if any keywords not gets matched in any of the list then simply put as miscellaneous So, output I'm looking for as:- word_list matched_list_names ['nuclear','election','usa','baseball'] politics,sports,miscellaneous ['football','united','thriller'] sports,movies,miscellaneous ['marvels','spiderman','hockey'] movies,sports .................... ..................... .................... ..................... .................... .................... I successfully get the match keywords as:- for i in df['word_list']: for j in movies: if i in j: print (i) but this gives me the list of matched keywords. How I get the list names and add it into pandas column?
answer count: 2
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/90132834
possible better answer: http://stackoverflow.com/a/51574671
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51550692
has body: I recently studied a python recursion function and found that the recursion stops when it uses element in []. So I made a simple test function, found that there is even no print out. So how can I understand the element in []? Why does the function stop when referring to element in []? b=1 def simple(): for i in []: print('i am here') return i+b a = simple()
type: Question
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90068651
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51550760
tagged with: python
has title: python what's the element in []
tagged with: list
has answer: http://stackoverflow.com/a/51551915
has answer: http://stackoverflow.com/a/51550784

http://stackoverflow.com/q/51564260
has answer: http://stackoverflow.com/a/51564845
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/90095538
has answer: http://stackoverflow.com/a/51564354
score: 1
has answer: http://stackoverflow.com/a/51564424
has body: Example to illustrate: &gt;&gt;&gt; a = dict(eggs='eggs', spam='spam') &gt;&gt;&gt; b = dict(spam='spam', ham='ham') &gt;&gt;&gt; dict(a.items() | b.items()) {'eggs': 'eggs', 'ham': 'ham', 'spam': 'spam'} Meanwhile... &gt;&gt;&gt; dict(a.items() + b.items()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items' Is there a reason for this? Wouldn't it be reasonable to assume that addition and union should do the same for dictionaries? In Python 2 this works perfectly fine: &gt;&gt;&gt; dict(a.items() + b.items()) {'eggs': 'eggs', 'ham': 'ham', 'spam': 'spam'} Although in Python 2 .items() returns a regular list (in contrast to dict_items), so maybe it's by accident. Finally, I don't think "what happens if keys have different values"-dilemma applies here as operator | doesn't seem to mind anyway (one of two values is selected seemingly at random).
answer count: 3
upvote count: 1
has title: Why dictionaries (dict_items) support union (__or__) but not addition (__add__)?
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51534605
has comment: http://stackoverflow.com/comment/90037335
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51542394
score: -1
type: Question
has comment: http://stackoverflow.com/comment/90036881
tagged with: for-loop
answer count: 1
has body: The list: li=['check3_dwg_Polyline', 'check2_dwg_Polyline', 'check3_dwg_Polyline_feat_to_polyg',# this will not be needed to extracted 'check2_dwg_Polyline_feat_to_polyg',# &gt;&gt; &gt;&gt; 'check3_dwg_Polyline_feat_to_polyg_feat_to_line', 'check2_dwg_Polyline_feat_to_polyg_feat_to_line'] Purpose Put the parameters as this: erase('check3_dwg_Polyline','check3_dwg_Polyline_feat_to_polyg_feat_to_line','output_name') Useful info: tried sorting the list but didn't fix it. The purpose is to extract the files from the list and put them in the function erase through a loop. Like this: erase('check3_dwg_Polyline','check3_dwg_Polyline_feat_to_polyg_feat_to_line','output_name') I tried: a=[li[i:i+3] for i in range(0, len(li), 3)] for base, base_f, base_line in a: print(base, base_line, base + "_output") # when it is fixed the # print will be replaced with # 'erase' to form the function and it gives: check2_dwg_Polyline_feat_to_polyg check2_dwg_Polyline_feat_to_polyg_feat_to_line check2_dwg_Polyline_feat_to_polyg_output check3_dwg_Polyline check3_dwg_Polyline_feat_to_polyg check3_dwg_Polyline_output while it should: check3_dwg_Polyline check3_dwg_Polyline_feat_to_polyg_feat_to_line check3_dwg_Polyline_output check2_dwg_Polyline check2_dwg_Polyline_feat_to_polyg_feat_to_line check2_dwg_Polyline_output so later it can be put to function like this: erase('check3_dwg_Polyline','check3_dwg_Polyline_feat_to_polyg_feat_to_line','output_name')
has comment: http://stackoverflow.com/comment/90037988
tagged with: data-analysis
has title: Put parameters of a function with for loop from list
tagged with: python
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51487627
accepted answer of: http://stackoverflow.com/q/51487582
answers question: http://stackoverflow.com/q/51487582
has body: You can't have multiple Tk objects with their own mainloops. Or, rather, you can, but whichever one is currently running mainloop, none of the others (and none of their children) gets to do anything until that mainloop finishes. What you want is to have multiple Toplevel widgets, with the same Tk as their master. (If you just have one Tk, as you usually do, you can leave that as the default.) But you have another, equally serious problem here. You're creating a Calculator with a bunch of Tk vars attached, then immediately trying to read those vars and do something with them. You can't do that. What you need to do is to put all of that in the callback to some kind of user event, like clicking the Results button. You have one more problem in your code that makes things a bit harder: Number1=Number1.get() What you really want here is two separate variables, one the Tk var, and the other an int. And then you need to make the Tk var accessible in the results callback in some way. The obvious way is to move all of this to a class, and store all your Tk vars as instance attributes. If you don't know how to do that, you can always use globals. (Not ideal, but until you learn classes, it's fine.) Then the actual numbers are just local to the callback function. Putting it all together: def Calculator(root): global Number1, Number2, Operator calculator = Toplevel() Number1 = DoubleVar() Number2 = DoubleVar() Operator = IntVar() Operator.set(1) Entry(calculator,textvariable=Number1,justify="c").grid() Entry(calculator,textvariable=Number2,justify="c").grid() Radiobutton(calculator,text="Add",variable=Operator,value=1).grid() Radiobutton(calculator,text="Subtract",variable=Operator,value=2).grid() Radiobutton(calculator,text="Multiply",variable=Operator,value=3).grid() Radiobutton(calculator,text="Divide",variable=Operator,value=4).grid() Radiobutton(calculator,text="Square",variable=Operator,value=5).grid() Radiobutton(calculator,text="Square root",variable=Operator,value=6).gr…
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89944856
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/90061913
has text: I can't remember where I read it, but I think I read you must turn off "auto-exposure" as well as set a manual one. I may be wrong - I often am!
score: 1
comment on: http://stackoverflow.com/q/51546787
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51518382
type: Question
has body: Name Class Marks1 Marks2 AA CC 10 AA CC 33 AA CC 21 AA CC 24 I want to transform data in the above format into Name Class Marks1 Marks2 AA CC 10 33 AA CC 21 24 How should i achieve the result? PS- This is just an example of the data the data is too big and has many more columns and it can have many such rows. How should i remove the duplicate rows without affecting the data quality.
tagged with: dataframe
has answer: http://stackoverflow.com/a/51518441
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/43119503
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Group a column when none of the rows are unique into one using pandas
has comment: http://stackoverflow.com/comment/90005367
upvote count: 1

http://stackoverflow.com/comment/90007564
has text: @jpp. I did think that before I started writing an answer though. They problems are very closely related, but I couldn't come up with a nice generator that I could just call next on or run to completion since we're removing elements here.
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51518791

http://stackoverflow.com/a/51530330
type: Answer
answers question: http://stackoverflow.com/q/51530216
has body: You can use the __dict__ attribute to get a dict of all the attributes of an object. class A(): def __init__(self,b,c): self.b = b self.c = c def get_dict(self): return self.__dict__ print(A(1, 2).get_dict()) This outputs: {'b': 1, 'c': 2}
score: 0

http://stackoverflow.com/comment/89973439
comment on: http://stackoverflow.com/a/51502497
has text: @MadPhysicist sure, have a go at it =)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90086210
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51556743
type: AnswerComment
has text: Hmm... Is there a simple answer what the correct projection is? What are the main differences between 4326 and 5243?

http://stackoverflow.com/comment/89993933
type: Comment
type: QuestionComment
has text: you are expecting two values(n, row) for each iteration(tuple of length 2) but there are more values than that.
comment on: http://stackoverflow.com/q/51512356
score: 0

http://stackoverflow.com/a/51527369
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51526759
answers question: http://stackoverflow.com/q/51526759
type: Answer
has comment: http://stackoverflow.com/comment/90025252
has body: Here is something that should work to append the extra text to the previous line. This is checking whether the regex fails, in which case just write the line to the file without a newline \n so it just appends to the previous line in the file. start = True with open('chat.txt', "r") as infile, open("Output.txt", "w") as outfile: for line in infile: time = re.search(r'(?&lt;=\[)[^]]+(?=\])', line) sender = re.search(r'(?&lt;=\] )[^]]+(?=\:)', line) if sender and time: date = datetime.strptime( time.group(), '%d/%m/%Y, %H:%M:%S') sender = sender.group() text = line.rsplit(r'].+: ', 1)[-1] new_line = str(date) + ',' + sender + ',' + text if not start: new_line = '\n' + new_line outfile.write(new_line) else: outfile.write(' ' + line) start = False It also looks like you weren't writing new lines to the file even when the regex worked, so I added that in too.
downvote count: 0
score: 1

http://stackoverflow.com/q/51529272
score: 0
type: AnsweredQuestion
has title: Making Ansible use non-empty shell environment
type: Question
tagged with: python-2.7
tagged with: ansible
has answer: http://stackoverflow.com/a/51547276
answer count: 1
has body: When executing ad-hoc commands or play-books, I am running into a situation where the ENV Vars from the /home/user-that-sudoed/.bashrc needs to be read for the ad-hoc command or playbook to work on the destination inventory host. Inside that .bashrc file we have setup LD_LIBRARY_PATH (necessary for some of the Python functions we are using). Is there a parameter in /home/local-user/.ansible.cfg that can effectively turn "/bin/sh -c" into "/bin/sh" with no "-c"? the "-c" (command run is below). ssh -q -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/tmp/.ansible/sockets/5c2164546a zlpv1229 '/bin/sh -c '"'"'sudo -H -S -n -u atg /bin/sh -c '"'"'"'"'"'"'"'"'echo BECOME-SUCCESS-cyhlvtntyqmbkkmcpkhhkspusdirgwlk; /sites/utils/bin/python'"'"'"'"'"'"'"'"' &amp;&amp; sleep 0'"'"'' The connection is made as "user@controller to user@inventory_host, then user@inventory_host is becoming 'user-that-sudoed'
tagged with: python
tagged with: ansible-2.x
accepted answer: http://stackoverflow.com/a/51547276

http://stackoverflow.com/q/51611533
possible better answer: http://stackoverflow.com/a/51611830
type: Question
has comment: http://stackoverflow.com/comment/90187787
answer count: 2
has body: Guys, I have a df like this : A B C D E Yes 14 12 123 153 178 0 13 1 435 55 87 0 14 12 123 1 435 0 ...... 15 0 125 66 90 0 Let us say, we have two variable x and y, are integer. I want to change the 'Yes' column to '1' if any one of following conditions are fulfilled : df.D &lt; x and df.E &gt; x df.D &gt; x and df.E &gt; y df.D &gt; y and df.E &gt; y Besides, I am sure df.E is always larger than df.D in those raw data. How can I do it quickly ? I tried to write some expression based on that, but all have some problems ... Really appreciate.
has answer: http://stackoverflow.com/a/51611665
accepted answer: http://stackoverflow.com/a/51611665
tagged with: pandas
has title: Change column value on rows which fulfilled conditions in DataFrame
upvote count: 1
has answer: http://stackoverflow.com/a/51611830
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: dataframe

http://stackoverflow.com/comment/90184840
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51609426
has text: Tim thanks for clarifying I missed that point on your question. I just tested locally using a file and the validated json from you and it does work without problems. I cannot replicate it either using your original code or the code of @roganjosh.
score: 0

http://stackoverflow.com/a/51621443
downvote count: 0
type: Answer
has body: Write a function that you can apply to your dataframe rather than using iterrows match_set = set(ms.split()) def check_matches(row): return row['value'] if row['string'] in match_set else None df['matched'] = df.apply(check_matches, axis=1) Which gives you: priority string value matched 0 1 hi 2 NaN 1 10 astronaut 3 NaN 2 3 overflow -1 -1.0 3 4 varfoo 1 NaN 4 2 hello 0 0.0 Then you can sort the values and take the first non NaN value from df.matched to get what you called final_value. df.sort_values('priority').matched.dropna().iloc[0] 0.0 Alternatively, you could sort and convert the df into a list of tuples: l = df.sort_values('priority').apply(lambda r: (r['string'], r['value']), axis=1).tolist() Giving: l [('hi', 2), ('hello', 0), ('overflow', -1), ('varfoo', 1), ('astronaut', 3)] And write a function that stops when it hits the first match: def check_matches(l): for (k, v) in l: if k in match_set: return v check_matches(l) 0
has comment: http://stackoverflow.com/comment/90208717
upvote count: 1
has comment: http://stackoverflow.com/comment/90209732
has comment: http://stackoverflow.com/comment/90208795
score: 1
accepted answer of: http://stackoverflow.com/q/51621190
answers question: http://stackoverflow.com/q/51621190
type: AcceptedAnswer

http://stackoverflow.com/q/51486510
has answer: http://stackoverflow.com/a/51486553
has title: Zipping a list with a list of lists in python
tagged with: python
tagged with: dictionary
has body: is there a way to zip a list with a list of lists? So for example you have the two lists: lst1 = ['food', 'drinks', 'sports'] lst2 = [['hamburger', 'beer', 'football'], ['cheeseburger', 'wine', 'tennis']] And then as a result u would get: [{'food':'hamburger', 'drinks':'beer', 'sports':'football'}, {'food':'cheeseburger', 'drinks':'wine', 'sports':'tennis'}] Is there a way to do this?
type: AnsweredQuestion
tagged with: list
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/51486553
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/zip

http://stackoverflow.com/comment/90111719
score: 0
has text: What exactly is the ```Images``` object that you are passing?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51569370

http://stackoverflow.com/q/51510107
type: AnsweredQuestion
has title: Customizing the Y-Axis scale in Matplotlib
has answer: http://stackoverflow.com/a/51546383
type: Question
tagged with: quantitative-finance
tagged with: matplotlib
score: 0
answer count: 1
tagged with: axis-labels
accepted answer: http://stackoverflow.com/a/51546383
tagged with: candlestick-chart
tagged with: python
has body: I have plotted some horizontal lines on a Candlestick OHLC chart; however, my objective is to get the chart to show the value of each of these lines on the Y-Axis. This is my code: plt.figure( 1 ) plt.title( 'Weekly charts' ) ax = plt.gca() minor_locator_w = allweeks major_formatter_w = yearFormatter ax.xaxis.set_minor_locator( minor_locator_w ) ax.xaxis.set_major_formatter( major_formatter_w ) candlestick_ohlc(ax, zip(df_ohlc_w[ 'Date2' ].map( mdates.datestr2num ), df_ohlc_w['Open'], df_ohlc_w['High' ], df_ohlc_w['Low'], df_ohlc_w['Close']), width=0.6, colorup= 'g' ) ax.xaxis_date() ax.autoscale_view() plt.setp(ax.get_xticklabels(), horizontalalignment='right') historical_prices_200 = [ 21.53, 22.09, 22.31, 22.67 ] horizontal_lines = historical_prices_200 x1 = Date2[ 0 ] x2 = Date2[ len( Date2 ) - 1 ] plt.hlines(horizontal_lines, x1, x2, color='r', linestyle='-') plt.show() This is the output that I am getting: Is there a way to show all the prices on the Y-Axis?

http://stackoverflow.com/comment/89985868
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51508104
has text: @ialarmedalien it's not so much about creating the list but using it in the final print statements is the issue for me.

http://stackoverflow.com/comment/90206863
type: QuestionComment
has text: Thank you for your help Naveen! adding the "driver.switch_to.frame()" line helped fix the issue I was having.
score: 1
comment on: http://stackoverflow.com/q/51548202
type: Comment

http://stackoverflow.com/comment/90206099
has text: Yes, that is correct. It is nothing special with the fact that they are imports, it is just that Python executes the outermost layer of the file top-down. Hence why we usually place imports at the top (to have them be imported before anything else can run).
comment on: http://stackoverflow.com/a/51619934
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90184776
has text: Its common practice to train your embeddings on a huge dataset, like wikipedia and then reuse the embedding for your task. You can use pretrained Glove, word2vec or fastText embeddings for example. Or you can use subword embeddings.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51608893

http://stackoverflow.com/a/51625420
score: 0
type: Answer
has body: I think you having ImportError for import pyautogui try this, import error for pyautogui
answers question: http://stackoverflow.com/q/51625388

event-handling
tag name: event-handling
tags question: http://stackoverflow.com/q/51538871
type: Tag

http://stackoverflow.com/comment/90030610
type: Comment
comment on: http://stackoverflow.com/a/51512461
score: 0
type: AnswerComment
has text: `df = df.reset_index(drop=True)` this worked...thanks a lot

http://stackoverflow.com/q/51525036
tagged with: image-processing
tagged with: analysis
type: Question
has title: How to find the success rate of a clustering algorithm?
accepted answer: http://stackoverflow.com/a/51525403
tagged with: cluster-analysis
upvote count: 14
linked to: http://stackoverflow.com/q/13974167
has answer: http://stackoverflow.com/a/51525403
answer count: 1
downvote count: 1
has body: I have implemented several clustering algorithms on an image dataset. I'm interested in deriving the success rate of clustering. I have to detect the tumor area, in the original image I know where the tumor is located, I would like to compare the two images and obtain the percentage of success. Following images: Original image: I know the position of cancer Image after clustering algorithm I'm using python 2.7.
favorite count: 0
has comment: http://stackoverflow.com/comment/90019381
linked to: http://stackoverflow.com/q/14697442
tagged with: python
score: 13
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/189943

http://stackoverflow.com/q/51565270
tagged with: testing
answer count: 1
downvote count: 0
tagged with: django-testing
accepted answer: http://stackoverflow.com/a/51565529
favorite count: 0
has title: Runserver in "test-mode" with test databases
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51565529
score: 1
has body: I'm trying to create tests for my Django application but I'm having some trouble creating a test database. I'd like to keep the existing structure while entering new curated test-information, creating test users, uploading test content, etc. Which I can then populate a test database with so that I have curated data on which I can test edge-cases. Creating a test database seems simple, just run python manage.py test --keepdb. Getting entries into it seems more difficult. Is it possible to run Django in "test mode" with the test database being used so that I can use the website UI to enter all the data, or is there some other better way to do it entirely?
type: Question

oop
tags question: http://stackoverflow.com/q/51604126
tags question: http://stackoverflow.com/q/51551588
tags question: http://stackoverflow.com/q/51594288
tags question: http://stackoverflow.com/q/51571191
tag name: oop
tags question: http://stackoverflow.com/q/51546989
tags question: http://stackoverflow.com/q/51503271
tags question: http://stackoverflow.com/q/51583944
tags question: http://stackoverflow.com/q/51509531
tags question: http://stackoverflow.com/q/51483516
tags question: http://stackoverflow.com/q/51561710
tags question: http://stackoverflow.com/q/51612985
tags question: http://stackoverflow.com/q/51517548
tags question: http://stackoverflow.com/q/51587098
tags question: http://stackoverflow.com/q/51579559
tags question: http://stackoverflow.com/q/51570985
tags question: http://stackoverflow.com/q/51569298
tags question: http://stackoverflow.com/q/51550426
tags question: http://stackoverflow.com/q/51628525
tags question: http://stackoverflow.com/q/51514472
tags question: http://stackoverflow.com/q/51491325
tags question: http://stackoverflow.com/q/51502156
tags question: http://stackoverflow.com/q/51491782
tags question: http://stackoverflow.com/q/51564071
tags question: http://stackoverflow.com/q/51598247
tags question: http://stackoverflow.com/q/51494650
type: Tag
tags question: http://stackoverflow.com/q/51604638
tags question: http://stackoverflow.com/q/51583119

http://stackoverflow.com/q/51631788
score: 1
type: Question
answer count: 1
downvote count: 0
tagged with: pandas
upvote count: 1
tagged with: python
favorite count: 0
has title: counting number of occurrences in multiple pandas columns
has answer: http://stackoverflow.com/a/51631883
accepted answer: http://stackoverflow.com/a/51631883
has body: dg se 29 10 37 22 3 13 15 7 42 20 31 23 26 17 7 1 36 19 5 7 21 5 37 13 37 6 2 24 In the dataframe above, I want to count the percentage of occurences in each column of values between 0 - 30, 30 - 40 and > 40; and also percentage of occurrences where both columns have values between 0 - 30 and 30 - 40. I was thinking of using pandas histfunction but that does not do what I want
type: AnsweredQuestion

http://stackoverflow.com/a/51636467
has comment: http://stackoverflow.com/comment/90239872
has comment: http://stackoverflow.com/comment/90239748
accepted answer of: http://stackoverflow.com/q/51634350
answers question: http://stackoverflow.com/q/51634350
score: 0
has body: You could do your manipulations after import: from io import StringIO import numpy as np datafile = StringIO("""FICHE CLIMATOLOGIQUE; ; Statistiques 1981-2010 et records; PARIS-MONTSOURIS (75) Indicatif : 75114001, alt : 75m, lat : 48°49'18"N, lon : 02°20'12"E; Edité le : 18/12/2017 dans l'état de la base; ; Janv.; Févr.; Mars; Avril; Mai; Juin; Juil.; Août; Sept.; Oct.; Nov.; Déc.; Année; La température la plus élevée (°C); (Records établis sur la période du 01-06-1872 au 03-12-2017); ; 16.1; 21.4; 25.7; 30.2; 34.8; 37.6; 40.4; 39.5; 36.2; 28.9; 21.6; 17.1; 40.4; Date ; 05-1999; 28-1960; 25-1955; 18-1949; 29-1944; 26-1947; 28-1947; 11-2003; 07-1895; 01-2011; 07-2015; 16-1989; 1947; Température maximale (Moyenne en °C); ; 7.2; 8.3; 12.2; 15.6; 19.6; 22.7; 25.2; 25; 21.1; 16.3; 10.8; 7.5; 16; Température moyenne (Moyenne en °C); ; 4.9; 5.6; 8.8; 11.5; 15.2; 18.3; 20.5; 20.3; 16.9; 13; 8.3; 5.5; 12.4; Température minimale (Moyenne en °C); ; 2.7; 2.8; 5.3; 7.3; 10.9; 13.8; 15.8; 15.7; 12.7; 9.6; 5.8; 3.4; 8.9;""") df = pd.read_table(datafile, sep=';', index_col=0, skiprows=7, header=0, skip_blank_lines=True, skipinitialspace=True) df1 = pd.DataFrame(df.values[~df.isnull().all(axis=1),:], index=df.index.dropna()[np.r_[0,2:6]], columns=df.columns) df_out = df1.dropna(how='all',axis=1) print(df_out) Output: Janv. Févr. Mars Avril \ La température la plus élevée (°C) 16.1 21.4 25.7 30.2 Date 05-1999 28-1960 25-1955 18-1949 Température maximale (Moyenne en °C) 7.2 8.3 12.2 15.6 Température moyenne (Moyenne en °C) 4.9 5.6 8.8 11.5 Température minimale (Moyenne en °C) 2.7 2.8 5.3 7.3 Mai Juin Juil. Août \ La température la plus élevée (°C) 34.8 37.6 40.4 39.5 Date 29-1944 26-1947 28-1947 11-2003 Température maximale (Moyenne en °C) 19.6 22.7 25.2 25 Température moyenne (Moyenne en °C) 15.2 18.3 20.5 20.3 Température minimale (Moyenne en °C) 10.9 13.8 15.8 15.7 Sept. Oct. Nov. Déc. Année La température la plus élevée (°C) 36.2 28.9 21.6 17.1 40.4 Date 07-1895 01-2011 07-2015 1…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90239777
type: Answer
has comment: http://stackoverflow.com/comment/90239970

http://stackoverflow.com/a/75100290
type: Answer
has body: I think the answer is that you can do this, but no current package really handles RTL languages well, so you're going to have to do some mopping up after whichever one you use. I've had some success extracting Arabic text from (born digital) PDFs using pdfplumber. By "some success" I mean that it was a huge pain in the... neck, and didn't end up being accurate enough for my purposes. The pain part was because the extracted text was backwards and it had inserted a space next to every diacritic. (I imagine you would need to get rid of the zero-width ligature in Persian either as a pre- or post-processing step.) In Arabic, at least, those were fixable — some code is below. But the accuracy problem was because I was using a PDF of an Arabic novel that was written in a pretty font where some of the letters are kind of stacked on top of each other. pdfplumber was mostly able to extract what letters were there, but not which order. (Not surprising — this is tough for human students of Arabic as well.) I'm not sure if Persian has the same issue. But if your source is using a plain font you might have better results. The text in the sample below should read: في رأس النهج تبينت مدقة الباب النحاسية التي استقرت فوق الخد الخشبي الضخم علي هيئة قبضة يد نصف مضمومة. الهدوء import pdfplumber file = 'sample_page.pdf' pdf = pdfplumber.open(file) page = pdf.pages[0] text = page.extract_text() print(text[:110]) output: دّ لخا قوف ترّ قتسا يتلا ةيّ ساحنلا بابلا ةقّ دم تنيّ بت جهنلا سأر في لاإ مٌ يّ مخ ءودلها .ةمومضم فصن دي ةض ^ This is backwards and all there are spaces next to the diacritics # Reverse text with bidi from bidi import algorithm text_rev = algorithm.get_display(text) print(text_rev[:110]) output: يف رأس النهج تب ّينت مد ّقة الباب النحاس ّية التي استق ّرت فوق اخل ّد اخلشب ّي الضخم عىل هيئة قبضة يد نصف مضم ^ Not backwards anymore, but still the diacritic problem # Strip most common diacritic — in real use you would need to get all of them shadda = unichr(0x0651) text_rev_dedi…
answers question: http://stackoverflow.com/q/51511345
score: 0

http://stackoverflow.com/q/51580190
tagged with: http://stackoverflow.com/tag/html
answer count: 1
tagged with: beautifulsoup
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51580255
tagged with: web-scraping
has title: BeautifulSoup won't find tag
type: Question
has answer: http://stackoverflow.com/a/51580255
tagged with: tags
has body: I've read in some HTML from a website that I'm trying to parse into a soup object. After that I have extracted the body of the HTML which I have looked at and seen that it does contain the items that I'm looking for. The items that I'm looking for are contained inside &lt;div&gt; tags, with class = 'listitem artikal obicniArtikal imaHover-disabled i index'. Now I'm trying to do do: r = requests.get('https://www.olx.ba/pretraga?trazilica=golf+2', timeout=5) soup = BeautifulSoup(r.text, 'html.parser') body = soup.find('div', attrs={'id':'rezultatipretrage'}) all_items = body.find_all('div', class_='listitem artikal obicniArtikal imaHover-disabled i index') print(all_items) all_items returns an empty list even though the tags are present in the body. I would be sincerely grateful if anybody would tell me what's going on.
score: 0

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/51548211
type: Tag

http://stackoverflow.com/a/51579841
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51579798
type: AcceptedAnswer
has body: If settingN is a dict, you can do this: argZ = settingN.get('z', default_value) So, if settingN doesn't have the key 'z', default_value will be returned.
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51579798

http://stackoverflow.com/comment/90265946
has text: Honestly, `place` almost never is the best solution. With `pack` and `grid` you can make almost anything you want. If you can't figure it out, you could of course always ask a new question.
comment on: http://stackoverflow.com/a/51635109
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/90091623
score: 0
type: AnswerComment
has text: Paste full code (I already provided a smal reproducable piece). I still get the error when I replace `handling` with `zzz` : usage: argtest.py [-h] operations [operations ...] furniture color [zzz]
type: Comment
comment on: http://stackoverflow.com/a/51559070

http://stackoverflow.com/comment/90059923
type: QuestionComment
comment on: http://stackoverflow.com/q/51545659
score: 0
has text: in this case, we have something on the order of ~10^3 columns, so it is not a square matrix. I hadn't thought about the null spaces, thanks for brining that up
type: Comment

memoization
type: Tag
tags question: http://stackoverflow.com/q/51585130
tag name: memoization
tags question: http://stackoverflow.com/q/51623807

http://stackoverflow.com/a/52628937
score: 5
type: Answer
answers question: http://stackoverflow.com/q/51549804
upvote count: 5
downvote count: 0
has body: In order to get two geopandas maps side by side, you can write: fig, (ax1,ax2) = plt.subplots(nrows=1, ncols=2, figsize=(20, 16)) ax1 = geodataframe.plot(ax=ax1, column='obs', legend=True) ax2 = geodataframe.plot(ax=ax2, column='pred', legend=True)

http://stackoverflow.com/q/51489500
type: UnansweredQuestion
type: Question
score: 1
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51496629
upvote count: 2
has title: raise JSONDecodeError("Expecting value", s, err.value) from None JSONDecodeError: Expecting value
answer count: 1
downvote count: 1
favorite count: 0
has body: Python 3.6 I am trying to use python to crawl the location of bus stop within an area from Google Maps. I have read similar questions but still did not find a solution. File "d:\ProgramData\Anaconda3\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None JSONDecodeError: Expecting valueHere is the code Traceback: Traceback (most recent call last): File "", line 1, in runfile('D:/Dropbox/Lisa/CRC/BusStop/google_place.py', >wdir='D:/Dropbox/Lisa/CRC/BusStop') File "D:/ProgramData/Anaconda3/lib/site->packages/spyder/utils/site/sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "D:/ProgramData/Anaconda3/lib/site->packages/spyder/utils/site/sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "D:/Dropbox/Lisa/CRC/BusStop/google_place.py", line 123, in main() File "D:/Dropbox/Lisa/CRC/BusStop/google_place.py", line 117, in main for st, st_lat, st_lng, buses in nearby_bus_stations(lat, lng, apikeys): File "D:/Dropbox/Lisa/CRC/BusStop/google_place.py", line 73, in >nearby_bus_stations "&amp;rankby=distance&amp;language=zh-TW&amp;type=bus_station") File "D:/Dropbox/Lisa/CRC/BusStop/google_place.py", line 48, in get_web_json return json.loads(dataform.decode("utf8")) File "d:\ProgramData\Anaconda3\lib\json__init__.py", line 354, in loads return _default_decoder.decode(s) File "d:\ProgramData\Anaconda3\lib\json\decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "d:\ProgramData\Anaconda3\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None JSONDecodeError: Expecting value Here is the complete code: #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import json from urllib.request import urlopen, Request from lxml import html import random def warning(msg): sys.stderr.write("Warning: %s\n" % msg) def dump_list(ls): return '[' + ','.join(ls) + ']' def get_…
has comment: http://stackoverflow.com/comment/89947807
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/q/51530981
upvote count: 1
downvote count: 1
tagged with: string
possible better answer: http://stackoverflow.com/a/51531499
favorite count: 0
has comment: http://stackoverflow.com/comment/90030732
accepted answer: http://stackoverflow.com/a/51531608
tagged with: python
has title: Search for a set of letters in a given string - Python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90029808
has body: I'm trying to check if the emblem is contained in the userString. For emblem to be contained in userString, the characters in emblem should appear in userString. Python code is as follows: emblem = "mammoth" userEntered = "zmzmzmzaztzozh" print(emblem) print(userEntered) found = emblem in userEntered print(found) In the above case, the word mammoth does appear in zmzmzmzaztzozh (the characters m, a, o, t, h are all in zmzmzmzaztzozh), but still I get found = false. Is there a way to check if a given word appears in a scrambled string without using regular expressions in Python?
has comment: http://stackoverflow.com/comment/90030637
has comment: http://stackoverflow.com/comment/90030755
has answer: http://stackoverflow.com/a/51531608
has answer: http://stackoverflow.com/a/51531499
type: Question
has comment: http://stackoverflow.com/comment/90030679
has comment: http://stackoverflow.com/comment/90029842
score: 0
answer count: 2

list-comprehension
tags question: http://stackoverflow.com/q/51573795
tags question: http://stackoverflow.com/q/51590677
tags question: http://stackoverflow.com/q/51548042
tags question: http://stackoverflow.com/q/51546348
tags question: http://stackoverflow.com/q/51548633
tags question: http://stackoverflow.com/q/51624029
tags question: http://stackoverflow.com/q/51512474
tags question: http://stackoverflow.com/q/51527203
tag name: list-comprehension
tags question: http://stackoverflow.com/q/51556631
tags question: http://stackoverflow.com/q/51607847
tags question: http://stackoverflow.com/q/51526547
type: Tag
tags question: http://stackoverflow.com/q/51625009
tags question: http://stackoverflow.com/q/51518189
tags question: http://stackoverflow.com/q/51637323
tags question: http://stackoverflow.com/q/51590304
tags question: http://stackoverflow.com/q/51586643

http://stackoverflow.com/comment/90037849
type: AnswerComment
comment on: http://stackoverflow.com/a/51534811
type: Comment
has text: Sure, as we know that the pattern always starts with numerics (and that there are no other numbers in the string we want to capture). \d means one digit, \d+ means any number of digits, \D means one non digit. So \d+\D+ means any number of digits followed by any number of non-digits.
score: 0

http://stackoverflow.com/q/51616546
tagged with: tweepy
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90199563
type: Question
tagged with: sentiment-analysis
upvote count: 1
has comment: http://stackoverflow.com/comment/90201097
has body: Problem I am a beginner to Python coding and wrote a piece of code that performs sentiment analysis on tweets. The results are displayed as follows : TWEETS (POLARITY_SCORE, SUBJECTIVITY_SCORE) Now, I want to write my results to a CSV file with 3 columns where the first column should be the tweets, the second column should be polarity and the last column subjectivity score. However being new to Python I couldn't figure out how to go about it. I tried some different random techniques but I did not get the desired results. Any help (simple explanation should be enough) in this regard would be of great help. Here is the code I wrote : import tweepy from textblob import TextBlob # Create the authentication package consumer_key = "yiOewPXCYY86sHHKMPUcUP5qj" consumer_secret = "FtSA31g45eZvpT9OJ6kIPOYjGFjYgTdd9BHDDNr8p0RW8AYW5V" access_token = "1016268651211603968-6IAk4SCDprCT83xrsucA9fVBqr1RYF" access_token_secret = "KDQgUklgB08tcfrPL4pCbD3WcuT9N2emuXZ20fhdjSYM5" # Authenticate the app auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) # Search for tweets public_tweets = api.search("Trump") for tweets in public_tweets : # Print the tweets print(tweets.text) # Perform sentiment analysis on tweets analysis = TextBlob(tweets.text) print(analysis.sentiment) print("") What I thought was analysis.sentiment[0] was storing the polarity while analysis.sentiment[1] was storing the subjectivity, however when I tried to do the same and print the results, my answers were different from what I was expecting. OPTIONAL DOUBT (THIS QUESTION NEED NOT HAVE AN ANSWER RIGHT NOW) What would be my approach if I wanted to check if the polarity is greater than a specified value how would I do that?
has title: How do I modify my Python code to separate sentiments from tweets
favorite count: 0
has comment: http://stackoverflow.com/comment/90200375
has comment: http://stackoverflow.com/comment/90200195
has comment: http://stackoverflow.com/comment/90198667
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90025772
has text: That means your `table.index` does not have the same length as `df_pos['BLIP']`. You can use `df_pos.index` instead
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51527617

http://stackoverflow.com/comment/90167373
comment on: http://stackoverflow.com/q/51600182
type: Comment
type: QuestionComment
has text: @sundance is right! I have all my code built up in a way to get the logs on my browser. It's honestly just the structure of how to get every instance of "clear" until the next "clear". The html part shouldn't be hard.
score: 0

http://stackoverflow.com/q/51520985
has answer: http://stackoverflow.com/a/51521501
answer count: 1
accepted answer: http://stackoverflow.com/a/51521501
linked to: http://stackoverflow.com/q/51510081
has body: I have the following: Type RT LT NAID RecordTime "T" "15" "123" "NZ45" "2018-05-30 16:59:00" "S" "34" "210" "NZ45" "2018-05-30 16:59:00" "T" "56" "480" "NZ45" "2018-05-30 16:59:00" "T" "90" "480" "CR98" "2018-05-30 16:59:00" "S" "80" "180" "RU992" "2018-05-30 16:58:00" And I need to sum the RT and LT values based on the Type column and the NAID as you can see below sum the values for the same type and NAID. Type RT LT NAID RecordTime "T" "71" "603" "NZ45" "2018-05-30 16:59:00" "S" "34" "210" "NZ45" "2018-05-30 16:59:00" "T" "90" "480" "CR98" "2018-05-30 16:59:00" "S" "80" "180" "RU992" "2018-05-30 16:58:00" Could you give me a hand?
favorite count: 0
has comment: http://stackoverflow.com/comment/90010755
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/90011031
downvote count: 4
has comment: http://stackoverflow.com/comment/90010971
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90011686
has comment: http://stackoverflow.com/comment/90011001
type: Question
has title: Python sum two columns based on array key
has comment: http://stackoverflow.com/comment/90010969
upvote count: 1

http://stackoverflow.com/comment/99529486
score: 0
comment on: http://stackoverflow.com/a/54737235
type: AnswerComment
type: Comment
has text: This also worked for me. It seems that pip-19.0.1 installed the METADATA file inside a subdirectory with the same name (this is all for the --user option within Windows). I just upgraded to 19.1.1 (python -m pip install --upgrade pip --user), and it seems to have fixed it.

http://stackoverflow.com/q/51619803
accepted answer: http://stackoverflow.com/a/51619903
favorite count: 0
tagged with: memory-management
type: Question
upvote count: 1
tagged with: python
has title: Python Data Structure memory footprint behaving weird
tagged with: programming-pearls
has comment: http://stackoverflow.com/comment/90205875
answer count: 1
has comment: http://stackoverflow.com/comment/90205724
has answer: http://stackoverflow.com/a/51619903
type: AnsweredQuestion
downvote count: 0
has body: I was trying out the one of the programming pearls: Given a file containing at most ten million 7-digit integers with no duplicates. What is an efficient way to print these numbers in ascending order using just 1.5Mb RAM and reading the data just once? What are the consequences of only having 1Mb of RAM and no other storage? How would your answer change if duplicates were permitted? In order to create a test case I, generated 8999999 numbers and wrote them to a file. Then for each line, i started inserting the same to a tree, finally creating a trie structure. Sample Code: from sys import getsizeof tree = dict() xtree = dict() f = open("data2.txt", "r") cnt = 0 for number in f: cnt += 1 currTree = tree xtree[number] = dict() for n in number.strip(): if n not in currTree: currTree[n] = dict() currTree = currTree[n] f.close() print(cnt) print(getsizeof(tree)) print(getsizeof(xtree)) print(tree) sample file data2.txt has 20 records The tree generated is Now the question is that when i do a memory sizing of the tree that is built, at 20 lines it shows a memory foot print of 240 bytes At 100 line, size of tree becomes 368 bytes and at 8999999 lines also it gives 368 bytes I built an auxiliary map named xtree which just feeds in the data The sizes for xtree and tree are in bytes. can anyone please explain how this is so..??
score: 1
has comment: http://stackoverflow.com/comment/90205587

data-science
tags question: http://stackoverflow.com/q/51522743
tags question: http://stackoverflow.com/q/51521351
tags question: http://stackoverflow.com/q/51634774
tags question: http://stackoverflow.com/q/51622452
tags question: http://stackoverflow.com/q/51486083
type: Tag
tags question: http://stackoverflow.com/q/51602386
tags question: http://stackoverflow.com/q/51630106
tags question: http://stackoverflow.com/q/51544927
tags question: http://stackoverflow.com/q/51593843
tags question: http://stackoverflow.com/q/51485289
tags question: http://stackoverflow.com/q/51638837
tags question: http://stackoverflow.com/q/51527264
tags question: http://stackoverflow.com/q/51597842
tags question: http://stackoverflow.com/q/51494887
tag name: data-science
tags question: http://stackoverflow.com/q/51579073
tags question: http://stackoverflow.com/q/51614756

http://stackoverflow.com/a/51541469
has comment: http://stackoverflow.com/comment/90051571
has comment: http://stackoverflow.com/comment/98278886
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/90051373
answers question: http://stackoverflow.com/q/51541372
has body: It is possible. You could use selenium with python, which is pretty easy to use, scrapy or pyppeteer (pupeeteer with python). Your question is too broad. Read the documentation of one of those frameworks, and try to code with it.
has comment: http://stackoverflow.com/comment/90051299
score: 3
downvote count: 0

http://stackoverflow.com/q/51619095
accepted answer: http://stackoverflow.com/a/51645267
type: Question
type: AnsweredQuestion
has body: EDITTED See at end of post for edit in response to Employed Russian's comment Disclaimer Before going forward, I know that naming a function error is generally bad practice since it may clash with a similar function in libc, but this is an issue I have with some third-party software on which I have little control. Plus I would really like to understand where this error comes from :-) The issue The problem I have is that the code below, when executed through the Python interpreter instead of calling my local implementation of the error function, is actually calling the libC's error function instead (as shown by GDB's stack trace below). When simply compiling the same code within another C program, I do not have such issues. Does someone knows where that comes from ? Does it have to do with the way Python loads shared libraries ? MCVE #include <stdio.h> #include <Python.h> static PyObject* call_error(PyObject *self, PyObject *args); static PyMethodDef module_methods[] = { {"error", call_error, METH_NOARGS, "call error"}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef module_defs = { PyModuleDef_HEAD_INIT, "Test", "Test", -1, module_methods, NULL, NULL, NULL, NULL}; PyObject* PyInit_Test(void) { PyObject *module = PyModule_Create(&module_defs); return module; } void error(const char* fmt, ...); PyObject* call_error(PyObject *self, PyObject *args) { error("Error!"); Py_RETURN_NONE; } void error(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); } GDB output Here is the output of importing running the above code within GDB using python3 -c "import Test; Test.error()" GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-git Copyright (C) 2018 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configure…
tagged with: http://stackoverflow.com/tag/c
answer count: 1
downvote count: 0
tagged with: segmentation-fault
favorite count: 0
has answer: http://stackoverflow.com/a/51645267
tagged with: python
tagged with: python-c-api
has title: Python C API call to error() binds to libc implementation instead of a local one
score: 2
upvote count: 2
tagged with: libc

http://stackoverflow.com/q/51516709
has title: pandas dataframe giving empty frame when variable is used to filter
has comment: http://stackoverflow.com/comment/90001863
tagged with: pandas
has comment: http://stackoverflow.com/comment/90001860
favorite count: 0
has answer: http://stackoverflow.com/a/51517059
type: Question
has comment: http://stackoverflow.com/comment/90001976
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51516783
score: -2
has answer: http://stackoverflow.com/a/51516967
has comment: http://stackoverflow.com/comment/90002115
downvote count: 3
answer count: 3
has body: I have a dataframe and I need to filter it. And I am using for i in values: df = df[df['name'] == i] print(df) Here I am getting empty dataframe. But if I use df = df[df['name'] == 'manualentryofname'] its ok. But values is a list of names based on which I need to filter the dataframe and do some operations.
tagged with: for-loop
tagged with: dataframe
type: UnansweredQuestion

http://stackoverflow.com/comment/90025991
type: Comment
has text: this is awesome and way better than using `apply(pd.Series)` and `stack` but with this method, how do keep the id number? is there a way to link this number in your new_df? just a curiosity :)
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51528720

http://stackoverflow.com/a/51585727
score: 0
type: Answer
has body: missing = 'drop' will drop rows with missing values, which is why your X and y are different lengths. There are different ways to fill it in, but I like pandas.DataFrame.fillna.
answers question: http://stackoverflow.com/q/51585599

http://stackoverflow.com/comment/90194014
type: QuestionComment
comment on: http://stackoverflow.com/q/51614349
score: 1
has text: What does it mean for a record to be "duplicated"? Same file name?
type: Comment

http://stackoverflow.com/q/51580751
tagged with: python
has answer: http://stackoverflow.com/a/51633894
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/51633894
has body: Given the logits (output from the RNN/Lstm/Gru in time major format i.e. (maxTime, batchSize, numberofClasses)), how does ctc greedy decoder performs decoding to generate output sequence. I found this "Performs greedy decoding on the logits given in input (best path)" on its webpage https://www.tensorflow.org/api_docs/python/tf/nn/ctc_greedy_decoder. One possibility is to select output class with maximum value at each time step, collapse repetitions and generate corresponding output sequence. Is it, ctc greedy decoder doing here or something else? Explanation using an example will be very useful.
tagged with: tensorflow
type: Question
downvote count: 0
answer count: 1
has title: How does tf.nn.ctc_greedy_decoder generates output sequences in tensorflow?
favorite count: 0

http://stackoverflow.com/comment/90214507
type: AnswerComment
has text: Yes, you can have two (or more) anaconda environments with different python versions, and/or the same python version, and different packages installed. Yes, on mac OS, you can have anaconda alongside other python distributions; for windows, IDK, but I don't see why you could not.
type: Comment
comment on: http://stackoverflow.com/a/51624703
score: 0

http://stackoverflow.com/q/51544847
has body: I will try to write as many details as I can. I'm the author of a tool called Virtual Forms. It is an ActiveX server control. For now, I have only used it from VBA, VB.NET &amp; C# Now I want to use it from Python on windows. It works, but, I got stuck on one line of code. Here is the code: import win32com.client as win32 vf1 = win32.gencache.EnsureDispatch('VirtualForm2.VirtualForm') vf1.VFFile = r"C:\Users\WinPIS\Desktop\VFPython\VFFilePython.vf" vf1.DatabaseType = 2 vf1.ConnectionString = r"DRIVER={MySQL ODBC 5.3 Unicode Driver};" \ "Port=3306;" \ "SERVER=myserver;" \ "DATABASE=mydatabase;" \ "USER=imtheuser;" \ "PASSWORD=hereismypass;" \ "OPTION=3;" #vf1.OpenVirtualFormDesigner() vf1.ShowVirtualForm("VF2") vf1.TextBox("VF2", "[customerid]").Text = "888" So I can call methods and pass some parameters to this control. The control accepts the VFFile, DatabaseType and the ConnectionString parameter, because it opens the Virtual Form, connect to the MySQL database and displays the data. Here is the screenshot: . Then, in VBA I use this line of code to change the text that is in a textbox: vf1.TextBox("VF2", "[customerid]").Text = "888" And here is the screenshot that it works in VBA: . But when I try it from Python I got this error: C:\Users\WinPIS\venv\VFPython\Scripts\python.exe C:/Users/WinPIS/PycharmProjects/VFPython/VFPythonFile.py Traceback (most recent call last): File "C:/Users/WinPIS/PycharmProjects/VFPython/VFPythonFile.py", line 20, in &lt;module&gt; vf1.TextBox("VF2", "[customerid]").Text = "888" AttributeError: 'tuple' object has no attribute 'Text' Process finished with exit code 1 This only works in windows. If you want to try it out you will need to install the setup for this Virtual Forms control that is in this download: https://www.virtual-forms.com/sharing/Virtual%20Forms%20Framework2.0.0.31.zip And here is the VFFile: https://www.virtual-forms.com/sharing/VFFilePython.vf Any suggestion is welcome. Thanks, Davor UPDATE: the print(dir(vf1)) gives t…
has answer: http://stackoverflow.com/a/51692488
has comment: http://stackoverflow.com/comment/90057820
type: Question
has comment: http://stackoverflow.com/comment/90057598
tagged with: win32com
score: 0
has comment: http://stackoverflow.com/comment/90058411
has comment: http://stackoverflow.com/comment/90058040
answer count: 1
has comment: http://stackoverflow.com/comment/90058059
has title: Getting Python error: AttributeError: 'tuple' object has no attribute 'Text'
has comment: http://stackoverflow.com/comment/90057975
accepted answer: http://stackoverflow.com/a/51692488
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90058055

http://stackoverflow.com/q/51625207
has answer: http://stackoverflow.com/a/51625507
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51625320
type: Question
has comment: http://stackoverflow.com/comment/90215428
tagged with: pointers
has answer: http://stackoverflow.com/a/51625320
has title: c = a + b; How can I make c always reflect any changes made to a or b?
score: 0
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/90215460
has answer: http://stackoverflow.com/a/51625257
downvote count: 1
has body: I am not sure the proper way to phrase this question. I would like to assign/bind some arithmetic (with references/pointers to other "subVariables") to a variable and have the value of the variable update if any of the contributing "subVariables" are updated. &gt;&gt;&gt; a = 1 &gt;&gt;&gt; b = 2 &gt;&gt;&gt; c = a + b &gt;&gt;&gt; c 3 &gt;&gt;&gt; a = 2 &gt;&gt;&gt; c 3 In the ideal situation c would have a value of 4 at the end of this code sample. -- Additional information: I am generating the arithmetic randomly and would like to be able to nest these variables (ex: d = a + c would be the same as d = a + (a + b) where d would reflect any changes that happen to a or b)
has comment: http://stackoverflow.com/comment/90215291
favorite count: 0
possible better answer: http://stackoverflow.com/a/51625257
tagged with: python

http://stackoverflow.com/a/51620486
type: AcceptedAnswer
has body: This has nothing really to do with SVR or BagginRegressor as an algorithm, but simply the parameter grid you use. There is no need for such a small step size for epsilon and gamma. &gt;&gt;&gt; len(np.arange(0.1, 1.0, 0.01)) 90 So you span a grid of 90*90*11=89100. So even if you classifier/regressor takes only a second to train, you have to wait for over 24 hours! Just take smaller steps (e.g. 0.1) as results aren't that sensitive. If there is a region (e.g. smaller epsilon), you may consider some sort of geometric series instead of linear increasing values).
downvote count: 0
answers question: http://stackoverflow.com/q/51614938
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/51614938
score: 2

http://stackoverflow.com/comment/90232455
score: 0
type: AnswerComment
has text: Neither do I, but it was the only example I could think of :D ...Okay, my bad, I did None as none. Okay! Getting there, but now the text isn't showing in the gui at all, it's still showing in the console, presumably because I have said print ('Chatbot:', result), I'd need it to show similar to User: Hey Chatbot: Hi User: Whats up All in the GUI. Tried something like this but not working: `botResponse = tk.Label(window,'User:', result) `
comment on: http://stackoverflow.com/a/51632203
type: Comment

http://stackoverflow.com/a/51572366
score: 0
has comment: http://stackoverflow.com/comment/90110995
has comment: http://stackoverflow.com/comment/90110974
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51572338
has body: Most likely you are simply using a different interpreter from your command line than from your PyCharm project. This will happen, for example, if you have set up your PyCharm project using a fresh conda environment. To see which one you are using on the command-line, simply run where python. Then compare this with what you found in PyCharm.
answers question: http://stackoverflow.com/q/51572338
type: Answer

http://stackoverflow.com/q/51609471
has answer: http://stackoverflow.com/a/51609669
tagged with: attributeerror
tagged with: super
downvote count: 3
type: Question
answer count: 2
upvote count: 0
favorite count: 0
tagged with: attributes
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51609589
score: -3
has body: I'm new to this and I'm getting an error that I was hoping someone could help me with and explain my error. Error: line 178, in applyThrust shipPos = self.Fighter.getPos(self.origin) AttributeError: 'Fighter' object has no attribute 'Fighter' class Fighter(SphereCollideObj, object): fighterCount = 0 def __init__(self, modelPath, parentNode, nodeName, posVec, traverser, scaleVec = 1.0): super(Fighter, self).__init__(modelPath, parentNode, nodeName, 0, 0, 0, 3.0) self.modelNode.setScale(scaleVec) self.modelNode.setPos(posVec) self.trav = traverser self.origin = render.attachNewNode("origin") self.origin.setPos(0, 0, 0) self.origin.hide() self.setKeyBindings() self.hud = Hud("./Tools/Hud.x", self.modelNode, "Hud", (0, 10, 0)) def setKeyBindings(self): self.accept("space", self.thrust, [1]) self.accept("space-up", self.thrust, [0]) def thrust(self,keyDown): if keyDown: taskMgr.add(self.applyThrust, "thrust") else: taskMgr.remove("thrust") self.acceptOnce("space", self.thrust,[1]) self.acceptOnce("space-up", self.thrust,[0]) def applyThrust(self, task): shipPos = self.Fighter.getPos(self.origin) hudPos = self.hud.modelNode.getPos(self.origin) trajectory = hudPos - shipPos rate = 5 trajectory.normalize() self.Fighter.setFluidPos(shipPos + trajectory * rate)
has title: AttributeError: 'Fighter' object has no attribute 'Fighter'
tagged with: python

http://stackoverflow.com/q/51521453
has answer: http://stackoverflow.com/a/51524819
answer count: 1
has comment: http://stackoverflow.com/comment/90012304
tagged with: http://stackoverflow.com/tag/svg
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90011946
tagged with: http://stackoverflow.com/tag/xml
type: Question
has comment: http://stackoverflow.com/comment/90014388
has body: I have two SVGs that where the same but I changed some values inside, for instance: SVG1 &lt;desc id="desc20622"&gt;[Visualization] name=H131B1; &lt;/desc&gt; and the other is: SVG2 &lt;desc id="desc20622"&gt;[Visualization] name=R131C2; &lt;/desc&gt; Now I have realocated a lot of elements in one SVG and I would like to replicate this changes to the other SVG. How is the simplest way to consume those SVGs, compare the ids, copy the values from SVG2 to SVG1 and save a new SVG file? I'm familiar with a bunch of programming languages but I was taking a look at Python to do this job using minidom or xml.etree.ElementTree. Could some one help me on that? Thanks in advance.
has comment: http://stackoverflow.com/comment/90012126
has title: How to copy attributes from a SVG to another?
score: 0

http://stackoverflow.com/q/51515925
has comment: http://stackoverflow.com/comment/90001217
has comment: http://stackoverflow.com/comment/90000591
has title: azure python - create service principal
tagged with: azure
has body: Python script that has to create Azure service principal and get the tenant ID, client ID and secret. Is there any support API that I can bring the required details.
answer count: 0
type: UnansweredQuestion
tagged with: service-principal
tagged with: python
linked to: http://stackoverflow.com/q/47958126
score: 0
type: Question
has comment: http://stackoverflow.com/comment/90000253
tagged with: clientid

http://stackoverflow.com/comment/90095538
type: QuestionComment
comment on: http://stackoverflow.com/q/51564260
has text: Btw, I'm only asking why it's not supported (or is there any reason at all). I dont have a concrete use-case I'm trying to solve - I'm just curious.
score: 0
type: Comment

http://stackoverflow.com/comment/90101770
score: 0
type: QuestionComment
has text: Another answer that is worth looking at is [this](https://stackoverflow.com/a/20857415/6649050)
type: Comment
comment on: http://stackoverflow.com/q/51562015

http://stackoverflow.com/comment/90010196
type: Comment
score: 0
has text: I am afraid it is that straightforward. It says that the variables are not defined.
type: QuestionComment
comment on: http://stackoverflow.com/q/51520482

http://stackoverflow.com/comment/91749379
has text: Possible duplicate of [Regularly spaced orthogonal grid Delaunay triangulation (Computing the paraboloid coeficients)](https://stackoverflow.com/questions/21888546/regularly-spaced-orthogonal-grid-delaunay-triangulation-computing-the-paraboloi)
comment on: http://stackoverflow.com/q/51591212
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90021738
comment on: http://stackoverflow.com/q/51526392
type: QuestionComment
type: Comment
score: 1
has text: I don't understand.

http://stackoverflow.com/a/51607734
score: 0
answers question: http://stackoverflow.com/q/51605520
has comment: http://stackoverflow.com/comment/90213472
has body: You need to look into python namespaces and scope But here is how i like to think of it to avoid going crazy(everything in python is an object). In simple terms python those .py files are modules, when python is running those modules are converted into objects, so you have a urls object, a views object ,etc. so any variable you define on module level turns into an attribute and any function defined turns into a method. I believe you do something like this on your url.py from simulator import views or from simulator.views import update which basically means get the views object which represent the views.py file. From the views object you are able to access your methods like update. Your update method is able to access the f because here's an excerpt from python namespaces and scope the global scope of a function defined in a module is that module’s namespace, no matter from where or by what alias the function is called. Basically your f is an attribute of the views object meaning any methods within views object can access it. Reason why it works when on urls.py its because methods can access the attributes of objects the are defined in, so since update method is define inside views its able to access views attributes. Please read more on python namespaces and scope this a very simplified explanation.
type: Answer

http://stackoverflow.com/q/51556631
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/90079907
has title: should we always replace for loops with list comprehension
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90080120
has body: my question is just as the title. Should we always try to replace a for loop with list/dict comprehension when we can since the latter performs faster? I am writing this project which requires iterating through some massive lists of tuples several times and it's taking forever. So I am struggling to optimize my codes now. The main reason I need to iterate through a list of tuples is, assume I have a value, I'd like to know if it is in the list and what is the other value in the same tuple. is turning these lists into an array or dictionary would help? Any input will be much appreciated. Thanks in advance.
has comment: http://stackoverflow.com/comment/90079919
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90080155
tagged with: python
tagged with: generator
score: 2
has answer: http://stackoverflow.com/a/51556750
upvote count: 3
has comment: http://stackoverflow.com/comment/90079926
downvote count: 1
has comment: http://stackoverflow.com/comment/90081410
type: Question
tagged with: for-loop

http://stackoverflow.com/comment/89934177
type: Comment
type: QuestionComment
score: 0
has text: Dumping code in stack overflow isn't a good way to ask questions
comment on: http://stackoverflow.com/q/51482640

http://stackoverflow.com/q/51606377
favorite count: 0
has comment: http://stackoverflow.com/comment/90179900
type: UnansweredQuestion
tagged with: python
downvote count: 1
score: 3
has title: Single API for various Databases in Python
type: Question
upvote count: 4
tagged with: api
tagged with: perl
tagged with: database
has answer: http://stackoverflow.com/a/51607452
has body: I hold good experience in working with Perl DBI module.The DBI module acts as single API for multiple databases like Oracle, Postgres, etc. I have recently started working on Python and I noticed that there are separate API for each databases in Python. Following are my questions: 1. Isn't there single DB API in Python? 2. If not, isn't this a disadvantage in Python?
answer count: 1

http://stackoverflow.com/comment/90150132
has text: @madjaoue can you provide some explanatory links? i'm not sure i'm following you.
comment on: http://stackoverflow.com/q/51592247
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89979388
type: Comment
type: QuestionComment
has text: For example "123 ABC".
comment on: http://stackoverflow.com/q/51505166
score: 0

http://stackoverflow.com/a/51530336
has comment: http://stackoverflow.com/comment/90028797
score: 1
has body: youre looking for pd.dropna(axis=0,thresh=3) if you set thresh = to the number of columns you have itll only drop rows with everything nan. docs edit: i misread how=all, students comment is probably a better anwser
has comment: http://stackoverflow.com/comment/90028933
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90047157
upvote count: 1
answers question: http://stackoverflow.com/q/51530311

http://stackoverflow.com/comment/90123330
score: 0
comment on: http://stackoverflow.com/q/51578993
type: Comment
type: QuestionComment
has text: @mahir I just did two for loop as mentioned above. However, I do not know how to move on from there.

http://stackoverflow.com/a/51492029
has comment: http://stackoverflow.com/comment/89953045
answers question: http://stackoverflow.com/q/51491578
has comment: http://stackoverflow.com/comment/89953176
score: 0
has body: Drako already mentioned, that this is not free coding service. Show some effort yourself and tell us, what you already tried and how it didn't work. also provide output to help us analyze the problem. I'll help anyway; also welcome to StackOverflow. What you are looking for is a "power set". An exhaustive set M of sets s, where each s is a subset of M and there is in fact no subset of M which is not already contained in a s. As sets are unordered by definition, you don't have to care about duplicates because of different ordering. Looking at this question There is a nice answer to get the power set of a given set. Assuming your input list/set/iterable is i, you can use the following code to get the power set list. from itertools import chain, combinations def get_power_set(i): i.sort() # Sorted input --&gt; sorted output ps_iterable = chain.from_iterable(combinations(i, r) for r in range(len(i)+1)) return list(ps_iterable) def get_highest_sum(input_list): maximum = 0 for s in input_list: sum_of_set = sum(s) if sum_of_set &gt; maximum: maximum = sum_of_set return maximum i = [1,2,3] # Assign your input list here power_set = get_power_set(i) highest_sum = get_highest_sum(power_set) print(power_set) # &gt;&gt;&gt; [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] print("Highest sum is {}".format(highest_sum)) # &gt;&gt;&gt; 6
type: Answer
has comment: http://stackoverflow.com/comment/89952771
has comment: http://stackoverflow.com/comment/89952660

http://stackoverflow.com/comment/89956373
has text: @JoontaeKim: Accept the answer if it helped you (green tick on the left).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51493212
type: Comment

http://stackoverflow.com/q/51638053
downvote count: 0
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/90240759
has answer: http://stackoverflow.com/a/51638276
accepted answer: http://stackoverflow.com/a/51638276
tagged with: python
has title: Using custom tensorflow ops in keras
upvote count: 3
tagged with: tensorflow
has body: I am having a script in tensorflow which contains the custom tensorflow ops. I want to port the code to keras and I am not sure how to call the custom ops within keras code. I want to use tensorflow within keras, so the tutorial I found so far is describing the opposite to what I want: https://blog.keras.io/keras-as-a-simplified-interface-to-tensorflow-tutorial.html. I also read about Lambda layers that can wrap arbitrary custom function, yet I did not see an example for tf.ops. If you could provide code snippet with a simplest example how to do that I would be very grateful. For example assuming the tf.ops as: outC = my_custom_op(inA, inB) ---EDIT: Similar problem has been described in here - essentially calling this custom op in keras, however I cannot grasp the solution how to apply it on another example that I want, for instance this one. This custom tf op is first compiled (for gpu) and then so far used within tensorflow as here, see @ line 40. It is clear for me how to use a custom (lambda) function wrapped in Lambda layer, what I would like to understand is how to use the compiled custom ops, if I use keras.
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90240871
type: Question
linked to: http://stackoverflow.com/q/45067108
has comment: http://stackoverflow.com/comment/90250826
linked to: http://stackoverflow.com/q/51523305
answer count: 1

http://stackoverflow.com/comment/90126471
type: Comment
has text: `pip install --upgrade pip` will upgrade pip
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51580577

http://stackoverflow.com/comment/90131585
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51583119
has text: `putZero` is an `int`, you can't subscript an `int`, e.g. `1[0]` is an error - what are you trying to accomplish - did you simply mean `IndexOfZero = putZero`?

http://stackoverflow.com/comment/120987161
comment on: http://stackoverflow.com/a/63834834
score: 6
type: Comment
type: AnswerComment
has text: Since someone just asked me, here is the code of the example adapted for the `ProcessPoolExecutor` https://gist.github.com/ltalirz/9220946c5c9fd920a1a2d81ce7375c47

http://stackoverflow.com/comment/90095887
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51550341
has text: -group 1 - row 1 = 98 because of no other point of reference so it uses itself --- -group 1 - row 2 = 98 because it does not consider itself now that it has at least some historical reference, so it compares to the data in row 1

http://stackoverflow.com/q/51624320
favorite count: 0
possible better answer: http://stackoverflow.com/a/51624336
answer count: 3
has answer: http://stackoverflow.com/a/51624375
tagged with: python
has title: Create a new Dataframe based on conditions from another Dataframe for loop
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51624336
score: 1
accepted answer: http://stackoverflow.com/a/51624337
tagged with: dataframe
type: Question
tagged with: for-loop
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51624337
has body: Working with 2017 NFL Quarterback Data, looking to put the top 10 qbs each week in a dataframe (along with the rest of the data). qb = {'week': [1, 1, 1, 2, 2, 2], 'qb': ['Rodgers', 'Brady', 'Wilson', 'Rodgers', 'Brady', 'Wilson'], 'pts': [30, 24, 20, 31, 20, 26]} qb_df = pd.DataFrame(data=qb) week qb pts 1 Rodgers 30 1 Brady 24 1 Wilson 20 2 Rodgers 31 2 Brady 20 3 Wilson 26 For this sake looking to return the top 2 from each week into a new dataframe. week qb pts 1 Rodgers 30 1 Brady 24 2 Rodgers 31 2 Wilson 26 I tried a for loop that works as far as getting the data, but can't figure out to put it in a dataframe top10_17 = pd.DataFrame() for i in range(1, 18): i_17 = qb_2017.loc[qb_2017['Week'] == i].sort_values('FantasyPoints', ascending=False)[:10] top10_17 = pd.concat(i_17) Used range(1,18) for the 17 weeks in an NFL season
downvote count: 0

http://stackoverflow.com/comment/90073941
comment on: http://stackoverflow.com/q/51541433
score: 1
has text: @jpp, thank you very much for the support, I tried to make it clear as possible :)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90133116
score: 0
type: AnswerComment
type: Comment
has text: You have to think a little in your logic. The argument *book_type.0* is not the *pk* of `Book`, but the *type*. You use this to get a **list** of books with that type, not a single book, so don't use get_object_or_404. So something like this: `Book.objects.filter(book_type=book_types_id)`.
comment on: http://stackoverflow.com/a/51583403

http://stackoverflow.com/comment/90272457
comment on: http://stackoverflow.com/q/51620925
type: Comment
type: QuestionComment
score: 0
has text: Scroll down to the bottom. There should be a button that says 'Post your answer' and a big text box above it.

http://stackoverflow.com/q/51580689
score: -4
has comment: http://stackoverflow.com/comment/90128665
has title: Python program to convert words to numbers in a text file containing English words also
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/17140886
tagged with: words
tagged with: python
has answer: http://stackoverflow.com/a/51581270
tagged with: numbers
answer count: 1
has comment: http://stackoverflow.com/comment/90130075
type: UnansweredQuestion
downvote count: 4
upvote count: 0
has body: I would like to use word2number from https://pypi.org/project/word2number/ to convert words to numbers in a text file to another file as output. A similar program is available to convert numbers to words. So how do I workaround this program to suit my case. import re import num2words with open('input.txt') as f_input: text = f_input.read() text = re.sub(r"(\d+)", lambda x: num2words.num2words(int(x.group(0))), text) with open('output.txt', 'w') as f_output: f_output.write(text)

http://stackoverflow.com/q/51578959
score: 0
has body: I repeat here a simplified version of a question for which I received no reply: I installed wiringpi on my RaspberryPi 3 Python 3.4. I can run the wiring commands (like i2cdetect) under the raspberrypi command line, but I can not make it work in the Python shell. I have tried various installations and imports, but it does not appear to become a recognized module by the Python shell. Can anyone help?
downvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90199664
has answer: http://stackoverflow.com/a/51625395
has comment: http://stackoverflow.com/comment/90175818
has comment: http://stackoverflow.com/comment/90131179
tagged with: wiringpi
has comment: http://stackoverflow.com/comment/90130989
has title: Wiringpi under Python shell
type: Question
upvote count: 1
answer count: 1
tagged with: raspberry-pi3
favorite count: 0

http://stackoverflow.com/comment/89973466
score: 1
comment on: http://stackoverflow.com/q/51502479
type: Comment
type: QuestionComment
has text: What you *really* should do, however, is pass in `y` as an argument to `func()`. Why do you think you need a global in the first place?

http://stackoverflow.com/comment/90053866
score: 0
comment on: http://stackoverflow.com/q/51542243
type: Comment
type: QuestionComment
has text: you can use django-forms-builder. I think it would do the task for you. You can check it out here - https://github.com/stephenmcd/django-forms-builder

http://stackoverflow.com/comment/90031319
type: AnswerComment
has text: Hi @kitetan612, Did you try to modify the code and test again?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51518391

http://stackoverflow.com/a/51562882
accepted answer of: http://stackoverflow.com/q/51562320
answers question: http://stackoverflow.com/q/51562320
type: Answer
upvote count: 2
has body: To uninstall a package just use pip uninstall BlueJeansMeetingsRestApi if there is some configuration issue with IPYTHON you can encounter such errors. But if you are running short for time, i would suggest got with direct python shell command shell by using,i think this should work when you try import it into a file. python &lt;filename&gt;.py please check and let me know.
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89978015
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51504133
has text: Please add more information and code. What have you tried so far? SO users aren't clairvoyants.

http://stackoverflow.com/a/51520122
accepted answer of: http://stackoverflow.com/q/51486454
score: 49
answers question: http://stackoverflow.com/q/51486454
has comment: http://stackoverflow.com/comment/110591530
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/138941165
upvote count: 51
has comment: http://stackoverflow.com/comment/138335485
has body: If you don't want to create this dict manually, you can also rely on geopandas creating it: In [1]: import shapely.geometry In [2]: import geopandas In [3]: shapely_polygon = shapely.geometry.Polygon([(0, 0), (0, 1), (1, 0)]) In [4]: geopandas.GeoSeries([shapely_polygon]).__geo_interface__ Out[4]: {'bbox': (0.0, 0.0, 1.0, 1.0), 'features': [{'bbox': (0.0, 0.0, 1.0, 1.0), 'geometry': {'coordinates': (((0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (0.0, 0.0)),), 'type': 'Polygon'}, 'id': '0', 'properties': {}, 'type': 'Feature'}], 'type': 'FeatureCollection'} (Note that this gives a FeatureCollection and not a single feature.) Or to a string (or file): In [4]: geopandas.GeoSeries([shapely_polygon]).to_json() Out[4]: '{"features": [{"bbox": [0.0, 0.0, 1.0, 1.0], "geometry": {"coordinates": [[[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]], "type": "Polygon"}, "properties": {}, "id": "0", "type": "Feature"}], "bbox": [0.0, 0.0, 1.0, 1.0], "type": "FeatureCollection"}'
downvote count: 2
type: Answer

http://stackoverflow.com/q/51548884
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90065591
has body: try: folderSizeInMB= int(subprocess.check_output('du -csh --block-size=1M', shell=True).decode().split()[0]) print('\t\tTotal download progress (MB):\t' + str(folderSizeInMB), end = '\r') except Exception as e: print('\t\tDownloading' + '.'*(loopCount - gv.parallelDownloads + 3), end = '\r') I have this code in my script because for some reason my unix decided to not find 'du' command. It throws an error /bin/sh: du: command not found. My hope with this code was that even though my program runs into this error, it will just display the message in the except block and move-along. However, it prints the error before displaying the message in the except block. Why is it doing so? Is there a way for me to suppress the error message displayed by the try block? Thanks. EDIT: I rewrote the code after receiving the answer like shown below and it works. I had to rewrite only one line: folderSizeInMB= int(subprocess.check_output('du -csh --block-size=1M', shell=True, stederr=subprocess.DEVNULL).decode().split()[0])
possible better answer: http://stackoverflow.com/a/51548988
type: Question
has answer: http://stackoverflow.com/a/51548988
has title: try/except showing error but I don't want it to
accepted answer: http://stackoverflow.com/a/51549033
has comment: http://stackoverflow.com/comment/90066224
score: 0
answer count: 2
tagged with: exception
tagged with: python
tagged with: unix
has answer: http://stackoverflow.com/a/51549033

http://stackoverflow.com/q/51587098
has body: I am trying to create a program than can detect faces and predict its gender on the live stream. but I get this error message when running the program Traceback (most recent call last): File "text.py", line 54, in &lt;module&gt; cus_ana.prediction() File "text.py", line 31, in prediction gender = gender_classifier() TypeError: __call__() missing 1 required positional argument: 'inputs' This is the code so far class CusAnalytics(): def __init__(self, cascade, gender): self.cascade = cascade self.gender = gender def gender_classifier(self): classifier = self.gender gender = classifier.predict(np.expand_dims(cv2.resize(cropped, (198, 198)), axis=0)) gender = np.where(gender.flatten() &lt; 0.5, "Female", "Male") def prediction(self): cam = cv2.VideoCapture(0) while True: ret, frame = cam.read() frame = cv2.flip(frame, 1) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = self.cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5, minSize=(150, 150)) for (x, y, w, h) in faces: cropped = cv2.resize(frame[y:y+h, x:x+w], (198,198)) gender = gender_classifier() if gender[0] == 'Male': cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2) cv2.rectangle(frame, (x-1, y+h), (x+w+1, y+h+50), (255, 0, 0), -1) cv2.rectangle(frame, (x-1, y), (x+w+1, y-50), (255, 0, 0), -1) else: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2) cv2.rectangle(frame, (x-1, y+h), (x+w+1, y+h+50), (0, 0, 255), -1) cv2.rectangle(frame, (x-1, y), (x+w+1, y-50), (0, 0, 255), -1) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cv2.imshow('Stream', frame) cascadePath = "../../../MODEL/TRAINED MODELS/FACE_DETECTION/haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascadePath) gender_classifier_path = '../../../MODEL/TRAINED MODELS/GENDER_CLASSIFICATION/best_gender_classifier.h5' gender_classifier = load_model(gender_classifier_path) cus_ana = CusAnalytics(faceCascade, gender_classifier) cus_ana.prediction() The code works fine without the implementation of OOPS. …
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90139498
tagged with: python
has comment: http://stackoverflow.com/comment/90139600
tagged with: oop
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90139650
has comment: http://stackoverflow.com/comment/90139537
has title: type error when running program
score: 0
has comment: http://stackoverflow.com/comment/90139682

http://stackoverflow.com/comment/89994490
type: QuestionComment
comment on: http://stackoverflow.com/q/51497681
score: 1
has text: How many columns do you have in `text.csv`? If more than one column, then you cannot use TfidfVectorizer on it.
type: Comment

http://stackoverflow.com/comment/90066851
has text: okay thanks guys i got this now its working using bas64 as input!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51549361

http://stackoverflow.com/comment/90120692
score: 0
type: QuestionComment
has text: Possible duplicate of [Keras custom loss function: Accessing current input pattern](https://stackoverflow.com/questions/46464549/keras-custom-loss-function-accessing-current-input-pattern)
type: Comment
comment on: http://stackoverflow.com/q/51576796

http://stackoverflow.com/comment/90030945
has text: @Theroarx see my answer, It's probably because you're using python 2.7.
comment on: http://stackoverflow.com/q/51531565
score: 0
type: QuestionComment
type: Comment

stacked-bar-chart
tag name: stacked-bar-chart
tags question: http://stackoverflow.com/q/51495982
type: Tag

http://stackoverflow.com/q/51604912
downvote count: 0
answer count: 0
has title: Multi-task learning: keep same batch size or same epochs?
tagged with: machine-learning
has body: I am building a multi-task model with two tasks. However, the data size for them are different: let's say task 1 has 100k training data while task 2 only has 10k. In this case, should I keep the same batch size and train task 1 10 times then task 2 once; or keep the same epoch and reduce the batch size of task 2 to 1/10 of that of task 1?
type: Question
score: 4
tagged with: deep-learning
tagged with: multitasking
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 4

http://stackoverflow.com/comment/90175222
has text: @NickSweet wired behavior ...ummm
comment on: http://stackoverflow.com/a/51604717
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90194592
score: 0
type: Comment
type: QuestionComment
has text: since I don't have your data, there's nothing more I can do to help. 'left' should fix it if the data is actually clean
comment on: http://stackoverflow.com/q/51614014

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/51585295
tags question: http://stackoverflow.com/q/51590263
tags question: http://stackoverflow.com/q/51552422
tags question: http://stackoverflow.com/q/51582204
tags question: http://stackoverflow.com/q/51632019
tags question: http://stackoverflow.com/q/51600390
tag name: r
tags question: http://stackoverflow.com/q/51601022
tags question: http://stackoverflow.com/q/51496713
tags question: http://stackoverflow.com/q/51486081
tags question: http://stackoverflow.com/q/51611815
tags question: http://stackoverflow.com/q/51614419
tags question: http://stackoverflow.com/q/51541031
tags question: http://stackoverflow.com/q/51600829
type: Tag
tags question: http://stackoverflow.com/q/51634251
tags question: http://stackoverflow.com/q/51534069
tags question: http://stackoverflow.com/q/51628161
tags question: http://stackoverflow.com/q/51561213
tags question: http://stackoverflow.com/q/51580727
tags question: http://stackoverflow.com/q/51569247

http://stackoverflow.com/q/51564226
score: 0
answer count: 1
tagged with: arrays
has body: I am processing columns in a loop 'US-Eco.Metric8_MomChg'.'US-Eco.Metric9_MomChg','US-Eco.Metric10_MomChg' I need to extract the integer from the strings and save it in a array. I am using following code, but getting an error. Please help me. for col in self.columns[]: country, market = col.split('-') num = [] num.append([int (s) for market in str.split() if market.isdigit ()]) Error message: TypeError: descriptor 'split' of 'str' object needs an argument Expected output: [8,9,10]
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90095367
type: Question
has answer: http://stackoverflow.com/a/51564275
has title: Error while extracting number from a string in python
accepted answer: http://stackoverflow.com/a/51564275

http://stackoverflow.com/q/51605561
has comment: http://stackoverflow.com/comment/90176490
has comment: http://stackoverflow.com/comment/90176520
has body: I have a table of 2 columns. First is order_id, Second is item_name. I want the top 10 choice of combination of Items based on order_id Data looks like order_id Item_Name 1 A 1 B 1 C 1 D 2 A 2 B 2 D 2 E 2 B 2 C 3 D 3 E 3 F 3 G 3 A 3 B 4 F 4 D 4 A 4 B 4 C I want the top combinations ranked and separated by pipes like A|B|D B|D|E The combinations can be for any number of Item_Name Numbers
score: 0
has answer: http://stackoverflow.com/a/51605642
has comment: http://stackoverflow.com/comment/90177068
tagged with: pandas
has comment: http://stackoverflow.com/comment/90176535
has title: Pandas: Find top 10 combination of records in one column, based on another column
answer count: 1
type: UnansweredQuestion
tagged with: python
type: Question

http://stackoverflow.com/a/51629471
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/90226352
upvote count: 2
answers question: http://stackoverflow.com/q/51627218
type: Answer
has body: GaussianProcessClassifier() has the following parameter as stated in the docs: copy_X_train : bool, optional (default: True) if you set it to false it will save you a lot of memory. However, GaussianProcessClassifier consumes a lot of memory even for fairly small datasets. I would recommend you to use a different classifier where you can apply some dimensionality reduction techniques.

http://stackoverflow.com/q/51589673
answer count: 1
downvote count: 0
tagged with: packaging
favorite count: 0
linked to: http://stackoverflow.com/q/34514703
has title: pip install producing "Could not find a version that satisfies the requirement"
score: 5
tagged with: pip
tagged with: python
tagged with: requirements.txt
duplicate of: http://stackoverflow.com/q/34514703
has answer: http://stackoverflow.com/a/51589725
type: AnsweredQuestion
has body: I have a package that i have uploaded to test.pypi. I can install this package in a virtual environment on my machine without any issues using pip install --index-url https://test.pypi.org/simple/ package_name_here There is a list of requirements for the package in a 'requirements.txt' file, which are also included in 'install_requires' in the config dict fed to setup in setup.py. This works fine on my machine. When I try the same process within a clean virtual environment on one of my groups local servers i get the following error: Could not find a version that satisfies the requirement widgetsnbextension&gt;=3.2.1 (from package_name_here) (from versions: ) No matching distribution found for widgetsnbextension&gt;=3.2.1 (from package_name_here) for many of the requirements in the requirements.txt file. However when the install bails, if i do: pip install widgetsnbextension pip finds and installs widgetsnbextension-3.2.1 without any problem. The requirements.txt file was made by using pip freeze, so I am confused as to why it will work without the version number, but not with it. Can anyone explain what I am doing wrong please?
has comment: http://stackoverflow.com/comment/90144707
type: Question
has comment: http://stackoverflow.com/comment/90144959
upvote count: 5
accepted answer: http://stackoverflow.com/a/51589725

http://stackoverflow.com/q/51498869
has answer: http://stackoverflow.com/a/51498979
score: 0
answer count: 2
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/77826408
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89965779
type: Question
has body: I conducted an annotation process with 5 people, where they each analyzed 100 Tweets and classified each Tweet as being either positive (1) or negative (0). Which measure of inter-rater agreement is appropriate in this case? I know Cohen's Kappa only handles two raters, and I can't seem to find another appropriate measure.
has title: inter-rater agreement with more than 2 raters

http://stackoverflow.com/q/51516589
has answer: http://stackoverflow.com/a/51517469
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/90001691
downvote count: 3
has comment: http://stackoverflow.com/comment/90002236
type: Question
tagged with: function
score: -2
answer count: 1
accepted answer: http://stackoverflow.com/a/51517469
favorite count: 0
has body: I am trying to verify the values entered by the user, The values that are entered by the user are being stored in one method and its values verification is done in the other method. But the problem I am facing is how to use variable values from one method to another. How can we do this in python?.I am getting error-"userDetailsValidation is not defined" Here is my code: from userAccountDatabase import * def userInputs(): userDetails=[] firstName=str(input("Enter First Name").upper()) while True: if(userDetailsValidation(firstName, "FirstName", accountDetails))==True: userDetails.append(firstName) break else: print('Enter valid First Name') firstName=str(input("Enter First Name").upper()) LastName=str(input("Enter Last Name").upper()) while True: if(userDetailsValidation(LastName, "LastName", accountDetails))==True: userDetails.append(LastName) break else: print('Enter valid last Name') firstName=str(input("Enter Last Name").upper()) dateOfBirth=str(input("Enter date of birth")) while True: if(userDetailsValidation(dateOfBirth, "LastName", accountDetails))==True: userDetails.append(dateOfBirth) break else: print('Enter valid dateOfBirth ') firstName=str(input("Enter dateOfBirth").upper()) # return firstName,LastName,dateOfBirth userInputs() def userDetailsValidation(value, fieldName, database): print("The account does not exist with the given details,Enter valid First name") for entry in database: if fieldName in entry and entry[fieldName] == value: print("correct value") return True else: return False def printRequiredUserInfo(FirstName,fieldname,AccountNumber,Accountbalance,Database): for entry in Database: if fieldname in entry and entry[fieldname] == FirstName: print(entry) printRequiredUserInfo(firstName,"FirstName","Account Number","Account Balance",accountDetails)
has title: Pass variable values from one method to another in python
has comment: http://stackoverflow.com/comment/90001936
has comment: http://stackoverflow.com/comment/90001883
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/90249823
comment on: http://stackoverflow.com/q/51626747
has text: yes let me post that right now.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51540399
type: AnsweredQuestion
score: 3
tagged with: list
has comment: http://stackoverflow.com/comment/90048534
has answer: http://stackoverflow.com/a/51540963
accepted answer: http://stackoverflow.com/a/51540963
linked to: http://stackoverflow.com/q/1714027
has comment: http://stackoverflow.com/comment/90048722
answer count: 2
possible better answer: http://stackoverflow.com/a/51540808
favorite count: 0
tagged with: tuples
upvote count: 3
has comment: http://stackoverflow.com/comment/90048463
has answer: http://stackoverflow.com/a/51540808
tagged with: python
has body: I extract specific names from text using regex etc. The result is a list of tuples containing titles and names. The tuples might be of a different length. lst below shows a list of possible scenarios. I need to remove duplicate names from the result. For example, ('Lord', 'Justice') == ('Lord', 'Justice', 'Smith'), and ('Lady', 'Smiles') == ('Lady', 'Justice', 'Smiles'), but ('Lord', 'Justice', 'Smith') and ('Lady', 'Justice', 'Smiles') are different names. The desired output for each element in lst should be [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles')]. lst = [[('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles')], [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Justice')], [('Lord', 'Justice', 'Smith'), ('Lady', 'Smiles'), ('Lady', 'Justice', 'Smiles')], [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice'), ('Lady', 'Justice', 'Smiles')], [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lady', 'Smiles')]] This is what I have right now but it doesn't yield the desired output. Will really appreciate your help and suggestions. for l in lst: print(l) # remove duplicates based on the last index in tuples lst_1 = list(dict((v[-1],v) for v in sorted(l, key=lambda l: lst[0])).values()) print(lst_1) # remove duplicates based on the second index [1] in tuples lst_2 = list(dict((v[1],v) for v in sorted(lst_1, key=lambda lst_1: lst_1[0])).values()) print(lst_2) print("\n") UPDATE: I was probably too specific in my examples. I had to include other names so the solution should work when there are other names present: lst = [ [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')], [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Justice'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')], [('Lord', 'Justice', 'Smith'), ('Lady', 'Smiles'), ('Lady…
downvote count: 0
has title: Remove duplicates from a list of tuples of different length with python
has comment: http://stackoverflow.com/comment/90048554
type: Question

http://stackoverflow.com/comment/90009099
has text: Is there a way to incorporate that type of output into my dataframe?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51503199
score: 0

http://stackoverflow.com/comment/90173316
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51603659
has text: `Happy Coding.`

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/51519615
tags question: http://stackoverflow.com/q/51562279
tags question: http://stackoverflow.com/q/51491019
tags question: http://stackoverflow.com/q/51572024
tags question: http://stackoverflow.com/q/51593898
tags question: http://stackoverflow.com/q/51566987
tags question: http://stackoverflow.com/q/51544077
tags question: http://stackoverflow.com/q/51490285
tags question: http://stackoverflow.com/q/51556188
tags question: http://stackoverflow.com/q/51609426
tags question: http://stackoverflow.com/q/51520526
tags question: http://stackoverflow.com/q/51616996
tags question: http://stackoverflow.com/q/51563673
tags question: http://stackoverflow.com/q/51536421
tags question: http://stackoverflow.com/q/51485490
tags question: http://stackoverflow.com/q/51577527
tags question: http://stackoverflow.com/q/51613315
tags question: http://stackoverflow.com/q/51563985
tags question: http://stackoverflow.com/q/51563867
tags question: http://stackoverflow.com/q/51587602
tags question: http://stackoverflow.com/q/51504086
tags question: http://stackoverflow.com/q/51627041
tags question: http://stackoverflow.com/q/51623878
tags question: http://stackoverflow.com/q/51491119
tags question: http://stackoverflow.com/q/51487643
tags question: http://stackoverflow.com/q/51510378
tags question: http://stackoverflow.com/q/51635184
tags question: http://stackoverflow.com/q/51489464
tags question: http://stackoverflow.com/q/51590965
tags question: http://stackoverflow.com/q/51536179
tags question: http://stackoverflow.com/q/51610959
tags question: http://stackoverflow.com/q/51594977
tags question: http://stackoverflow.com/q/51543386
tags question: http://stackoverflow.com/q/51506378
type: Tag
tags question: http://stackoverflow.com/q/51616686
tags question: http://stackoverflow.com/q/51624207
tags question: http://stackoverflow.com/q/51526057
tags question: http://stackoverflow.com/q/51564344
tags question: http://stackoverflow.com/q/51575139
tags question: http://stackoverflow.com/q/51544414
tags question: http://stackoverflow.com/q/51567877
tags question: http://stackoverflow.com/q/51491246
tags question: http://stackoverflow.com/q/51539344
tags question: http://stackoverflow.com/q/51635365
tags question: http://stackoverflow.com/q/51546276
tags question: http://stackoverflow.com/q/51607819
tags question: http://stackoverflow.com/q/51489500
tags question: http://stackoverflow.com/q/51634824
tags question: http://stackoverflow.com/q/51541359
tags question: http://stackoverflow.com/q/51509894
tags question: http://stackoverflow.com/q/51587175
tags question: http://stackoverflow.com/q/51569716
tags question: http://stackoverflow.com/q/51632003
tags question: http://stackoverflow.com/q/51526076
tags question: http://stackoverflow.com/q/51550982
tag name: json
tags question: http://stackoverflow.com/q/51519311
tags question: http://stackoverflow.com/q/51583779
tags question: http://stackoverflow.com/q/51634981
tags question: http://stackoverflow.com/q/51631810
tags question: http://stackoverflow.com/q/51526605
tags question: http://stackoverflow.com/q/51599052
tags question: http://stackoverflow.com/q/51626124
tags question: http://stackoverflow.com/q/51513711
tags question: http://stackoverflow.com/q/51600544
tags question: http://stackoverflow.com/q/51604282
tags question: http://stackoverflow.com/q/51539056
tags question: http://stackoverflow.com/q/51614511
tags question: http://stackoverflow.com/q/51552765
tags question: http://stackoverflow.com/q/51579543
tags question: http://stackoverflow.com/q/51584490
tags question: http://stackoverflow.com/q/51599532
tags question: http://stackoverflow.com/q/51534769
tags question: http://stackoverflow.com/q/51565364
tags question: http://stackoverflow.com/q/51578636
tags question: http://stackoverflow.com/q/51501231
tags question: http://stackoverflow.com/q/51566336
tags question: http://stackoverflow.com/q/51611500
tags question: http://stackoverflow.com/q/51628968

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/51497938
tag name: countvectorizer

http://stackoverflow.com/comment/90204136
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51619252
has text: Your code doesn't even determine where the different parts of the name *are*.
type: Comment

http://stackoverflow.com/q/51504540
tagged with: pandas
has answer: http://stackoverflow.com/a/51504617
answer count: 1
tagged with: python
score: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/89977948
type: UnansweredQuestion
has body: What I wish to do is create groups based on the last column (key) such that in the first group I get for example the row 1. For the second group I get rows 1 and 2. And in the 3rd group I get the last two rows. I tried to do it with pandas groupby method, grouped = df1.groupby('Key') but as expected it returns only 2 groups. df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3','A4'], ...: 'B': ['B0', 'B1', 'B2', 'B3', 'B4'], ...: 'C': ['C0', 'C1', 'C2', 'C3', 'C4'], ...: 'D': ['D0', 'D1', 'D2', 'D3', 'D4'], 'Key': ['K0', 'K1', 'K1', 'K0', 'K0']}, ...: index=[0, 1, 2, 3, 4]) df1 Out[89]: A B C D Key 0 A0 B0 C0 D0 K0 1 A1 B1 C1 D1 K1 2 A2 B2 C2 D2 K1 3 A3 B3 C3 D3 K0 4 A4 B4 C4 D4 K0
has title: how to create groups with duplicate keys in pandas groupby?
upvote count: 7
type: Question
has comment: http://stackoverflow.com/comment/89978692
linked to: http://stackoverflow.com/q/40802800
downvote count: 0
duplicate of: http://stackoverflow.com/q/40802800

http://stackoverflow.com/comment/90239123
type: Comment
has text: You are trying to multiply a dataframe to a series. What is expected multiplication operation?
comment on: http://stackoverflow.com/q/51637301
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90050077
has text: This line apparently looks ok, from the syntax point of view. Maybe the syntax error is somewhere else.
type: AnswerComment
comment on: http://stackoverflow.com/a/51540818
score: 0
type: Comment

http://stackoverflow.com/q/51552554
has body: s_headers=[] headers=['DRIVER’S NAME', 'LICENSE', 'PH NUMBER', 'DOB', 'HIRE DAY'] for head in headers: if isinstance(head, float): s_headers.append(str(int(head))) else: s_headers.append(head) print(s_headers) output:- ['DRIVER’S NAME', 'LICENSE', 'PH NUMBER', 'DOB', 'HIRE DAY'] when i am trying to reduce this code using this, s_headers.append(str(int(head) if (isinstance(head, float)) else head) for head in headers) print(s_headers) output:- [ at 0x7f2aeec50780>]
type: Question
tagged with: if-statement
possible better answer: http://stackoverflow.com/a/51552635
score: 0
answer count: 2
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51552720
has title: Not working if/else in one line Python
tagged with: python
has answer: http://stackoverflow.com/a/51552635
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51552720

http://stackoverflow.com/comment/89941626
comment on: http://stackoverflow.com/q/51486233
has text: `concurrent.futures` also includes a `ProcessPoolExecutor` which will execute *tasks* in other processes.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51530358
has title: Read a subset of files in a directory
has comment: http://stackoverflow.com/comment/90028857
possible better answer: http://stackoverflow.com/a/51530630
has comment: http://stackoverflow.com/comment/90028791
has comment: http://stackoverflow.com/comment/90028847
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90028832
accepted answer: http://stackoverflow.com/a/51530916
has comment: http://stackoverflow.com/comment/90028953
has comment: http://stackoverflow.com/comment/90028922
type: Question
has body: I have a directory of files in a directory, named like: tx01.data tx02.data tx03.data When I call this module from the command line, I want to pass in an argument to read only a subsetted range of these files, e.g. tx01.data and tx02.data (it will always be a consecutive range, not a random selection of files). I'm currently using glob to read in all of the files in the directory. From what I've found, glob doesn't really play well with subsetting. The closest I found was this answer. Is there a better way to read a subsetted range, that can be passed in from the command line?
has comment: http://stackoverflow.com/comment/90028978
has answer: http://stackoverflow.com/a/51530916
has comment: http://stackoverflow.com/comment/90028815
has comment: http://stackoverflow.com/comment/90029030
linked to: http://stackoverflow.com/q/23735529
has comment: http://stackoverflow.com/comment/90028911
has answer: http://stackoverflow.com/a/51530630
has comment: http://stackoverflow.com/comment/90028872
has comment: http://stackoverflow.com/comment/90028817
score: 0
has comment: http://stackoverflow.com/comment/90028819
answer count: 2

http://stackoverflow.com/comment/89974279
type: Comment
comment on: http://stackoverflow.com/a/51502777
has text: Yes this is what I need, now I guess I can just add a counter and sum it all to get the total?
score: 0
type: AnswerComment

http://stackoverflow.com/a/51587782
answers question: http://stackoverflow.com/q/51587710
has comment: http://stackoverflow.com/comment/90140814
has comment: http://stackoverflow.com/comment/90140781
has comment: http://stackoverflow.com/comment/90141296
has comment: http://stackoverflow.com/comment/90141339
has body: There's nothing at all wrong with your code. Or the mail servers. The email has &gt;&gt;&gt;&gt;&gt;&gt;&gt; in it, just as you intended. However, many mail programs and webmail systems translate &gt; at the start of a line into an indent marker when formatting mail for viewing. Traditionally, &gt; at the start of a line is how you mark that you're quoting someone inline. So, to make email threads earlier to read, mail clients turn those quotes into something that looks more like quotes. For example, this is a traditional plain-text email: John shouted: &gt; My father said: &gt;&gt; No! You will BE KILL BY DEMONS &gt; No! I must kill the demons The radio said: &gt; No, John, You are the demons. And then John was a zombie. An email client might render it like this: John shouted: My father said: No! You will BE KILL BY DEMONS No! I must kill the demons The radio said: No, John, You are the demons. And then John was a zombie. There's no universal workaround that will work for every client, because every client has its own heuristic code that messes things up. But there a few things that often work. First, if you send both HTML and plain-text versions of your mail, most of the fancy clients that would have treated &gt; as formatting will display the HTML instead, which you can format however you want, while clients that refuse to display HTML will probably also not try to do anything with the &gt;. Another option is to put the diff you're trying to include as an attachment, instead of the body. You can try to mark it as an inline attachment, in hopes that some clients will show it without making the user click on the attachment and open it, but I don't think too many clients like inline plain-text attachments. Prefixing the line with a space often works, like this: &lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD TBD1 ======= TRP1 &gt;&gt;&gt;&gt;&gt;&gt;&gt; b9bde66 But of course the person reading the mail will have to know about the extra space—and if they're copying and pasting, t…
type: Answer
has comment: http://stackoverflow.com/comment/90141633
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90140968
upvote count: 2
has comment: http://stackoverflow.com/comment/90141690

http://stackoverflow.com/q/51484937
has comment: http://stackoverflow.com/comment/89940755
has comment: http://stackoverflow.com/comment/89939924
has body: I would like to define a class so that its instances can be casted to both tuple and dict. An example: class Point3: ... p = Point(12, 34, 56) tuple(p) # gives (12, 34, 56) dict(p) # gives { 'x': 12, 'y': 34, 'z': 56 } I have found that if I define __iter__ as an iterator that yields single values then the instance can be casted to tuple and if it instead yields double values then it can be casted to dict: class Point3: def __init__(self, x, y, z): self.x = x self.y = y self.z = z # This way makes instance castable to tuple def __iter__(self): yield self.x yield self.y yield self.z # This way makes instance castable to dict def __iter__(self): yield 'x', self.x yield 'y', self.y yield 'z', self.z Is there any way to make instances castable to both tuple and dict in Python 2.7?
has comment: http://stackoverflow.com/comment/89939217
upvote count: 10
has comment: http://stackoverflow.com/comment/89939778
has comment: http://stackoverflow.com/comment/89940290
linked to: http://stackoverflow.com/q/44320382
has comment: http://stackoverflow.com/comment/89939366
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89940583
has comment: http://stackoverflow.com/comment/89939231
has comment: http://stackoverflow.com/comment/89940378
has comment: http://stackoverflow.com/comment/89938965
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/89938931
downvote count: 0
score: 10
has answer: http://stackoverflow.com/a/51486591
linked to: http://stackoverflow.com/q/35282222
type: Question
has title: Make class castable to both tuple and dict
has comment: http://stackoverflow.com/comment/89938802
has comment: http://stackoverflow.com/comment/89938806
has answer: http://stackoverflow.com/a/51485442
answer count: 2
has comment: http://stackoverflow.com/comment/89940691
has comment: http://stackoverflow.com/comment/89939113
has comment: http://stackoverflow.com/comment/89938904
tagged with: iterable
favorite count: 0
tagged with: tuples
has comment: http://stackoverflow.com/comment/89939315
tagged with: python-2.7

http://stackoverflow.com/q/51573068
has answer: http://stackoverflow.com/a/51634781
score: 1
tagged with: tensorflow
type: Question
has body: I am learning tensorflow currently and cannot wrap my head around why tensorflow doesn't do proper prediction on following simple regression problem. X are random numbers from 1000 to 8000 Y is X + 250 So if X is 2000, Y is 2250. This seems like a linear regression problem to me. Yet, when I try making a predictions, it is nowhere near close to what I would expect, X of 1000 is giving me prediction of 1048 instead of 1250. Also loss and average loss are huge: {'average_loss': 10269.81, 'loss': 82158.48, 'global_step': 1000} Here is the complete code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf from sklearn.model_selection import train_test_split x_data = np.random.randint(1000, 8000, 1000000) y_true = x_data + 250 feat_cols = [tf.feature_column.numeric_column('x', shape=[1])] estimator = tf.estimator.LinearRegressor(feature_columns=feat_cols) x_train, x_eval, y_train, y_eval = train_test_split(x_data, y_true, test_size=0.3, random_state=101) input_func = tf.estimator.inputs.numpy_input_fn({'x': x_train}, y_train, batch_size=8, num_epochs=None, shuffle=True) train_input_func = tf.estimator.inputs.numpy_input_fn({'x': x_train}, y_train, batch_size=8, num_epochs=1000, shuffle=False) eval_input_func = tf.estimator.inputs.numpy_input_fn({'x': x_eval}, y_eval, batch_size=8, num_epochs=1000, shuffle=False) estimator.train(input_fn=input_func, steps=1000) train_metrics = estimator.evaluate(input_fn=train_input_func, steps=1000) eval_metrics = estimator.evaluate(input_fn=eval_input_func, steps=1000) print(train_metrics) print(eval_metrics) brand_new_data = np.array([1000, 2000, 7000]) input_fn_predict = tf.estimator.inputs.numpy_input_fn({'x': brand_new_data}, shuffle=False) prediction_result = estimator.predict(input_fn=input_fn_predict) print(list(prediction_result)) Am I doing something wrong or am I misinterpreting what LinearRegression means?
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/62946055
linked to: http://stackoverflow.com/q/38340311
favorite count: 0
has title: Why is TensorFlow estimator not able to make this simple linear regression prediction
accepted answer: http://stackoverflow.com/a/51634781
tagged with: machine-learning
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/62946055
type: AnsweredQuestion

http://stackoverflow.com/q/51636721
possible better answer: http://stackoverflow.com/a/70699202
linked to: http://stackoverflow.com/q/6791911
accepted answer: http://stackoverflow.com/a/51761416
has answer: http://stackoverflow.com/a/70699202
linked to: http://stackoverflow.com/q/29223222
has title: Job is not performed by APScheduler's BackgroundScheduler
type: Question
has comment: http://stackoverflow.com/comment/90238240
has body: I have a Django application that I'm running on Docker. I'm trying to launch an APScheduler scheduler when I run the docker container. I created a scheduler and I simply added it a job that I called test1, and that sends an email to my address. This is the Python script that is launched when I run the container. from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.schedulers.background import BackgroundScheduler #scheduler = BlockingScheduler() scheduler = BackgroundScheduler() def test1(): ... (code to send email) scheduler.add_job(test1, 'interval', seconds = 20) scheduler.start() This is the results I obtained with each of the two kind of schedulers: BlockingScheduler: the scheduler works, I receive an email every 20 seconds. However I can't access the app. I presume this is normal due to the very nature of the BlockingScheduler. screenshot1 screenshot2 BackgroundScheduler: no problem to access the application. However, I receive no email. Since the emails were sent in one of the two cases I guess the problem is neither Django nor Docker related, but purely about APScheduler. I did my research but I couldn't find why the BackgroundScheduler didn't work as in the tutorials I read, the developper set up the scheduler the same way I did. Any help would be much appreciated, thanks! UPDATE 1 I tried the two following things, both made the BackgroundScheduler behave like a BlockingScheduler (which is not what I want) 1) Setting the daemon option to False when initialising the scheduler instance: scheduler = BackgroundScheduler(daemon = False) 2) "Trying to keep the main thread alive", as explained in these: how-do-i-schedule-an-interval-job-with-apscheduler apscheduler-inside-a-class-object I added this right after scheduler.starts(): while True: time.sleep(1) scheduler.shutdown() UPDATE 2 When I try to setup a BackgroundScheduler in a single Python file (outside of any application context), it works very well: from apscheduler.schedulers.back…
has comment: http://stackoverflow.com/comment/90238359
has comment: http://stackoverflow.com/comment/90238403
tagged with: docker
linked to: http://stackoverflow.com/q/42119673
answer count: 2
has comment: http://stackoverflow.com/comment/90238321
downvote count: 0
tagged with: apscheduler
has answer: http://stackoverflow.com/a/51761416
has comment: http://stackoverflow.com/comment/90237817
has comment: http://stackoverflow.com/comment/90237973
favorite count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/90238034
tagged with: django
tagged with: python
score: 8
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90238132

http://stackoverflow.com/comment/90034292
type: Comment
type: QuestionComment
has text: Don't write tests so their order matters. That is very bad practice. Write tests so they are independent.
comment on: http://stackoverflow.com/q/51532115
score: 0

http://stackoverflow.com/a/51502682
has body: Another option is: np.array(intervals)[(sample[:,None] &gt; intervals).sum(axis=1)] #array([30., 18., 18., 15., 30., 10., inf, 18., 25., 21.]) Essentially we build a mask that checks to see if the sample is greater than the interval (assumes it's already sorted as in your example). Then we sum along the first axis, which will add up a 1 for every interval that the value is greater than. The resultant sums are the indices in the intervals array. A non-NumPy solution using a list comprehension (obviously includes the for loop, but should be relatively efficient with the generator): new_sample = [next(i for i in intervals if i&gt;s) for s in sample] #[30, 18, 18, 15, 30, 10, inf, 18, 25, 21]
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51502197
upvote count: 1

http://stackoverflow.com/a/51538914
answers question: http://stackoverflow.com/q/51535473
upvote count: 1
downvote count: 3
has body: First of all python method arguments are by default tuple. Your case, you cannot use arg as a dictionary key which does not exist as a key of the dictionary. so if you want to do so you need to extract each key from the tuple and assign it to your dictionary. This code might help you. d = {1: 1, (1, 2): 3} def accessDict(name, *args): print('Hello', name) #So simple edit is for a in args: d[a] #1, 3 accessDict('foo', 1) accessDict('foo', (1, 2))
type: Answer
score: -2
has comment: http://stackoverflow.com/comment/90045939
has comment: http://stackoverflow.com/comment/90045665
has comment: http://stackoverflow.com/comment/90045898

http://stackoverflow.com/a/51672538
has comment: http://stackoverflow.com/comment/98098435
answers question: http://stackoverflow.com/q/51627603
type: AcceptedAnswer
has body: I want to render the same image and save it, without creating a visible window It is not possible to create an OpenGL Context with an version above 1.0 without any window. See the answer to the question Creating OpenGL context without window. But it is possible to use a completely hidden window for "offscreen" rendering. Sadly it is not possible to create a initially hidden window with Pygame. It is only possible to hide a window after it was created by pygame.display.iconify(). See also Hiding pygame display. But it is possible to create a initially hidden window with the GLFW library by setting the window hint VISIBLE to False. The glfw library can be found at glfw 1.7.0. The code may look like this: import cv2 import numpy as np from OpenGL.GL import * from OpenGL.GLU import * import glfw def main(): DISPLAY_WIDTH = 900 DISPLAY_HEIGHT = 900 # Initialize the library if not glfw.init(): return # Set window hint NOT visible glfw.window_hint(glfw.VISIBLE, False) # Create a windowed mode window and its OpenGL context window = glfw.create_window(DISPLAY_WIDTH, DISPLAY_HEIGHT, "hidden window", None, None) if not window: glfw.terminate() return # Make the window's context current glfw.make_context_current(window) gluPerspective(90, (DISPLAY_WIDTH / DISPLAY_HEIGHT), 0.01, 12) glEnable(GL_TEXTURE_2D) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) glRotatef(-90, 1, 0, 0) # Straight rotation glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glRotatef(285, 0, 0, 1) # Rotate yaw glTranslatef(-5, -3, -2) # Move to position # Draw rectangle glBegin(GL_QUADS) glColor3f(1, 0, 0) glVertex3f(2, 2, 0) glVertex3f(2, 2, 2) glVertex3f(2, 6, 2) glVertex3f(2, 6, 0) glEnd() image_buffer = glReadPixels(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT, OpenGL.GL.GL_RGB, OpenGL.GL.GL_UNSIGNED_BYTE) image = np.frombuffer(image_buffer, dtype=np.uint8).reshape(DISPLAY_WIDTH, DISPLAY_HEIGHT, 3) cv2.imwrite(r"C:\temp\image.png", image) glfw.destroy_window(window) glfw.terminate() if __name__ == "__main__": ma…
downvote count: 0
type: Answer
upvote count: 7
score: 7
accepted answer of: http://stackoverflow.com/q/51627603

http://stackoverflow.com/q/51500947
has title: stdout readlines for windows hangs python 3.4
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89974906
type: Question
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90019125
has comment: http://stackoverflow.com/comment/90019517
has body: i have a problem with the below script which is used to connect to one of our nodes using ssh and perform a command. when i execute the last line of the script the script hangs. could you please advise if there is a solution in order to solve this issue? import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.load_system_host_keys() ssh.connect('IP',port= 22, username='xxx',password='xxx') stdin, stdout, stderr = ssh.exec_command('xxxx') output=stdout.readlines()

http://stackoverflow.com/a/51624124
score: 1
accepted answer of: http://stackoverflow.com/q/51622490
answers question: http://stackoverflow.com/q/51622490
upvote count: 1
type: AcceptedAnswer
has body: The term 'outlier' does not directly mean 'invalid data point'. Instead, it means the datapoint is simply showing a value relatively distant from a bulk distribution. Also, what you call 'outliers' is often subjective and problem specific, thus there is no absolute criterion for 'outliers' (i.e. 1.5*IQR is just for box plot visualization purpose). If I oversimplify the reality, there are roughly 3 cases. The outlier is obviously well within the theoretical/practical limit of that instance's nature (e.g. Body temperature of 38.0C where others are in 35.8-36.5C range) and it can be a strong clue for something different is going on (therefore useful for modeling/prediction). The outlier is obviously well outside of the theoretical/practical limit (e.g. Human age of 500) and it should be considered as 'null' value Whether the outlier is inside/outside of the theoretical/practical limit is unknown, so the knowledge of domain experts is necessary (In this case we discuss with technical experts of specific area such as Physicist for Physics problems) Therefore, there is no universal way to handle 'outliers' based on the definition of box plots, but rather you should learn about the nature of the dataset and decide how to handle it properly.
type: Answer
downvote count: 0

http://stackoverflow.com/q/51566257
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/51747613
tagged with: word2vec
tagged with: python
tagged with: gensim
has answer: http://stackoverflow.com/a/63676650
score: 1
has answer: http://stackoverflow.com/a/51583744
upvote count: 1
has body: I am now working on a project using Gensim.word2vec, and I am a total freshman for this field. Actually I already got a model. Are there any way that I can get the similarity rank of a word for another word. For example, the top 2 most similar words for the word 'girl' is 'lady' and then 'woman'. Are there any functions I can use if i enter 'lady' is can return 1, if i enter 'woman' it can return 2? Thanks!
type: Question
answer count: 2
has title: Return the rank of word in Gensim Word2vec
downvote count: 0

http://stackoverflow.com/comment/90154383
type: Comment
comment on: http://stackoverflow.com/a/51594176
score: 1
type: AnswerComment
has text: My solution was so similiar to yours I wont even post it ;)

http://stackoverflow.com/q/51553467
has title: How do I scrape IP addresses through the use of BeautifulSoup and output to CSV?
score: -1
tagged with: export-to-csv
upvote count: 0
answer count: 1
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51553778
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51553778
tagged with: web-scraping
downvote count: 1
type: Question
has body: import requests from bs4 import BeautifulSoup url ='https://myip.ms/browse/blacklist/Blacklist_IP_Blacklist_IP_Addresses_Live_Database_Real-time' response = requests.get(url) data = response.text soup = BeautifulSoup(data, 'html.parser') ipList = soup.find("td",{"class": "row_name"}) rows = ipList.findAll('td') for tr in rows: cols = td.findAll('td') if len(cols) &gt; 0: print (ip.cols.text.strip()) I am doing web scraping using BeautifulSoup and I have encountered some problems. May I know why am I unable to scrape IP addresses from the database table. How do I output the results to a CSV file?

http://stackoverflow.com/comment/90167899
type: Comment
has text: @sacul, thanks. i was not aware of this. Edited the answer.
comment on: http://stackoverflow.com/a/51600488
score: 0
type: AnswerComment

http://stackoverflow.com/a/51617228
has comment: http://stackoverflow.com/comment/90221324
type: Answer
accepted answer of: http://stackoverflow.com/q/51617098
has body: If what you want is the reciprocal of the Server_count column multipled by 100: result["Ratio"] = (1 / result["Server_count"]) * 100
has comment: http://stackoverflow.com/comment/90206488
answers question: http://stackoverflow.com/q/51617098
has comment: http://stackoverflow.com/comment/90208081
has comment: http://stackoverflow.com/comment/90206387
score: 0
has comment: http://stackoverflow.com/comment/90205966
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90206059
has comment: http://stackoverflow.com/comment/90206337

http://stackoverflow.com/a/51557945
downvote count: 0
answers question: http://stackoverflow.com/q/51557819
score: 1
has body: This will find 4 items containers = soup.find_all("a", {"class": "ProductList-item-link"}) print(len(containers)) for a in containers: item_name = a["href"] get_price(website + item_name)
upvote count: 1
type: Answer

http://stackoverflow.com/q/51578845
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/51578887
accepted answer: http://stackoverflow.com/a/51578887
has body: I have a dataframe as the following: A B C D E g1 1 -10 20 text1 g2 0 0 0 text2 g3 0 1 0 text3 g4 0 0 0 text4 I want to filter out g2 &amp; g4 where all of 'B', 'C', 'D' values are 0 I tried df = df[df'B','C','D'==0] returns output same as input, df = df[df'B','C','D'.all(axis=1)==0] also returns output same as input, df = df.loc[df'B','C','D'.isin(['0'])] returns 'Cannot index with multi-dimensional key. The expected output is, A B C D E g1 1 -10 20 text1 g3 0 1 0 text3 What is the error here? Thanks in Advance.
upvote count: 2
tagged with: pandas
has title: indexing with multidimensional key pandas error
answer count: 1
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/51540068
score: 1
has title: Keras: Transfer Learning - Image scaling worsens performance of the model significantly
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51540354
has body: I am working on an image classification problem with keras and tensorflow. I am using the VGG16 model with Imagenet weights and I am importing my data using the ImageDataGenerator from Keras. Now I've been reading that one should always rescale the images using 1./255 for an efficient tranining. However, once I implement the scaling my model performs significantly worse than before. Changing the learning rate and batch size didn't help either. Now I am questioning whether this is possible or if my model has some error. I am using standard .jpg image files. from keras.preprocessing.image import ImageDataGenerator IMAGE_SIZE = 224 BATCH_SIZE = 32 num_classes = 27 main_path = "C:/Users/abc/data" final_path = os.path.join(main_path, "ML_DATA") labels = listdir(gesamt_path) data_generator = ImageDataGenerator(rescale=1./255, ### rescaling done here validation_split=0.20) train_generator = data_generator.flow_from_directory(final_path, target_size=(IMAGE_SIZE, IMAGE_SIZE), shuffle=True, seed=13, class_mode='categorical', batch_size=BATCH_SIZE, subset="training") validation_generator = data_generator.flow_from_directory(final_path, target_size=(IMAGE_SIZE, IMAGE_SIZE), shuffle=False, seed=13, class_mode='categorical', batch_size=BATCH_SIZE, subset="validation") Model definition and training vgg16_model = keras.applications.vgg16.VGG16(weights='imagenet', include_top=True) model = Sequential() for layer in vgg16_model.layers[:-1]: model.add(layer) for layer in model.layers: layer.trainable = False model.add(Dense(num_classes, activation='softmax')) model.compile(Adam(lr=.001), loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit_generator(train_generator, validation_data=validation_generator, epochs=85, verbose=1,callbacks=[tbCallBack,earlystopCallback])
has answer: http://stackoverflow.com/a/75934135
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/56367320
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: conv-neural-network
downvote count: 0

http://stackoverflow.com/comment/90105909
type: AnswerComment
has text: Thankyou @Hiranya, That seems to have got rid of that error but now I am seeing another one.(See edit)
type: Comment
comment on: http://stackoverflow.com/a/51543997
score: 0

http://stackoverflow.com/comment/90129919
type: Comment
comment on: http://stackoverflow.com/a/51582135
has text: I am using 3.6.4 only difference with our code is you are storing your data in a variable and I use MongoDB. and when I try to query my DB it gives that error. it gives the error when I execute Navigation.objects().first() to get the 1st item in my Navigation document
score: 0
type: AnswerComment

http://stackoverflow.com/q/51510617
has body: Actual Return { "store_product_mapping":{ "master_product":{ "name": "abc", "description": "xyz" } } "selling_price": 445 } Serializers looks like: class GrandParentSerializer(serializers.ModelSerializer): class Meta: model = Z fields = ('name', 'description') class ParnetSerializer(serializers.ModelSerializer): master_product = GrandParentSerializer(many=False, read_only=False) class Meta: model = Y fields = ('master_product',) class ChildSerializer(serializers.ModelSerializer): store_product_mapping = ParnetSerializer(many=False, read_only=False) class Meta: model = X fields = ('store_product_mapping', 'selling_price') Am using nested rest_framework.serializer.ModelSerializer to serialize the data from multiple levels but in response i need it to be like. Do I need to make a new dictionary and in a loop update the dictionary? Or is there a shortcut to do same? { "name": xyz "description": abcd "price": 10 }
tagged with: django-rest-framework
favorite count: 0
has title: Get nested serialized data as one
has answer: http://stackoverflow.com/a/51510659
tagged with: django
tagged with: python
type: AnsweredQuestion
downvote count: 0
type: Question
score: 3
tagged with: django-models
upvote count: 3
accepted answer: http://stackoverflow.com/a/51510659
answer count: 1

http://stackoverflow.com/a/51527917
has comment: http://stackoverflow.com/comment/90025789
answers question: http://stackoverflow.com/q/51526464
type: Answer
has comment: http://stackoverflow.com/comment/90026184
has body: For your question, this office article Office automation when multiple versions of Office are installed will be helpful. Multiple version of "Canoe" can be installed on one PC at the same time Each version of "Canoe" has an identifiable PROGID If the above two conditions are satisfied, you can switch the target by specifying PROGID of the desired version number.
has comment: http://stackoverflow.com/comment/90025927
score: 0
has comment: http://stackoverflow.com/comment/90025569

http://stackoverflow.com/a/51604370
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51604310
has body: You can use the following list comprehension to parse all numbers in the file, and then calculate the average based on the new list. lnumbers = [float(number) for line in ufile for number in re.findall('\d+(?:\.\d*)?', line)] print(sum(lnumbers) / len(lnumbers))

http://stackoverflow.com/a/51601630
has comment: http://stackoverflow.com/comment/90170501
has comment: http://stackoverflow.com/comment/90170167
type: Answer
answers question: http://stackoverflow.com/q/51601249
upvote count: 1
score: 1
has body: Since it was my comment which lead to this, I'll add my follow up: enumerate can be thought of as a generator so it will just take a sequence (any sequence or iterator actually) and just "generate" an incrementing index to be yielded with each item from the passed sequence (so it's not making a copy or mutating the list anyway just using an "enumerate object"). In the case of the code in that question, you were never changing the length of the list you were iterating over and once the if statement was run the value of the element did not matter. So the copy wasn't needed, it will be needed when an element is removed as the iterator index is shared with the list and does not account for removed elements. The Python Ninja has a great example of when you should use a copy (or move to list comprehension)
has comment: http://stackoverflow.com/comment/90170538
downvote count: 0

http://stackoverflow.com/comment/90175967
type: QuestionComment
has text: @Onyambu Its working but its not looking at the previous day's 'Final_Order'.
score: 0
comment on: http://stackoverflow.com/q/51604809
type: Comment

http://stackoverflow.com/q/51621168
has comment: http://stackoverflow.com/comment/90208830
favorite count: 0
type: UnansweredQuestion
has title: Pandas -- set row values based on values in another table
has comment: http://stackoverflow.com/comment/90213529
has body: I have two tables in pandas. One is about 10,000+ rows that looks like this: Table 1 col_1 date state ratio [50 more cols] A 10/12 NY .5 A 12/05 MA NaN ......... I have another table that's about 10 rows that looks like this: Table 2 date state ratio 12/05 MA .9 12/03 MA .8 ............ I need to set the ratio in table 1 based on the date and state values from table 2. The ideal solution would be to merge on date and state, but that creates two columns: ratio_x and ratio_y I need a way to set the ratio in table 1 to the corresponding ratio in table 2 where the date and states both match. The ratios in table 1 can be overwritten. If this can be done correctly by merging then that works too. Edit: You can consider table 2 as being meant to map to specific state values (so all the states in table 2 are MA in this example)
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51624658
tagged with: dataframe
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/90207843
has answer: http://stackoverflow.com/a/51624594
tagged with: pandas
tagged with: python

http://stackoverflow.com/a/51564653
type: Answer
has body: get_json was not added to response objects in flask until version 1.0. In previous versions, you need to use get_data: import json json.loads(response.get_data().decode("utf-8")) Having said this, I would caution you against calling route methods directly from other functions (except for testing), or returning response objects from non-route methods. If you are attempting to test this method, you should consider using the test_client: with app.test_client() as client: json.loads(client.get("the/url").get_data().decode("utf-8")) # ...
score: 9
upvote count: 9
answers question: http://stackoverflow.com/q/51563867
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51563867

http://stackoverflow.com/q/51493313
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51493530
tagged with: variables
tagged with: string
favorite count: 0
tagged with: int
tagged with: python
has comment: http://stackoverflow.com/comment/89955288
has comment: http://stackoverflow.com/comment/89955412
has comment: http://stackoverflow.com/comment/89955337
has comment: http://stackoverflow.com/comment/89955585
has comment: http://stackoverflow.com/comment/89955372
type: UnansweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/89955416
has body: I cannot figure out why this won't work, I have gone as far as to apply integer variables, I would prefer to keep it purely to strings. I'm new, what am I doing wrong? x = int(2) y = int(1) while userinput != (1,2): userinput = input("Do you wish to continue, to start from scratch?") if input == 1: print("y") if input == 2: print ("n") else: print("Try y or n, they mean yes or no respectively.")
type: Question
has comment: http://stackoverflow.com/comment/89955441
has title: Python, How do I use a string in a while loop and then an if statement?
has comment: http://stackoverflow.com/comment/89955366
has comment: http://stackoverflow.com/comment/89955350
has comment: http://stackoverflow.com/comment/89955225
score: -3
has comment: http://stackoverflow.com/comment/89955284

http://stackoverflow.com/comment/90169699
type: AnswerComment
comment on: http://stackoverflow.com/a/51600586
type: Comment
has text: @julian I entirely agree with you. But I like to think that people should care about performance and memory when it really matters. My idea of creating a list was to allow op to use a similar logic using other types like `string` for example. I made it general and readable because the question title is general and that could ne benificial for future users.
score: 0

http://stackoverflow.com/q/51518189
score: 0
has answer: http://stackoverflow.com/a/51518414
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51518414
type: Question
has comment: http://stackoverflow.com/comment/90004918
has body: i would like to turn this for loop into list comprehension people_metrics = [] for idx, user_id in tqdm(enumerate(list(interactions_test_indexed_df.index.unique().values))): anime_user_metrics = evaluate_model_for_anime_watcher(model, user_id) anime_user_metrics['_user_id'] = user_id people_metrics.append(anime_user_metrics) print('%d users processed' % idx) enumerate looks like idx user_id 0 20 1 32 ...etc i tried : anime_user_metrics = [evaluate_model_for_anime_watcher(model, user_id) for idx, user_id in tqdm(np.ndenumerate(list(interactions_test_indexed_df.index.unique().values)))] it work. then i tried : anime_user_metrics['_user_id'] = list(zip(*enumerate(interactions_test_indexed_df.index.unique().values)))[::-1] or user_proxy = [b for a, b in np.ndenumerate(list(interactions_test_indexed_df.index.unique().values))] anime_user_metrics['_user_id'] = user_proxy but when i'm tried to do the 2nd line i got an error TypeError: list indices must be integers, not str
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/90005004
tagged with: numpy
has title: for loop to list comprehension
has comment: http://stackoverflow.com/comment/90005079
tagged with: for-loop
answer count: 1

http://stackoverflow.com/q/51496429
favorite count: 0
has title: Group by and apply string in one entry to whole group
tagged with: python
type: AnsweredQuestion
has body: I need to apply a string to group based off the non null value in the group. An example is: ID name surname prsn_id A john smith prsn_01 A john smith NaN A john smith NaN A john smith NaN B mary jane prsn_02 B mary jane NaN B mary jane NaN B mary jane NaN B mary jane NaN B mary jane NaN B mary jane NaN C Barry willis prsn_03 C Barry willis Nan C Barry willis Nan C Barry willis Nan C Barry willis Nan The output should be: ID name surname prsn_id A john smith prsn_01 A john smith prsn_01 A john smith prsn_01 A john smith prsn_01 B mary jane prsn_02 B mary jane prsn_02 B mary jane prsn_02 B mary jane prsn_02 B mary jane prsn_02 B mary jane prsn_02 B mary jane prsn_02 C Barry willis prsn_03 C Barry willis prsn_03 C Barry willis prsn_03 C Barry willis prsn_03 C Barry willis prsn_03 or: ID name surname prsn_id prsn_id_2 A john smith prsn_01 NaN A john smith NaN prsn_01 A john smith NaN prsn_01 A john smith NaN prsn_01 B mary jane prsn_02 NaN B mary jane NaN prsn_02 B mary jane NaN prsn_02 B mary jane NaN prsn_02 B mary jane NaN prsn_02 B mary jane NaN prsn_02 B mary jane NaN prsn_02 C Barry willis prsn_03 NaN C Barry willis Nan prsn_03 C Barry willis Nan prsn_03 C Barry willis Nan prsn_03 C Barry willis Nan prsn_03 I have tried: df['prsn_id_2'] = (df .groupby(['ID', 'name', 'surname'])['prsn_id'] .fillna(method='ffill')) This may work, however it is taking along time so will not be very practical going forward. I need another solution that is vectorised and relatively quick.
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/51496541
type: Question
has answer: http://stackoverflow.com/a/51496541
tagged with: pandas
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/90114282
comment on: http://stackoverflow.com/a/51572201
score: 0
type: Comment
has text: did not work for me, when i use this code i get "None" as result, what i want to get is content of the box, which is the upvoters names
type: AnswerComment

http://stackoverflow.com/comment/90109479
has text: Related: [python - Unpacking, extended unpacking, and nested extended unpacking - Stack Overflow](https://stackoverflow.com/questions/6967632/unpacking-extended-unpacking-and-nested-extended-unpacking)
score: 0
comment on: http://stackoverflow.com/q/51571612
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51540203
type: Question
tagged with: conditional-statements
possible better answer: http://stackoverflow.com/a/51540802
has answer: http://stackoverflow.com/a/51540802
has comment: http://stackoverflow.com/comment/90048075
answer count: 2
has comment: http://stackoverflow.com/comment/90048343
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/51540530
favorite count: 0
has title: How to construct condition in a loop in Python?
has body: I want to construct a condition for my dataframe in a function by iterating through the given dictionary dict. def get_condition(dataframe, dict={'col1':val1, 'col2':val2, 'col3':val3})": condition = ... return condition Expected output condition = (dataframe['col1']==val1) &amp; (dataframe['col2']==val2) &amp; (dataframe['col3']==val3) How to do this?
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/51540530
has comment: http://stackoverflow.com/comment/90048797
has comment: http://stackoverflow.com/comment/90048237

http://stackoverflow.com/comment/90229729
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51632183
type: QuestionComment
has text: @guidot Sorry, that's my fault (I posted a previous version of my code). In my current version (which isn't working), I catch every continuous prime in one go, so instead of catching a maximum of one prime per iteration, it catches between 0-5. So 13, 15, 17, 19 would be caught in one iteration, but in the next one, only 23 would, but then 29 and 31 would be caught. So what would the time complexity of that be?

http://stackoverflow.com/comment/90153111
type: Comment
comment on: http://stackoverflow.com/a/51585911
has text: So everytime I have a new view, I have to make the query and pass it to the view so base.html can use it if it's custom to my Django application?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51491931
has answer: http://stackoverflow.com/a/51492082
downvote count: 0
has answer: http://stackoverflow.com/a/51492296
has comment: http://stackoverflow.com/comment/89954356
favorite count: 0
has comment: http://stackoverflow.com/comment/89953412
has comment: http://stackoverflow.com/comment/89953076
has comment: http://stackoverflow.com/comment/89953865
tagged with: python
has comment: http://stackoverflow.com/comment/89952936
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/89954574
possible better answer: http://stackoverflow.com/a/51492082
linked to: http://stackoverflow.com/q/51485289
upvote count: 1
has comment: http://stackoverflow.com/comment/89954524
type: Question
has comment: http://stackoverflow.com/comment/89954317
has body: I have the following architecture of the text files in the folders and subfolders. I want to read them all and create a df. I am using this code, but it dont work well for me as the text is not what I checked and the files are not equivalent to my counting. l = [pd.read_csv(filename,header=None, encoding='iso-8859-1') for filename in glob.glob("2018_01_01/*.txt")] main_df = pd.concat(l, axis=1) main_df = main_df.T for i in range(2): l = [pd.read_csv(filename, header=None, encoding='iso-8859-1',quoting=csv.QUOTE_NONE) for filename in glob.glob(str(foldernames[i+1])+ '/' + '*.txt')] df = pd.concat(l, axis=1) df = df.T main_df = pd.merge(main_df, df) file
has comment: http://stackoverflow.com/comment/89953106
accepted answer: http://stackoverflow.com/a/51492296
has comment: http://stackoverflow.com/comment/89954747
has comment: http://stackoverflow.com/comment/89953809
has title: Reading text files from subfolders and folders and creating a dataframe in pandas for each file text as one observation
answer count: 2
tagged with: pandas

http://stackoverflow.com/q/51566884
answer count: 0
type: UnansweredQuestion
has title: PyQt5: In a QGraphicsView, rebind ScrollHandDrag to work with middle mouse button, not just left mouse button
favorite count: 0
has body: I'm working on a map editor, where I use a QGraphicsView to display a QGraphicsObject (the map). I have already implemented the image zoom functionality from this post, and I have tried using their implementation of pan, and have found that it works. However, I want to be able to do the pan without toggling, simply by holding down the middle mouse button and dragging from there. I've written this code to switch between the two modes (normal and drag), and then call it on mouse(Press/Release)Events. (in QGraphicsView) def toggleDragMode(self): if self.dragMode() == QGraphicsView.ScrollHandDrag: self.setDragMode(QGraphicsView.NoDrag) self.pointerMode = PointerMode.Normal else: self.setDragMode(QGraphicsView.ScrollHandDrag) self.pointerMode = PointerMode.Drag def mousePressEvent(self, event): if event.buttons() &amp; Qt.MiddleButton: self.toggleDragMode() ... super().mousePressEvent(event) def mouseReleaseEvent(self, event): if self.dragMode() == QGraphicsView.ScrollHandDrag: self.setDragMode(QGraphicsView.NoDrag) self.pointerMode = PointerMode.Normal super().mouseReleaseEvent(event) (Sidenote: With the mouseReleaseEvent, I found that I couldn't use event.buttons() &amp; Qt.MiddleButton to check if the middle button was released, so I always check and release in this case.) However, whenever I try and middle-click and drag, no pan happens. However, I have confirmed this works correctly whenever I use the left mouse button as the binding (i.e. if event.buttons() &amp; Qt.LeftButton: toggleDrag()). There has to be some code in QGraphicsView.mouseMoveEvent() that checks to see if the left button is held AND the cursor is in DragMode. Is there a way to change the keybinding on that deeper level? EDIT: I just found this link and tried it by doing this (in QGraphicsView) def __init__(*args, **kwargs): ... self.STOP_GLOBAL_SCROLLING = 1 But to no avail. Still, it's an interesting lead.
type: Question
tagged with: python
tagged with: qgraphicsview
upvote count: 3
linked to: http://stackoverflow.com/q/35508711
tagged with: pyqt5
downvote count: 1
tagged with: qt
tagged with: qgraphicsitem
score: 2

http://stackoverflow.com/q/51538480
has comment: http://stackoverflow.com/comment/90044537
accepted answer: http://stackoverflow.com/a/51539404
favorite count: 0
score: 0
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/90044907
tagged with: python
possible better answer: http://stackoverflow.com/a/51539451
has answer: http://stackoverflow.com/a/51539451
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51539404
linked to: http://stackoverflow.com/q/49035358
has body: From a 2D dictionary, how to convert it into a dataframe or matrix of presence/absence where the values, in the lists) are the columns and keys are the row names? Accumulating the values in a list, I goal is to organize them in a matrix. I had been trying this but no success: values = set() for genome, info in dict_cluster.items(): for v in info: #t = [genome, ([v for v in info])] t = [genome,v] print pd.DataFrame(t) Input: A ['arylpolyene', 'hserlactone', 'hserlactone', 'nrps', 'siderophore', 't1pks-nrps', 'terpene', 'thiopeptide', 'transatpks-nrps'] B ['hserlactone', 'hserlactone-arylpolyene', 'nrps', 'siderophore', 'thiopeptide'] C ['nrps', 'nrps', 'nrps', 'siderophore', 't1pks-nrps', 't1pks-nrps'] D ['nrps', 'siderophore', 't1pks-nrps'] Output: arylpolyene siderophore hserlactone-arylpolyene transatpks-nrps terpene thiopeptide hserlactone nrps t1pks-nrps A 1 2 0 1 1 1 2 1 1 B 0 1 1 0 0 1 1 1 0 C 0 1 0 0 0 0 0 3 2 D 0 1 0 0 0 0 0 1 1 And my output is this: 0 0 GCF_900068895.1 1 transatpks-nrps 0 0 GCA_002415165.1 1 thiopeptide 0 0 GCA_000367685.2 1 t1pks-nrps 0 0 GCA_002732135.1 1 t1pks-nrps
has title: dictionary to dataframe presence/absence
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51539288
type: Question

http://stackoverflow.com/comment/90094960
score: 0
comment on: http://stackoverflow.com/q/51563893
type: Comment
type: QuestionComment
has text: If this helps, the URL for the search part of the database is: http://irsa.ipac.caltech.edu/applications/wise/#id=Hydra_wise_wise_5&RequestClass=ServerRequest&projectId=wise&shortDesc=Solar%20System%20Object/Orbit&isBookmarkAble=true&isDrillDownRoot=true

http://stackoverflow.com/comment/90186439
type: Comment
comment on: http://stackoverflow.com/a/51608337
score: 0
type: AnswerComment
has text: I updated mongoengine but it couldn't solve the problem, I know insert_many with {} but I need to use it like **insert_many([Human(name='John'), Human(name='Cookie Monster')])** , tried it and didn't work, insert_many should used like your example.So i think i should find different method

http://stackoverflow.com/q/51579951
has title: Python not able to compare the dates in dateframes
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90125121
score: 1
duplicate of: http://stackoverflow.com/q/16852911
type: Question
has body: I have a dataframe df['Latest date'] as below 45 01.12.2015 - 13:35:23 46 01.12.2015 - 13:36:27 ... 4355 09.07.2018 - 07:54:22 4356 09.07.2018 - 07:52:03 4357 24.07.2018 - 16:00:36 4358 09.07.2018 - 07:53:19 4359 09.07.2018 - 11:40:22 4369 23.07.2018 - 09:13:34 4370 16.07.2018 - 13:02:28 4371 23.07.2018 - 09:14:13 4372 23.07.2018 - 09:14:44 4374 23.07.2018 - 09:15:35 4378 23.07.2018 - 09:15:58 4379 23.07.2018 - 09:16:24 4380 23.07.2018 - 09:16:41 4381 23.07.2018 - 09:17:16 4383 23.07.2018 - 09:17:53 4387 23.07.2018 - 09:18:28 4389 23.07.2018 - 09:19:25 4393 23.07.2018 - 09:20:08 4394 25.07.2018 - 14:25:20 4395 18.07.2018 - 10:10:58 4396 18.07.2018 - 10:10:18 4398 18.07.2018 - 10:10:42 4399 16.07.2018 - 11:09:21 4400 16.07.2018 - 11:27:23 4401 23.07.2018 - 09:21:16 4407 18.07.2018 - 10:11:15 4417 24.07.2018 - 11:56:14 4418 25.07.2018 - 11:05:11 I want to filter for the rows with date> 22/07/2018 I tried df=df[(df["Latest date"]&gt;"22/07/2018")] however the new df returns entries not necessarily after 22/07/2018. I wonder if it is not understanding the dates are in "dd/mm/yy" formats.
downvote count: 0
tagged with: pandas
tagged with: datetime
answer count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51579968
upvote count: 1
accepted answer: http://stackoverflow.com/a/51579968
linked to: http://stackoverflow.com/q/16852911

http://stackoverflow.com/comment/89944455
score: 1
type: Comment
has text: The standard `inspect` module has functions to examine the call stack; given the function that called you, you can get the module that contains it; modules have a `__FILE__` attribute...
type: QuestionComment
comment on: http://stackoverflow.com/q/51487645

http://stackoverflow.com/q/51550926
upvote count: 0
has comment: http://stackoverflow.com/comment/90069209
type: Question
tagged with: performance
downvote count: 3
answer count: 1
tagged with: processing-efficiency
accepted answer: http://stackoverflow.com/a/51551491
has title: Which is faster - Conditional String Formatting or Conventional if/else?
favorite count: 0
has body: Method 1 - Conventional if/else: from collections import Counter sentence = Counter(input("What would you like to say? ").lower()) sentence_length = 0 for k, v in sentence.items(): if v &gt; 1: print("There are {} {}'s in this sentence.".format(v, k)) else: print("There is {} {} in this sentence.".format(v, k)) sentence_length += v print("There are {} words, including spaces, in total.".format(sentence_length)) Method 2 - Conditional String Formatting: from collections import Counter sentence = Counter(input("What would you like to say? ").lower()) sentence_length = 0 for k, v in sentence.items(): print("There {} {} {}{} in this sentence.".format(("are" if v &gt; 1 else "is"), v, k, ("'s" if v &gt; 1 else ""))) sentence_length += v print("There are {} words, including spaces, in total.".format(sentence_length)) Both code snippets are used to calculate the number of occurrences of a particular character in a sentence. The difference between the two methods is the part inside of the "for" statement - Conditional String Formatting or Conventional if/else. I am trying to figure which method would be more efficient.
tagged with: string-formatting
score: -3
has answer: http://stackoverflow.com/a/51551491
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51635991
score: 0
tagged with: crc
tagged with: python
has body: I need to know how can we convert a byte array like this one for example input =[0x6E,0x00,0x00,0x0B,0x00,0x00,0x2F,0x4A,0x0,0x00] to an hexadecimal string '\x6E\x00\x00\x0B\x00\x00' because i need to use it to calculate my CRC like that binascii.crc_hqx(b'\x6E\x00\x00\x0B\x00\x00',0) . is their any function that allow me to do that. Thank you
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51952371
tagged with: crc16
answer count: 1
has title: byte array to hexa string for CRC use

google-cloud-functions
tag name: google-cloud-functions
tags question: http://stackoverflow.com/q/51574359
type: Tag

http://stackoverflow.com/comment/90193854
score: 1
comment on: http://stackoverflow.com/q/51613969
type: Comment
type: QuestionComment
has text: You need to install PyQt4, or change the default backend

http://stackoverflow.com/a/51548011
answers question: http://stackoverflow.com/q/51547207
type: Answer
has body: With numpy you can easily do these kinds of matrix operations, e.g for a 3x3 matrix import numpy as np T = np.random.random((3,3,3)) T = T*T - 2*T ... etc.
score: 0

http://stackoverflow.com/comment/90006491
comment on: http://stackoverflow.com/q/51518415
type: Comment
type: QuestionComment
has text: What do you mean? One `print()` is inside try, other one is under except. Doesn't that mean that something should be printed in any case?
score: 0

http://stackoverflow.com/comment/90246176
score: 0
type: Comment
has text: The last line did the trick! Thank you and sorry for a late reply. Dissertation times are hard
comment on: http://stackoverflow.com/a/51516623
type: AnswerComment

http://stackoverflow.com/comment/90006034
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51518617
has text: `None` is considered "falsy". If `doAtest` returns `None`, then the `else` clause will be executed.

http://stackoverflow.com/comment/90194657
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51614308
has text: Both - first I have to open the PDF in the browser, which is besides the terminal, and after that I'll write into the terminal what I want the new name to be.
score: 0

http://stackoverflow.com/q/51604091
type: Question
tagged with: amazon-ec2
tagged with: boto3
has body: I have 4 S3 buckets : SourceBucket\folder1\file1 and DestinationBucket1-folder1, SourceBucket\folder2\file1 and DestinationBucket2-folder2. When I upload the folders, I would like the code to check for folder 'DestinationBucket1-folder1' if it exists and then upload the folder1 and files underneath that folder. I am struggling with S3 KEY. How can I parse S3 KEY and check if the specifice folder exist and then upload the first folder under SourceBucket?
answer count: 1
tagged with: python
has title: Upload file in S3 using boto3 with Dynamic Foldername
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51627690
tagged with: amazon-s3

http://stackoverflow.com/q/51636756
score: 2
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51646301
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has body: I defined a network and each scope contains weights for each process, each process assign its corresponding weights, here is my demo code from multiprocessing import Process import tensorflow as tf def init_network(name): with tf.name_scope(name): x = tf.Variable(int(name)) return x def f(name, sess): print('step into f()') vars = tf.trainable_variables(name) print(sess.run(vars[0])) sess.run(vars[0].assign(int(name)+10)) if __name__ == '__main__': sess = tf.Session() x1 = init_network('1') x2 = init_network('2') sess.run(tf.global_variables_initializer()) p1 = Process(target=f, args=('1', sess)) p2 = Process(target=f, args=('2', sess)) p1.start() p2.start() p1.join() p2.join() print(sess.run([x1, x2])) The demo code get stuck and it seems that sess can't be shared within different processes, how can I update weights in multiprocessing settings?
upvote count: 2
has answer: http://stackoverflow.com/a/51646301
tagged with: tensorflow
has title: Tensorflow, update weights in multiprocessing

http://stackoverflow.com/q/51602661
upvote count: 3
accepted answer: http://stackoverflow.com/a/53605293
type: Question
has title: Python Pivot Table margins=True not summing well
tagged with: pandas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/53605293
favorite count: 0
tagged with: pivot-table
tagged with: python
has body: I have the below code: import pandas as pd df=pd.read_csv("https://www.dropbox.com/s/90y07129zn351z9/test_data.csv?dl=1", encoding="latin-1") pvt_received=df.pivot_table(index=['site'], values = ['received','sent'], aggfunc = { 'received' : 'count' ,'sent': 'count'}, fill_value=0, margins=True) pvt_received['to_send']=pvt_received['received']-pvt_received['sent'] column_order = ['received', 'sent','to_send'] pvt_received_ordered = pvt_received.reindex_axis(column_order, axis=1) pvt_received_ordered.to_csv("test_pivot.csv") table_to_send = pd.read_csv('test_pivot.csv', encoding='latin-1') table_to_send.rename(columns={'site':'Site','received':'Date Received','sent':'Date Sent','to_send':'Date To Send'}, inplace=True) table_to_send.set_index('Site', inplace=True) table_to_send Which generate this table: Date Received Date Sent Date To Send Site 2 32.0 27.0 5.0 3 20.0 17.0 3.0 4 33.0 31.0 2.0 5 40.0 31.0 9.0 All 106.0 106.0 0.0 But this parameter margins=True is not giving correct result of total of each columns. For instance, Date Received should be 125 instead of 106, Date Sent should be 106 (it is correct) and Date To Send should be 19 instead of 0.0 (zero). Question: What am I supposed to change to get correct numbers? Also, there is lack on All that should do a sum of each row. Thanks a lot in advance.
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/51781911
upvote count: 15
downvote count: 0
has comment: http://stackoverflow.com/comment/127656589
answers question: http://stackoverflow.com/q/51525604
has comment: http://stackoverflow.com/comment/119254665
accepted answer of: http://stackoverflow.com/q/51525604
has comment: http://stackoverflow.com/comment/137953916
score: 15
type: AcceptedAnswer
has body: https://www.python.org/dev/peps/pep-0525/#asynchronous-generator-object An asynchronous function you can use instead of range(): async def async_range(count): for i in range(count): yield i await asyncio.sleep(0.0)
type: Answer

http://stackoverflow.com/comment/89991607
type: QuestionComment
has text: @Nanda I have posted an answer!
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51510716

tensorflow
tags question: http://stackoverflow.com/q/51503939
tags question: http://stackoverflow.com/q/51542111
tags question: http://stackoverflow.com/q/51528295
tags question: http://stackoverflow.com/q/51537851
tags question: http://stackoverflow.com/q/51539926
tags question: http://stackoverflow.com/q/51535792
tags question: http://stackoverflow.com/q/51536373
tags question: http://stackoverflow.com/q/51509083
tags question: http://stackoverflow.com/q/51591298
tags question: http://stackoverflow.com/q/51553722
tags question: http://stackoverflow.com/q/51626527
tags question: http://stackoverflow.com/q/51520566
tags question: http://stackoverflow.com/q/51502539
tags question: http://stackoverflow.com/q/51566573
tags question: http://stackoverflow.com/q/51567728
tags question: http://stackoverflow.com/q/51566229
tags question: http://stackoverflow.com/q/51526179
tags question: http://stackoverflow.com/q/51530203
tags question: http://stackoverflow.com/q/51506691
tags question: http://stackoverflow.com/q/51494860
tags question: http://stackoverflow.com/q/51588717
tags question: http://stackoverflow.com/q/51570785
tags question: http://stackoverflow.com/q/51579794
tags question: http://stackoverflow.com/q/51558339
tags question: http://stackoverflow.com/q/51540068
tags question: http://stackoverflow.com/q/51535128
tags question: http://stackoverflow.com/q/51527163
tags question: http://stackoverflow.com/q/51575507
tags question: http://stackoverflow.com/q/51572429
tags question: http://stackoverflow.com/q/51542304
tags question: http://stackoverflow.com/q/51612718
tags question: http://stackoverflow.com/q/51541031
tags question: http://stackoverflow.com/q/51490551
tags question: http://stackoverflow.com/q/51595909
tags question: http://stackoverflow.com/q/51552199
tags question: http://stackoverflow.com/q/51583461
tags question: http://stackoverflow.com/q/51593854
tags question: http://stackoverflow.com/q/51628450
tags question: http://stackoverflow.com/q/51557380
tags question: http://stackoverflow.com/q/51573068
tags question: http://stackoverflow.com/q/51578532
tags question: http://stackoverflow.com/q/51556579
tags question: http://stackoverflow.com/q/51507788
tags question: http://stackoverflow.com/q/51537682
tags question: http://stackoverflow.com/q/51601502
tags question: http://stackoverflow.com/q/51600696
tags question: http://stackoverflow.com/q/51583009
tags question: http://stackoverflow.com/q/51522011
tags question: http://stackoverflow.com/q/51591550
tags question: http://stackoverflow.com/q/51489125
tags question: http://stackoverflow.com/q/51631447
tags question: http://stackoverflow.com/q/51573864
tags question: http://stackoverflow.com/q/51629480
tags question: http://stackoverflow.com/q/51494211
tags question: http://stackoverflow.com/q/51520587
tags question: http://stackoverflow.com/q/51560382
tags question: http://stackoverflow.com/q/51569370
tags question: http://stackoverflow.com/q/51617315
tags question: http://stackoverflow.com/q/51586364
tags question: http://stackoverflow.com/q/51595618
tags question: http://stackoverflow.com/q/51569669
tags question: http://stackoverflow.com/q/51560331
tags question: http://stackoverflow.com/q/51618251
tags question: http://stackoverflow.com/q/51638053
tags question: http://stackoverflow.com/q/51549549
tags question: http://stackoverflow.com/q/51529785
tags question: http://stackoverflow.com/q/51485642
tags question: http://stackoverflow.com/q/51598437
tags question: http://stackoverflow.com/q/51520279
tags question: http://stackoverflow.com/q/51625702
tags question: http://stackoverflow.com/q/51567587
tags question: http://stackoverflow.com/q/51505552
tags question: http://stackoverflow.com/q/51518585
tags question: http://stackoverflow.com/q/51617995
tags question: http://stackoverflow.com/q/51601167
tags question: http://stackoverflow.com/q/51496838
tags question: http://stackoverflow.com/q/51516544
tags question: http://stackoverflow.com/q/51505729
tags question: http://stackoverflow.com/q/51611512
tag name: tensorflow

java
tags question: http://stackoverflow.com/q/51562279
tags question: http://stackoverflow.com/q/51610511
tags question: http://stackoverflow.com/q/51574976
tags question: http://stackoverflow.com/q/51552583
tags question: http://stackoverflow.com/q/51540597
tags question: http://stackoverflow.com/q/51616422
tags question: http://stackoverflow.com/q/51505655
tags question: http://stackoverflow.com/q/51581886
tags question: http://stackoverflow.com/q/51509289
tags question: http://stackoverflow.com/q/51545033
tags question: http://stackoverflow.com/q/51635187
tag name: java
tags question: http://stackoverflow.com/q/51572230
tags question: http://stackoverflow.com/q/51576949
type: Tag
tags question: http://stackoverflow.com/q/51624108

http://stackoverflow.com/comment/90105417
has text: Another question is how can I construct input like this ? Cause when I do np.array([[100,100],[100,100]]), it becomes to array of [2,100,100]
type: AnswerComment
comment on: http://stackoverflow.com/a/51569613
score: 0
type: Comment

http://stackoverflow.com/comment/90207355
type: Comment
score: 0
has text: isn't chaining `list` and `map` redundant in py2?
type: AnswerComment
comment on: http://stackoverflow.com/a/51620546

http://stackoverflow.com/q/51526849
favorite count: 0
tagged with: python-3.x
upvote count: 2
linked to: http://stackoverflow.com/q/50504500
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/51526954
type: AnsweredQuestion
downvote count: 2
type: Question
has title: Python line continuation results in DeprecationWarning
score: 0
has answer: http://stackoverflow.com/a/51526954
answer count: 2
has body: In Python 3.6.5, this works fine: command = "ffmpeg -i {0} -vsync 0 -q:v 2 -vf select=\"eq(pict_type\,PICT_TYPE_I)\" -r 30 {1}/frame%03d.jpg".format(file_path, output_path) That's obviously a long line, so I used a line continuation: command = "ffmpeg -i {0} -vsync 0 -q:v 2 -vf select=\"eq(pict_type\,PICT_TYPE_I)\" -r 30 {1}/frame%03d.jpg"\ .format(file_path, output_path) However, at startup, this generates a DeprecationWarning: DeprecationWarning: invalid escape sequence \, command = "ffmpeg -i {0} -vsync 0 -q:v 2 -vf select=\"eq(pict_type\,PICT_TYPE_I)\" -r 30 {1}/frame%03d.jpg"\ This does not, however: command = "foo {0} bar {1}"\ .format(file_path, output_path) I use line continuations all over the rest of the project; none have resulted in DeprecationWarning. Other questions like this one mention this warning, but none for continuation characters that I can find. What causes this warning, and why does it only appear in this very narrow case? Edit: This has nothing to do with the line continuation. The reason the error presented to me only some of the time has to do with Django's runserver. The first time runserver is run, the error is not reported. But if a change causes a reload, then the error is reported when the reloader runs.
possible better answer: http://stackoverflow.com/a/51527024
has answer: http://stackoverflow.com/a/51527024

http://stackoverflow.com/comment/90236340
type: QuestionComment
comment on: http://stackoverflow.com/q/51605079
has text: Yeah... I have to go through my test files, see if I can find my first try and post that. I obviously did the "trivial" differently.
score: 0
type: Comment

http://stackoverflow.com/comment/90203221
comment on: http://stackoverflow.com/q/51616637
has text: You have shown only the RasPi code so far. However it takes two to communicate. Therefore it is also important to know what the Arduino does. How does the Arduino read what the RasPi sends to it? Is it waiting for a terminator (`\r` or `\n` perhaps) which the RasPi does not send?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51563740
has answer: http://stackoverflow.com/a/51563864
has comment: http://stackoverflow.com/comment/90094599
tagged with: set
type: Question
has title: Categorize numbers of a list into different sets and count the occurences
has answer: http://stackoverflow.com/a/51563886
has body: I have a list of numbers, let's say A = [9,10,16,19]. I have four sets {8, 9, 10}, {11, 12, 13}, {14, 15, 16}, {17, 18, 19, 20}. For each element in list A, categorize the element into the given sets and count the occurences corresponding to each set. Considering the example I gave the output should be [2,0,1,1]. What is the best way to do this??
score: -2
answer count: 2
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/90094704
favorite count: 0
possible better answer: http://stackoverflow.com/a/51563864
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51563886

http://stackoverflow.com/q/51581886
type: Question
tagged with: object
linked to: http://stackoverflow.com/q/95419
has title: Initializing objects in Java without declaring a class or using a class
answer count: 3
score: -5
has comment: http://stackoverflow.com/comment/90129283
has answer: http://stackoverflow.com/a/51581914
has comment: http://stackoverflow.com/comment/90129058
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/51581915
has comment: http://stackoverflow.com/comment/90129031
has answer: http://stackoverflow.com/a/51581915
has body: I have general question regarding objects in Java. I want to initialize an object in Java without declaring a class or using a class. In python for example you can do like this: myObject = {"x":5,"y":10,"z":12,"name":"something"} Now myObject is an object. And I can say myObject.x which will be 5. From what I know I would have to do like this in Java: class object(){ int x; int y; int z; String name; myObject(int x, int y, int z, String name){ this.x = x; this.y = y; this.z = z; this.name = name; } } myObject = new object(10,5,12,"something") I would like to do that, but like in my python example. Hope anyone can help :)
downvote count: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51581914
tagged with: java
upvote count: 1
has answer: http://stackoverflow.com/a/51582062

http://stackoverflow.com/q/51583086
has title: In operator in 2D lists
tagged with: operator-keyword
tagged with: python
answer count: 0
has body: I am having trouble utilizing the in operator with 2D lists. In the following code, I expect 'hi' to be printed but 'bye' is printed. Shouldn't the statement "if '@' in tempGen:" return 'True' and move on, or am I misunderstanding how the in operator functions. MAX_ROW = 5 MAX_COL =5 tempGen = ['@'] * MAX_ROW for row in range(MAX_ROW): tempGen[row] = ['@'] * MAX_COL print(tempGen) if '@' in tempGen: print('hi') else: print('bye') I can't seem to find any answers to this question, but if you know of a thread please link me. Thank you for any help.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90131679
has comment: http://stackoverflow.com/comment/90131767
tagged with: 2d
tagged with: list
has comment: http://stackoverflow.com/comment/90131512
type: Question
score: 0

http://stackoverflow.com/a/51493231
has comment: http://stackoverflow.com/comment/89955262
has comment: http://stackoverflow.com/comment/89955882
has comment: http://stackoverflow.com/comment/89955651
accepted answer of: http://stackoverflow.com/q/51493095
type: Answer
answers question: http://stackoverflow.com/q/51493095
score: 3
has comment: http://stackoverflow.com/comment/89955378
has body: Why not do what Python does? Let's see an example: open("foo", "q") # =&gt; ValueError: invalid mode: 'q' open is in C, but you can see how it looks like for e.g gzip.open: if "t" in mode: if "b" in mode: raise ValueError("Invalid mode: %r" % (mode,)) Don't be scared of making the code a little longer; you can't really avoid it in Python. And also, "Error in Keithley.Autorange(): Input not allowed." doesn't tell the programmer which input is not allowed. In this case, explicit and clear is better than clever and short. I'd do: def auto_range(self, function, source, value): if function not in ["source", "measure"]: raise ValueError("Invalid function: %s" % function) if source not in ["v", "i"]: raise ValueError("Invalid source: %s" % source) if value not in [0, 1]: raise ValueError("Invalid value: %d" % value) # ... Not directly relevant to your questions, but it is best to stick to the language's coding style: in Python, variables are in snake_case (lowercase with underscores).
has comment: http://stackoverflow.com/comment/89955455
has comment: http://stackoverflow.com/comment/91672743
has comment: http://stackoverflow.com/comment/89956460
has comment: http://stackoverflow.com/comment/89955579
downvote count: 0
has comment: http://stackoverflow.com/comment/89955165
upvote count: 3
has comment: http://stackoverflow.com/comment/89955589
has comment: http://stackoverflow.com/comment/89955577
has comment: http://stackoverflow.com/comment/89956410
has comment: http://stackoverflow.com/comment/89955832
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89955205
has comment: http://stackoverflow.com/comment/91673002

http://stackoverflow.com/q/51484727
downvote count: 1
answer count: 1
has body: I have images of vehicles . I need to predict the price of the vehicle based on image extraction. What I have learnt is , I can use CNN to extract the image features but what I am not able to get is, How to predict the prices of vehicles. I know that the I need to train my CNN model before it predicts the price. I don't know how to train the model with images along with prices . In the end what I expect is , I will input an vehicle image and I need to get price of the vehicle. Can any one provide the approach for this ?
favorite count: 0
has comment: http://stackoverflow.com/comment/89938767
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/67088725
tagged with: python
upvote count: 0
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/89938703
type: Question
has comment: http://stackoverflow.com/comment/89941293
score: -1
has title: CNN image extraction to predict a continuous value

http://stackoverflow.com/comment/90023872
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51508937
has text: @Joel so you're saying if there is n recipients, so there is going to be n^2 emails send out altogether? If so, do you know how to fix it?

tkinter
tags question: http://stackoverflow.com/q/51617405
tags question: http://stackoverflow.com/q/51528578
tags question: http://stackoverflow.com/q/51590418
tags question: http://stackoverflow.com/q/51570116
tags question: http://stackoverflow.com/q/51571242
tags question: http://stackoverflow.com/q/51551673
tags question: http://stackoverflow.com/q/51564081
tags question: http://stackoverflow.com/q/51536969
tags question: http://stackoverflow.com/q/51634729
tags question: http://stackoverflow.com/q/51534019
tags question: http://stackoverflow.com/q/51576693
tags question: http://stackoverflow.com/q/51524294
tags question: http://stackoverflow.com/q/51484356
tags question: http://stackoverflow.com/q/51550585
tags question: http://stackoverflow.com/q/51604921
tags question: http://stackoverflow.com/q/51590357
tag name: tkinter
tags question: http://stackoverflow.com/q/51566284
tags question: http://stackoverflow.com/q/51545528
tags question: http://stackoverflow.com/q/51634657
tags question: http://stackoverflow.com/q/51578072
tags question: http://stackoverflow.com/q/51586841
tags question: http://stackoverflow.com/q/51627258
tags question: http://stackoverflow.com/q/51621354
tags question: http://stackoverflow.com/q/51591163
tags question: http://stackoverflow.com/q/51584501
tags question: http://stackoverflow.com/q/51483789
tags question: http://stackoverflow.com/q/51487582
tags question: http://stackoverflow.com/q/51630585
tags question: http://stackoverflow.com/q/51568819
tags question: http://stackoverflow.com/q/51531680
tags question: http://stackoverflow.com/q/51514209
tags question: http://stackoverflow.com/q/51611390
tags question: http://stackoverflow.com/q/51567500
tags question: http://stackoverflow.com/q/51535879
tags question: http://stackoverflow.com/q/51525416
tags question: http://stackoverflow.com/q/51538871
tags question: http://stackoverflow.com/q/51506982
tags question: http://stackoverflow.com/q/51506923
tags question: http://stackoverflow.com/q/51591456
tags question: http://stackoverflow.com/q/51505795
tags question: http://stackoverflow.com/q/51524821
tags question: http://stackoverflow.com/q/51625869
tags question: http://stackoverflow.com/q/51517152
tags question: http://stackoverflow.com/q/51552281
tags question: http://stackoverflow.com/q/51575710
tags question: http://stackoverflow.com/q/51638082
tags question: http://stackoverflow.com/q/51555155
tags question: http://stackoverflow.com/q/51491996
tags question: http://stackoverflow.com/q/51607268
tags question: http://stackoverflow.com/q/51598295
tags question: http://stackoverflow.com/q/51528103
tags question: http://stackoverflow.com/q/51505121
tags question: http://stackoverflow.com/q/51611929
tags question: http://stackoverflow.com/q/51503819
tags question: http://stackoverflow.com/q/51568717
tags question: http://stackoverflow.com/q/51521320
tags question: http://stackoverflow.com/q/51519086
tags question: http://stackoverflow.com/q/51544683
tags question: http://stackoverflow.com/q/51567177
tags question: http://stackoverflow.com/q/51497066
tags question: http://stackoverflow.com/q/51631105
tags question: http://stackoverflow.com/q/51538818
tags question: http://stackoverflow.com/q/51606605
tags question: http://stackoverflow.com/q/51513808
tags question: http://stackoverflow.com/q/51613195
tags question: http://stackoverflow.com/q/51514148
tags question: http://stackoverflow.com/q/51635541
tags question: http://stackoverflow.com/q/51522174
tags question: http://stackoverflow.com/q/51484630
tags question: http://stackoverflow.com/q/51605779
tags question: http://stackoverflow.com/q/51492442
tags question: http://stackoverflow.com/q/51597979
tags question: http://stackoverflow.com/q/51553428
tags question: http://stackoverflow.com/q/51523984
tags question: http://stackoverflow.com/q/51530310
tags question: http://stackoverflow.com/q/51595372
tags question: http://stackoverflow.com/q/51556361
tags question: http://stackoverflow.com/q/51489073
tags question: http://stackoverflow.com/q/51534878

http://stackoverflow.com/comment/90235476
score: 0
has text: You can create an `environment.yml` file from your old anaconda install and use it to create a new environment in anaconda3. The command is `conda env export`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51632310

http://stackoverflow.com/a/51520709
score: 1
has body: If you want your code not to run if p is greater than len(number), add it to the conditions for the while loop: while p &lt;= len(number) and number[p] &lt; 0: if "some condition": #do something else: #do something p=p+1 There's no need to have the same code repeated in both parts of the if/else -- just move it out so it's directly under the while.
answers question: http://stackoverflow.com/q/51520381
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90268025
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51631229
has text: Wait so you are not doing a Byte alignement (byte=8bits), but instead a 4-bits alignment right ?
score: 0

http://stackoverflow.com/comment/90119687
type: Comment
has text: It breaks the while loop because it can't break an if statement, so it breaks the furthest while or for loop outside of it. I've tested it, that part works fine-- it actually fixed something else, bringing it to a break statement instead of a toggled variable.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51577173

http://stackoverflow.com/q/51596766
downvote count: 0
linked to: http://stackoverflow.com/q/3033952
favorite count: 0
accepted answer: http://stackoverflow.com/a/51596843
tagged with: python
has comment: http://stackoverflow.com/comment/90159625
type: AnsweredQuestion
score: 2
has title: Using map with queue.put()?
upvote count: 2
has answer: http://stackoverflow.com/a/51596906
type: Question
possible better answer: http://stackoverflow.com/a/51596906
has answer: http://stackoverflow.com/a/51596942
has answer: http://stackoverflow.com/a/51596843
has body: To load a list into a queue in Python, I found this code snippet which failed to work. No items were added to the queue: from queue import Queue my_list = [1,2,3,4,5,6,7,8,9,10] q = Queue() # This code doesn't work map(q.put, my_list) q.qsize() # Returns zero, which is unexpected The more verbose solution: for num in my_list: q.put(num) print(q.qsize()) # returns 10 as expected works as expected. What am I missing here?
answer count: 3

http://stackoverflow.com/q/51512892
has comment: http://stackoverflow.com/comment/89994358
has answer: http://stackoverflow.com/a/51513081
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89994120
linked to: http://stackoverflow.com/q/5843518
tagged with: python
has body: I have this below text and I am trying to remove the special character shown in the image using Python. Update (pasting the text): 145,Kevin,07/06/2018 15:12:37,Kevin,nan,nan,"have to clear outstanding tasks. check schedule " I tried the below but had no luck DF['col'] = re.sub("[^a-zA-Z]", " ", str(DF['col'])) Could anyone assist on this. Thanks..
tagged with: regex
has comment: http://stackoverflow.com/comment/89994519
has comment: http://stackoverflow.com/comment/89994154
has comment: http://stackoverflow.com/comment/89994376
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89994970
score: -4
has answer: http://stackoverflow.com/a/51514630
has title: Python - Removing special character from string
type: Question
has comment: http://stackoverflow.com/comment/89994186
has comment: http://stackoverflow.com/comment/89994545
has comment: http://stackoverflow.com/comment/89994448
downvote count: 4
has answer: http://stackoverflow.com/a/51514651
answer count: 3
upvote count: 0
has comment: http://stackoverflow.com/comment/89994172

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/51635438
tags question: http://stackoverflow.com/q/51530112
type: Tag

http://stackoverflow.com/a/51566036
has comment: http://stackoverflow.com/comment/90806176
accepted answer of: http://stackoverflow.com/q/51498056
has comment: http://stackoverflow.com/comment/90755077
upvote count: 2
answers question: http://stackoverflow.com/q/51498056
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90145191
has comment: http://stackoverflow.com/comment/90228606
type: Answer
has body: Unfortunately this won't be possible as when you trigger a shutdown naoqi will exit as well and destroy your service. If you are coding in c++ you could use a destructor, but there is no proper equivalent for python... An alternative would be to execute some code when your script exits whatever the reason. For this you can start your script as a service and wait for "the end" using qiApplication.run(). This method will simply block until naoqi asks your service to exit. Note: in case of shutdown, all services are being killed, so you cannot run any command from the robot API (as they are probably not available anymore!)
score: 2

http://stackoverflow.com/comment/90225098
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51630119
has text: I think keeping the type the same as in the question is enough for me to think it's worthwhile. However, you can see in the print of jpp's output counters by default are printed as `Counter({...` instead of `{...`, which is nicer in my opinion. Furthermore, if all I was trying to do was defend my answer, then I'd say the usage of a function is preferable to writing the same loop three times.
type: AnswerComment

http://stackoverflow.com/a/51608139
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90200689
has comment: http://stackoverflow.com/comment/90255197
has body: I think ajax data is placed in the request body. Try this see if you get your data from django.http import QueryDict from django.views.decorators.csrf import csrf_exempt @csrf_exempt def validate_username(request): if request.method == "POST" and request.is_ajax(): # The body of the request is in byte form, # so we decode/convert to string using utf-8 encoding datastring = request.body.decode("utf-8") # The data comes in as if it was coming # from a real form i.e. each field on the model # comes separated by &amp; e.g. the_post=demo&amp;othefield=4 etc # use djangos QueryDict to get a dictionary you can easily # work with. datadictionary = QueryDict(datastring) # retrieve value like any other dictionary description = datadictionary.get("the_post") projects = Project.objects.filter(user__id__icontains = request.user.id)\ .filter(pro_description__icontains = description)\ .values_list('pro_description') response_data = {} try: response_data['result'] = 'Success' response_data['message'] = list(projects) except: response_data['result'] = 'Unsuccessful' response_data['message'] = 'The Subprocess module did not run the script correctly.' return HttpResponse(json.dumps(response_data), content_type="application/json") Please NOTE I have also added the decorator @csrf_exempt on your method to disable csrf protection. Please read on how to set csrf on ajax request
type: Answer
accepted answer of: http://stackoverflow.com/q/51601094
answers question: http://stackoverflow.com/q/51601094

http://stackoverflow.com/q/51498375
upvote count: 2
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89982781
has title: Apscheduler issues with uwsgi
tagged with: nginx
tagged with: uwsgi
downvote count: 0
tagged with: apscheduler
tagged with: flask
favorite count: 0
linked to: http://stackoverflow.com/q/41538435
has body: I have a Python Flask App with Apscheduler that checks if there is a change in an online spreadsheet (Smartsheet). I am caching contents of the spreadsheet in a dictionary (in memory). Everything works fine with the built-in Flask development web server, as well with uwsgi command. However, when I serve the application with nginx + uwsgi, it seems that the scheduler does not work. My question is, will uwsgi spawn multiple copies of the Flask app? How do I use uwsgi mule to trigger a function in the main Flask app? Any pointers is much appreciated. Thanks and regards, Hantzley
tagged with: python
score: 2
answer count: 0

http://stackoverflow.com/a/51583222
has comment: http://stackoverflow.com/comment/90131867
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90131829
has comment: http://stackoverflow.com/comment/90131926
has comment: http://stackoverflow.com/comment/90131914
has body: Let's say I type 5 and then enter at the first prompt: n = int(input()) Would take the input "5" and make it into the integer 5. So we are going from a string to an int Then we will get another input prompt because we have input() again in the next line: This time I'll type 123 324 541 123 134 and then enter. the .split() will split this into "123", "324", "541", "123", "134" which is a list (well a map) of strings. Then we'll map int onto them to give ourselves a map of ints rather than strings. int converts the strings to integers. When checking out code it is often helpful to try things in a REPL (read execute print, looper). In your command promt just type python or python3 if you have it installed or use replt.it. Type a = "123" + "321" then try `a = int("123") + int("321") Wrap this with list(map(int, input().split())) to get a list rather than a map.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51583109
answers question: http://stackoverflow.com/q/51583109
has comment: http://stackoverflow.com/comment/90131894

http://stackoverflow.com/q/51530868
tagged with: pandas
has answer: http://stackoverflow.com/a/51531770
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/43986045
type: UnansweredQuestion
has title: Detect user churn from first day of activity
has body: Inspired by count-consecutive-ones-in-a-dataframe-and-get-indices-where-this-occurs, I would like to do something a bit different. For this DataFrame, id is the index. id day1 day2 day3 day4 day5 day6 1 24 0 0 0 0 0 2 15 0 3 0 0 0 3 9 0 0 0 0 0 4 20 1 0 0 0 0 5 4 0 0 0 0 0 6 3 0 0 1 3 0 7 3 0 0 0 0 0 8 8 0 0 0 2 0 9 8 0 2 0 0 0 10 0 5 2 0 0 0 I would like to count how many id (user), after x number of days of zero activity, will not have any activities anymore. For a given function f(x), and assuming day6 is the last day, f(2) should return 8, since id [1,2,3,4,5,7,9,10] become churn after 2 consecutive 0. f(4) should return 5, since id [1,3,4,5,7] have no activity after 4 consecutive zeros. I believe the implementation should be df.apply(f(x), axis=1), so it iterates on each row and returns a 1 else 0 column. For instance df['churn=4'] = df.apply(f(x), axis=1) shall return: id day1 day2 day3 day4 day5 day6 'churn=4' 1 24 0 0 0 0 0 1 2 15 0 3 0 0 0 0 3 9 0 0 0 0 0 1 4 20 1 0 0 0 0 1 5 4 0 0 0 0 0 1 6 3 0 0 1 3 0 0 7 3 0 0 0 0 0 1 8 8 0 0 0 2 0 0 9 8 0 2 0 0 0 0 10 0 5 2 0 0 0 0 So I can sum up the new column to get the total number of churn=4' users. I got a bit complicated by myself even when drafting the question, please let me know if it is unclear.
type: Question
score: 0

http://stackoverflow.com/q/51566722
tagged with: cartesian-product
downvote count: 1
tagged with: python
tagged with: list
type: UnansweredQuestion
type: Question
tagged with: combinations
score: 1
has body: I'm trying to write a function that generates all possible configurations of a list by swapping certain allowable pairs of elements. For example, if we have the list: lst = [1, 2, 3, 4, 5] And we only allow the swapping of the following pairs of elements: pairs = [[0, 2], [4, 1]] i.e., we can only swap the 0th element if the list with the 2nd, and the 4th element with the 1st (there can be any number of allowed pairs of swaps). I would like the function to return the number of distinct configurations of the list given the allowable swaps. Since I'm planning on running this for large lists and many allowable swaps, it would be preferable for the function to be as efficient as possible. I've found examples that generate permutations by swapping all the elements, two at a time, but I can't find a way to specify certain pairs of allowable swaps.
upvote count: 2
has answer: http://stackoverflow.com/a/51566804
answer count: 1
has title: Generate permutations of list by swapping specific elements
tagged with: permutation
favorite count: 0

http://stackoverflow.com/comment/90200195
type: QuestionComment
comment on: http://stackoverflow.com/q/51616546
score: 0
has text: I thought if I gave API keys then it would help people run the code directly without them having to go through the trouble of creating their own app for the same.
type: Comment

http://stackoverflow.com/comment/90192622
has text: FWIW I tried removing manual flush statements from the IO interface and it had no effect. Also, for the majority of test cases the system works fine, i.e. read() statements block until a message is received, but with certain specific messages it repeatably causes this behavior of no longer blocking.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51602457
score: 0

http://stackoverflow.com/a/51543423
has body: You can use a subprocess and store the output of the shell script you are running. Then you can just output that text to a file like so: import subprocess output = subprocess.Popen(['./script.sh'], stdout=subprocess.PIPE) with open('outfile.txt', 'wb') as outfile: out, err = output.communicate() outfile.write(out.encode('utf-8'))
type: Answer
answers question: http://stackoverflow.com/q/51542965
score: 0

http://stackoverflow.com/q/51591752
favorite count: 0
has body: I have an horizontal barchart in which I am setting the labels with the command: ax.set_yticklabels(df_chart.country_group) I need some of the labels to be bold (and if possible aligned center-ly) depending on some name of the label. I have tried with: ax.set_yticklabels(df_chart.country_group, weight=["bold", "bold", "normal"...]) but the function does not accept a list. I have tries also with a loop: for label in ax.get_yticklabels(): if label in ["World", "Developing countries", "Developed countries"]: label.set_fontproperties(weight="bold") but I was not able to extract the label value from the Text object.
tagged with: python
has answer: http://stackoverflow.com/a/51591946
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51591946
answer count: 1
downvote count: 0
has title: matplotlib conditional formatting labels

http://stackoverflow.com/comment/90203947
comment on: http://stackoverflow.com/q/51619151
type: Comment
type: QuestionComment
has text: How are you communicating with the servers? Many network communication libraries have an adjustable timeout setting. Show us your code and we'll figure out if yours has one.
score: 3

http://stackoverflow.com/q/51491782
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89952145
score: 0
has comment: http://stackoverflow.com/comment/89952880
tagged with: excel
tagged with: oop
tagged with: win32com
type: UnansweredQuestion
has body: I want to create a class to ease my work when creating Excel sheets and extracting data from it. When I run the code without method it works fine and prints the value that i need. import win32com.client t= win32com.client.Dispatch("Excel.Application") t.Visible = True t.Workbooks.Open("C:\\Users\shtu5t\Desktop\Feb-Mar WT Campaign.xlsx") t.Sheets('Working Area').Select() print(t.ActiveSheet.Cells(87,9).Value) But when I want to create a class it works fine until I want extract some data from it. It opens the file that I need and selects the sheet but doesn't get the data from a cell and returns none. import win32com.client class Excel: def __init__(self): self.Eserver=win32com.client.Dispatch("Excel.Application") self.Eserver.Visible=True def open(self,path): self.open=self.Eserver.Workbooks.Open(path) def select_sheet(self,name): self.select_sheet=self.Eserver.Sheets (name).Select() def select_data(self,row,column): self.select_data=self.Eserver.ActiveSheet.Cells(row,column).Value B=Excel() B.open("C:\\Users\shtu5t\Desktop\Feb-Mar WT Campaign.xlsx") B.select_sheet('Working Area') print(B.select_data(87,1)) Please, could you tell me what I am doing wrong? Thank you for your attention!
has title: Working with excel in python- method returns none
answer count: 0
has comment: http://stackoverflow.com/comment/89953215

http://stackoverflow.com/comment/89956793
score: 0
type: Comment
has text: Thank you. Was looking for this!
comment on: http://stackoverflow.com/a/51493719
type: AnswerComment

http://stackoverflow.com/comment/90137803
score: 0
has text: @MadPhysicist It's related, I already did other parts, and this is the last part I need to solve. Thanks.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51586003

http://stackoverflow.com/q/51565853
type: Question
has answer: http://stackoverflow.com/a/51570044
has comment: http://stackoverflow.com/comment/90098724
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51570044
has comment: http://stackoverflow.com/comment/90098753
has comment: http://stackoverflow.com/comment/90104365
tagged with: python
has title: Selenium can't find javascript generated elements
type: AnsweredQuestion
upvote count: 2
score: 1
has body: So, what i want do is start the browser, get the page content (with the JavaScript rendered) and find the element i want using BeautifulSoup, here's my code: from selenium import webdriver from bs4 import BeautifulSoup as bs4 from selenium.webdriver.support.ui import WebDriverWait browser = webdriver.Edge() browser.get('https://www.premierleague.com/match/22721') element = WebDriverWait(browser, 10) html=bs4(browser.page_source,'html.parser') print(html.body.main.find('div',attrs={'class':'mcTabs'})) browser.quit() I get None from the print statement
tagged with: selenium
downvote count: 1

http://stackoverflow.com/a/51515857
has body: First flatten values in columns by numpy.ravel, create DataFrame by contructor and last add drop_duplicates, thanks @zipa: a = df'A','B'.values.ravel() b = df'ax','bx'.values.ravel() c = df'ay','by'.values.ravel() df = pd.DataFrame({'ID':a, 'x':b, 'y':c}).drop_duplicates('ID').reset_index(drop=True) print (df) ID x y 0 x 5 7 1 y 3 2 2 z 2 0 3 w 7 4 4 k 5 7 5 v 2 3
answers question: http://stackoverflow.com/q/51515733
downvote count: 0
type: Answer
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/90000155

http://stackoverflow.com/a/51512281
answers question: http://stackoverflow.com/q/51512252
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51512252
score: 0
type: Answer
has body: First column is index, so possible rename is by: df.index.name = 'val' Or: df = df.rename_axis('val') But if want avoid write first column (index) to excel, use: df.to_excel('file.xlsx', index=False) EDIT: There is problem if use inplace=True it return None, so df2 is None, not DataFrame.

http://stackoverflow.com/a/51557714
downvote count: 0
has comment: http://stackoverflow.com/comment/90082658
score: 1
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90083862
answers question: http://stackoverflow.com/q/51552327
has body: Unsure if it will meet your requirement because I could not test it on 3Gb files. I have slightly improved your code: I store full keys in a set, meaning pairs (ID, Date) from file1 I read each file only once I only store one row at time in memory for both input files Here is my code: from __future__ import print_function import dateutil.parser as dparser from dateutil.parser import parse import csv file1 = 'E:\File1.txt' file2 = 'E:\File2.txt' file3 = 'E:\OUTFile.txt' file4 = 'E:\Errors.txt' with open(file1, 'r') as f1: firstline = f1.readline() print('File1 Header:',firstline.strip('\n')) file1_delimiter = raw_input('Please provide the delimiter:') with open(file2, 'r') as f2: firstline = f2.readline() print('\nFile2 Header:',firstline.strip('\n')) file2_delimiter = raw_input('Please provide the delimiter:') file_1_set = set() file_1_set = set() def is_date(string): print(string) try: parse(string) return True except ValueError: return False with open(file1, 'r') as f1, open(file2, 'r') as f2: rd1 = csv.reader(f1, delimiter = file1_delimiter) headerList1 = next(rd1) print('\n---File1, Column Index with Header---') for i, item in enumerate(headerList1): print(i,item) file1_header1 = input("Enter column1 number:") file1_header2 = input("Enter column2 number:") rd2 = csv.reader(f2, delimiter = file2_delimiter) headerList2 = next(rd2) print('\n---File2, Column Index with Header---') for i, item in enumerate(headerList2): print(i, item) file2_header1 = input("Enter column1 number:") file2_header2 = input("Enter column2 number:") for x in rd1: if x[file1_header1] and is_date(x[file1_header2]): file_1_set.add((x[file1_header1], dparser.parse(x[file1_header2], fuzzy=True).date())) with open(file3, 'wb') as out_file, open(file4, 'wb') as err: out_wr = csv.writer(out_file, delimiter = file2_delimiter) err_wr = csv.writer(err, delimiter = file2_delimiter) out_wr.writerow(headerList2) f_2_result = [] for x in rd2: if not is_date(x[file2_header2]): err_wr.writerow(x) elif x[fi…

http://stackoverflow.com/q/51550549
answer count: 1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90074817
has title: pyShipping package installation fails
has comment: http://stackoverflow.com/comment/90068649
type: Question
has body: I tried installing python package pyShipping using Anaconda prompt but it resulted in an error Microsoft Visual C++ 14.0 is required so I installed Microsoft Visual C++ 14.0 and retried installing pyShipping package but still, it gives me the same error. Help me in this case!
has answer: http://stackoverflow.com/a/51554651
score: 0

http://stackoverflow.com/a/51603702
upvote count: 2
answers question: http://stackoverflow.com/q/51603684
has body: You are changing the iterable while iterating over it. So once you delete a object from it, it may skip the next one. If you iterate over a copy, this problem goes away, e.g. for i in names_friends[:]: print(i) names_friends.remove(i)
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/a/71238416
answers question: http://stackoverflow.com/q/51517053
has body: use ctrl + alt + s to open interpreter the select the one you wanted to use that is for the environment you have chosen. If you wanted to change the interpreter for the environment the go to the interpreter settings after pressing the ctrl + alt + s and select the environment interpreter.
score: 0
type: Answer

http://stackoverflow.com/q/51585965
has body: I write this code for web scraping work: browser.find_element_by_class_name('open_all_j').click() This code line gives me an error: selenium.common.exceptions.ElementNotVisibleException: Message: element not visible My full code: from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common import keys, action_chains from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup as soup import xlwt def click_time(): browser = webdriver.Chrome("./Drivers/chromedriver.exe") browser.implicitly_wait(20) browser.get("https://www.geegeez.co.uk/race-cards/#display=cards&amp;day=0") timeTable = browser.find_elements_by_class_name('meeting') timeRow = timeTable[0].find_element_by_class_name("races") timeRowTable = timeRow.find_elements_by_class_name("race_card_race") timeRowTD = timeRowTable[0].find_elements_by_xpath("//table") x = timeRowTable[0].find_element_by_class_name("cardstable") y = x.find_element_by_class_name("racetime") y.click() print('\n', len(browser.find_elements_by_id('tabs-cards')), '\n') wait = WebDriverWait(browser, 20) elem = wait.until(EC.presence_of_element_located((By.ID, "tabs-cards"))) #browser.find_element_by_xpath("//div[@class = 'open_all_r']").click() #find_element_by_class_name('open_all_r') browser.find_elements_by_class_name('open_all_j')[0].click() browser.find_elements_by_class_name('open_all_t')[0].click() I tried to use: browser.find_element_by_xpath("//div[@class = 'open_all_r']").click() This code line gives me the same error. Please help me...
type: Question
has title: ElementNotVisibleException error in Python/Selenium webdriver
has answer: http://stackoverflow.com/a/51586694
has answer: http://stackoverflow.com/a/51587095
has comment: http://stackoverflow.com/comment/90139414
tagged with: web-scripting
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90137875
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51587747
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium
tagged with: ui-automation

http://stackoverflow.com/comment/89953451
has text: @mzjn. I think we're at cross purposes here. I fully understand that the mapping is being populated. However, it's not a regular dict. I've made it so that repr(test) == format(test) == str(test) == '{}'. Where does the string in the documentation come from then?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51487209

http://stackoverflow.com/q/51553280
has body: I'm working on a casino program that gets a bet ($1-$50) from the user, then pulls a slot machine to display a three-string combination of "7", "cherries", "bar", or "(space)". Certain combinations will trigger a bet multiplier, and the user will win back this amount. The run should look like this: ask user for bet, show user the pull and their winnings, then ask user for a new bet, display a new pull, and so on. Right now, I have everything down except for a couple problems - I cannot make it so that the program generates a new random combination for each pull. Secondly, the main loop continues forever, printing the user's pull and winnings forever. Below is the method that generates either "7", "cherries", etc. def rand_string(self): random.seed(0) # produces a number between 0 and 999 test_num = random.randrange(1000) # precompute cutoffs bar_cutoff = 10 * TripleString.BAR_PCT cherries_cutoff = bar_cutoff + 10 * TripleString.CHERRIES_PCT space_cutoff = cherries_cutoff + 10 * TripleString.SPACE_PCT # bar = 38%, cherries = 40%, space = 7%, seven = 15% if test_num &lt; bar_cutoff: return TripleString.BAR elif test_num &lt; cherries_cutoff: return TripleString.CHERRIES elif test_num &lt; space_cutoff: return TripleString.SPACE else: return TripleString.SEVEN And here is the loop in main: while(True): if bet == 0: #a bet of $0 ends the program print("Please come again!") break else: print("whirrr...and your pull is " +\ object.pull()) object.display(None) I thought I could solve this by somehow adding 1 to random.seed() for each loop (we begin with random.seed(0), but for each new pull 1 is added so that random.seed(1) and so on), but I don't know how to go about doing this and I'm not even sure if it's doable. If someone could point out my mistakes here, that'd be great. (sorry if this makes no sense, I'm very new to Python).
has answer: http://stackoverflow.com/a/51553324
tagged with: methods
type: Question
has title: trying to +1 to random.seed() for every loop
score: 0
tagged with: random
answer count: 1
has comment: http://stackoverflow.com/comment/90073521
tagged with: while-loop
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90166516
comment on: http://stackoverflow.com/q/51600164
score: 0
has text: `extend` returns `None`, as it is an in-place operation
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51538665
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90046622
has comment: http://stackoverflow.com/comment/90046363
tagged with: selenium
has comment: http://stackoverflow.com/comment/90047380
type: Question
has comment: http://stackoverflow.com/comment/90047440
has comment: http://stackoverflow.com/comment/90046310
has comment: http://stackoverflow.com/comment/90046782
score: 0
has title: How to quit two Selenium webdrivers?
has body: I'm trying to use two different browser windows and then eventually closing them. I can access each of them separately but when I try to close them both only driver2 gets closed, no matter the focus. from selenium import webdriver driver1 = webdriver.Firefox() driver1.get("https://google.com/") driver2 = webdriver.Firefox() driver2.get("https://google.com/") driver1.quit() driver2.quit() Is there another way to do this? I'm using Geckodriver v.0.21.0, Firefox v61.0.1 and Selenium v3.13 on macOS High Sierra.
tagged with: selenium-firefoxdriver
tagged with: macos
has comment: http://stackoverflow.com/comment/90044931
has comment: http://stackoverflow.com/comment/90044830
has comment: http://stackoverflow.com/comment/90046679

http://stackoverflow.com/comment/107367612
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/60685097
has text: Also, `lambda: list()` can be shortened to just `list`.

http://stackoverflow.com/comment/90075079
type: AnswerComment
has text: Sorry there was a small mistake I rewrote it. Notice that in place of you re.match I changed to if True for simplicity
type: Comment
comment on: http://stackoverflow.com/a/51553555
score: 0

http://stackoverflow.com/q/51492385
tagged with: python
tagged with: roi
tagged with: opencv
type: AnsweredQuestion
score: 2
tagged with: python-tesseract
upvote count: 2
has title: Python cv2.error: OpenCV(3.4.1) error: (-215) !_src.empty() in function fastNlMeansDenoising when using calculated values inside array
has answer: http://stackoverflow.com/a/51494156
type: Question
has body: I am currently using OpenCV and PyTesseract to read image from an ROI specified. Here's what I've come through: import pytesseract import urllib import math import cv2 import numpy as np from unidecode import unidecode from PIL import Image def process_image(path=None): if path != None: original_image = cv2.imread(path) original_height, original_width = original_image.shape[:2] image = cv2.resize(original_image, (640, int(math.floor(original_height*640/original_width)))) cv2.imwrite('./uploads/resized_image.jpg', image) height, width = image.shape[:2] else: return "Terjadi kesalahan, harap hubungi administrator." print(height) print(width) coord = [ [height - 84, 34, height, 624] #Barcode # [378, 415, 364, 583], #Tanggal Lahir # [605, 656, 32, 992] ] result = None print ("Recognizing...") for x in coord: roi = image[x[0]:x[1],x[2]:x[3]] print(x[0]) print(x[1]) print(x[2]) print(x[3]) gray = cv2.cvtColor(roi,cv2.COLOR_RGB2GRAY) ret2,th2 = cv2.threshold(gray,128,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) dst = cv2.fastNlMeansDenoising(th2,10,10,7) cv2.imwrite('./uploads/tmp.jpg',dst) cao = Image.open('./uploads/tmp.jpg') rec_string = pytesseract.image_to_string(cao,lang='deu') if result != None: result += "\n" + rec_string else: result = rec_string print ("the result is {}".format(result)) return result Here you can see that, it gets an image, resize it to certain size, and write the image into new one called resized_image.jpg. Then, I'm trying to create an ROI from coordinates based on height. Take a look at coord array, you can see that I'm trying to get the bottom component by taking coordinates from height - 84 to height, and width from 34 to 624. It turns out well, after the "Recognizing..." text I printed out if the values were right. It is, but the image won't be processed, and this error pops out: File ./uploads/24-07-2018/aenkjtWIBYuTZsaU.jpg telah diupload 903 640 Recognizing... 819 34 903 624 OpenCV(3.4.1) Error: Assertion failed (!_src.empty()) in fastNlMeansD…
accepted answer: http://stackoverflow.com/a/51494156
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/51535181
type: Answer
score: 3
downvote count: 0
has body: &gt;&gt;&gt; '\x01\x03\x00\x00\x00\x01...'.encode('hex') '0103000000012e2e2e' As an added bonus... It's hex values that fall within ASCII characters. Since you have a bytestring, values within ASCII are represented as text.
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51535102
answers question: http://stackoverflow.com/q/51535102

http://stackoverflow.com/comment/90101739
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51567648
has text: https://github.com/d-Rickyy-b/Meet-n-Bot
score: 0

http://stackoverflow.com/q/51521655
has body: I have a DataFrame (df) which consists of more than 50 columns and different types of data types, such as df3.printSchema() CtpJobId: string (nullable = true) |-- TransformJobStateId: string (nullable = true) |-- LastError: string (nullable = true) |-- PriorityDate: string (nullable = true) |-- QueuedTime: string (nullable = true) |-- AccurateAsOf: string (nullable = true) |-- SentToDevice: string (nullable = true) |-- StartedAtDevice: string (nullable = true) |-- ProcessStart: string (nullable = true) |-- LastProgressAt: string (nullable = true) |-- ProcessEnd: string (nullable = true) |-- ClipFirstFrameNumber: string (nullable = true) |-- ClipLastFrameNumber: double (nullable = true) |-- SourceNamedLocation: string (nullable = true) |-- TargetId: string (nullable = true) |-- TargetNamedLocation: string (nullable = true) |-- TargetDirectory: string (nullable = true) |-- TargetFilename: string (nullable = true) |-- Description: string (nullable = true) |-- AssignedDeviceId: string (nullable = true) |-- DeviceResourceId: string (nullable = true) |-- DeviceName: string (nullable = true) |-- srcDropFrame: string (nullable = true) |-- srcDuration: double (nullable = true) |-- srcFrameRate: double (nullable = true) |-- srcHeight: double (nullable = true) |-- srcMediaFormat: string (nullable = true) |-- srcWidth: double (nullable = true) Now I wants all one type columns can be changed in one go such as timestamp_type = [ 'PriorityDate', 'QueuedTime', 'AccurateAsOf', 'SentToDevice', 'StartedAtDevice', 'ProcessStart', 'LastProgressAt', 'ProcessEnd' ] integer_type = [ 'ClipFirstFrameNumber', 'ClipLastFrameNumber', 'TargetId', 'srcHeight', 'srcMediaFormat', 'srcWidth' ] I know how to do one by one as i'm doing now. df3 = df3.withColumn("PriorityDate", df3["PriorityDate"].cast(TimestampType())) df3 = df3.withColumn("QueuedTime", df3["QueuedTime"].cast(TimestampType())) df3 = df3.withColumn("AccurateAsOf", df3["AccurateAsOf"].cast(TimestampType()) df3= df3.withColumn("srcMediaF…
tagged with: python
has comment: http://stackoverflow.com/comment/90017031
has comment: http://stackoverflow.com/comment/90014967
accepted answer: http://stackoverflow.com/a/51524636
upvote count: 1
tagged with: databricks
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90017345
score: 1
tagged with: pyspark
has title: Specify multiple columns data type changes to different data types in pyspark
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51524636
favorite count: 0
tagged with: apache-spark
tagged with: pandas

http://stackoverflow.com/a/51494559
type: Answer
answers question: http://stackoverflow.com/q/51494140
has body: Use lxml to get the XML comment in the description element. from lxml import etree tree = etree.parse("so.xml") comment = tree.xpath("/rss/channel/item/description/comment()")[0].text print(comment.split("\n")[2]) Output: &lt;ESCYL2400000024153A;(24,4;24,5;12,1;sun);(49,0;91,0;49,0);(1021,0;1021,2;1019,9);(5,0;10,0;219);(0,0);Sta Mar&amp;#237;a del Condado&gt;
score: 0

http://stackoverflow.com/comment/89992573
type: Comment
has text: @jezrael I saw the post but it does not explain why the error is occurring when I have explicitly given the argument for inplace=True
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51511972

http://stackoverflow.com/a/51610020
answers question: http://stackoverflow.com/q/51573298
type: Answer
has body: You Probably have not installed the Quandl package properly. Because I've tried it in Juypter Notebook before installation it gives me the same error that you are getting. But after installing the package it works fine. Please see the attached screenshot. Incase of command line installation please type the following command: pip install quandl Quandl Installation Link If it gives the pip installation then first you need to install pip.
score: 0
has comment: http://stackoverflow.com/comment/90209497

http://stackoverflow.com/comment/90271309
score: 1
type: AnswerComment
has text: Have a look: https://developers.google.com/analytics/devguides/reporting/core/dimsmets
comment on: http://stackoverflow.com/a/51652319
type: Comment

http://stackoverflow.com/q/51557543
has comment: http://stackoverflow.com/comment/90082211
has body: I have a script that I activate via the terminal that listens to events. I want to keep using the terminal after the script runs, but the script is running and I can't type anything. The only way I know that lets me keep typing is by using the Ctrl + C combination, but this stops the script. So how can I run the script in the background and keep using the terminal without terminating it? Edit: I tried to use the '&amp;' operator but it didn't work:
duplicate of: http://stackoverflow.com/q/44222883
upvote count: 1
answer count: 1
has title: Run Python script on Terminal and keep using the terminal afterwards
favorite count: 0
tagged with: linux
tagged with: python
has answer: http://stackoverflow.com/a/51557739
accepted answer: http://stackoverflow.com/a/51557739
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90082256
downvote count: 0
has comment: http://stackoverflow.com/comment/90082324
score: 1
has comment: http://stackoverflow.com/comment/90081815
has comment: http://stackoverflow.com/comment/90082201
type: Question
has comment: http://stackoverflow.com/comment/90082889
linked to: http://stackoverflow.com/q/44222883

http://stackoverflow.com/comment/90044788
score: 0
has text: @MikeHousky Thanks for the correction, I'll change the title.
type: Comment
comment on: http://stackoverflow.com/q/51538192
type: QuestionComment

http://stackoverflow.com/a/51540755
downvote count: 0
has comment: http://stackoverflow.com/comment/90065567
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51529680
has comment: http://stackoverflow.com/comment/90115942
accepted answer of: http://stackoverflow.com/q/51529680
has body: You need to first probe whether the dictionary already contains the key for which you're attempting to add a new value. Once you've determined if the key already exists, you can then check whether the returned value is a single number, or a list of numbers and act accordingly. In pseudocode: # Get current value associated with new key in dict. # If returned value is None, add new value for key in question. # Else If returned value is a list, append new value to list, store list for key in question # Else, returned value was a single number; create a list of returned value and new value. Store list for key in question. A solution in Python: class DictUtil(object): """ A utility class that automates handling of key collisions for a dictionary object. """ @staticmethod def add_to_dict(dict, new_key, new_value): # Get whatever currently exists within the dictionary for the given key. value_in_dict = dict.get(new_key) # If the value for the given key is None, there is no current entry, so we can add the new value. if value_in_dict is None: dict[new_key] = new_value # If the value for a given key returned a list, append new value to list and re-store in dict. elif type(value_in_dict) in [list, tuple]: dict[new_key].append(new_value) # Otherwise, the get returned a single item. Make a list of the returned value and the new value and re-store. else: dict[new_key] = [value_in_dict, new_value] def main(): """ Entry point for an example script to demonstrate Dictutil functionality. """ dict = {} # Populating values in dict using Dictutil method: add_to_dict: DictUtil.add_to_dict(dict, 'a', 2) DictUtil.add_to_dict(dict, 'a', 1) DictUtil.add_to_dict(dict, 'b', 2) DictUtil.add_to_dict(dict, 'a', 4) DictUtil.add_to_dict(dict, 'a', 3) DictUtil. add_to_dict(dict, 'b', 1) DictUtil.add_to_dict(dict, 'b', 2) DictUtil.add_to_dict(dict, 'c', 1) # Printing dictionary contents for key, value in dict.iteritems(): print 'Key: %s \t Value: %s' % (key, value) if __name__ == '__main__': main()
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/51592631
tagged with: beautifulsoup
score: 0
has answer: http://stackoverflow.com/a/51594171
accepted answer: http://stackoverflow.com/a/51594171
tagged with: python
tagged with: parsing
tagged with: web-scraping
type: AnsweredQuestion
has body: I need some concept how to parse a real estate market using Python. I've searched some information about parsing the websites, I even did this in VBA, but I would like to do it in python. This is the site which will be parsed (it's one offer only now, but it will be working on full range of real estate offers, multiple sites from kontrakt.szczecin.pl): http://www.kontrakt.szczecin.pl/mieszkanie-sprzedaz-100m2-335000pln-grudziadzka-pomorzany-szczecin-zachodniopomorskie,351149 First of all, program will use 3 pieces of information: 1/ The table where is information (Main parameters): Numer oferty 351149, Liczba pokoi 3, Cena 335 000 PLN, Cena za m2 3 350 PLN (Number of offer, Room no, Price, Price by square meter etc). However the quantity of information depends on property offer: sometimes is 14, sometimes is 12, sometimes 16 etc. 2/ Description of property in paragraphs (it is another part of program, for now it can be skipped): Sometimes in the table (1/) there is information that there is garage or balcony. But in paragraph there is a sentence that garage is for additional price (which means for me that property doesn't have garage) or balcony is in French type (which is no balcony for me). I managed that program should find the correct word in paragraph (such as garage) and copy text from paragraph with additional text on the left and right side (for instance: 20 letters in both sides, but what if the word is in the first place?) 3/ Additional Parameters - Not every offer has it but like this one (http://www.kontrakt.szczecin.pl/mieszkanie-sprzedaz-6664m2-339600pln-potulicka-nowe-miasto-szczecin-zachodniopomorskie,351165) there is information about number of balconies in property. Sometimes there is information about basement too. It should be similar code to the 1/ issue. So I tried something like this, using some internet sources (it is still incomplete): from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = "http://www.kontr…
type: Question
has title: Real Estate Market Scraping using Python and BeautifulSoup
has comment: http://stackoverflow.com/comment/90153598
answer count: 1

http://stackoverflow.com/comment/90179686
comment on: http://stackoverflow.com/a/51606610
score: 0
type: AnswerComment
type: Comment
has text: OK I just restarted Spyder and now it works. Go figure? Thanks for the help everyone.

http://stackoverflow.com/comment/90074817
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51550549
has text: I used `pip install pyShipping`

gmail
type: Tag
tags question: http://stackoverflow.com/q/51633787
tag name: gmail

http://stackoverflow.com/a/51628125
answers question: http://stackoverflow.com/q/51628032
score: 0
type: Answer
has body: Naive approach using a dict comprehension and simple division: c = Counter('abbccc') s = sum(c.values()) perc = {k: v*100.0/s for k, v in c.items()} # {'a': 16.666666666666668, 'b': 33.333333333333336, 'c': 50.0}

http://stackoverflow.com/comment/90013931
has text: If they column names are always two characters, one letter and one number, you can rewrite `is_symmetrical` using `ord(x[0])` for the letter part and `int(x[1])` for the number part to define the new symmetric function.
type: AnswerComment
comment on: http://stackoverflow.com/a/51514716
score: 0
type: Comment

http://stackoverflow.com/q/51541943
type: AnsweredQuestion
has body: My goal is to scale a numpy array so that all numbers are between 0 and 1. In sklearn.preprocessing.scale() the documentation states: axis : int (0 by default) axis used to compute the means and standard deviations along. If 0, independently standardize each feature, otherwise (if 1) standardize each sample. My question is, what is the difference between standardizing each feature and each sample?
has answer: http://stackoverflow.com/a/51542037
type: Question
tagged with: numpy
has title: Difference between Features and Samples in sklearn?
score: 0
answer count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/51542037
tagged with: python

http://stackoverflow.com/comment/90170192
type: AnswerComment
score: 0
type: Comment
has text: @trixn He/she did not understand why we need it and not simply use django rest framework with seperate frontend
comment on: http://stackoverflow.com/a/51601664

http://stackoverflow.com/a/51518975
has comment: http://stackoverflow.com/comment/90008473
has body: The primary problem with your approach is that you're comparing floating-point values exactly. This is almost always a very bad idea due to rounding errors, demonstrated in this infamous example: &gt;&gt;&gt; 0.1 + 0.2 == 0.3 False Note that numpy doubles and native python doubles are fundamentally similar (I'm not sure about the dependence of sizes depending on architecture in either case, but you probably get my point). So firstly you should always use np.isclose/np.allclose for comparing floats for equality. Secondly, which is the reason I'm posting a full answer: you don't have to use a list comprehension, you can do what you want in a single numpy broadcasting call to isclose: &gt;&gt;&gt; idx, data_idx = np.isclose(time[:,None], p_times).nonzero() &gt;&gt;&gt; idx array([ 9, 10, 11, 19, 20, 21, 29, 30, 31, 39, 40, 41, 49, 50, 51, 59, 60, 61, 69, 70, 71, 79, 80, 81, 89, 90, 91]) What happens here is that the time array is converted to a 2d column array by injecting a trailing singleton dimension, and a matrix of bools is constructed by pairing every time point to every p_times point. The final call to nonzero() returns the indices of the True values: the first output idx contains the indices you're looking for. This method is also safer, in that it won't throw an exception if a peak doesn't have a matching time. Instead you'll have fewer idx values than p_times points. In this case you'd be able to use data_idx to locate the indices of the peaks that were actually found: &gt;&gt;&gt; data_idx 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])
type: Answer
upvote count: 5
accepted answer of: http://stackoverflow.com/q/51518153
score: 5
answers question: http://stackoverflow.com/q/51518153
type: AcceptedAnswer
downvote count: 0

binary-search-tree
tags question: http://stackoverflow.com/q/51530678
tags question: http://stackoverflow.com/q/51576237
type: Tag
tag name: binary-search-tree
tags question: http://stackoverflow.com/q/51623790

http://stackoverflow.com/q/51530947
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51531300
tagged with: dataframe
tagged with: date
has body: Hello I am newish to python and pandas I have two DataFrames, one on a higher timeframe with Daily granularity, and one on a lower timeframe with hourly granularity. What I want to do is append the 'trend' data from the higher timeframe to the lower time frame where the day is the same. I'm having some trouble. My DataFrames have datetime index and look something like this: Higher time frame: time state 2015-06-03 22:00:00 bullish 2015-06-04 22:00:00 bullish 2015-06-05 22:00:00 bearish 2015-06-06 22:00:00 bullish 2015-06-07 22:00:00 bullish 2015-06-08 22:00:00 bullish Lower time frame: time state 2015-06-05 05:00:00 bullish 2015-06-05 09:00:00 bullish 2015-06-05 13:00:00 bullish 2015-06-05 17:00:00 bullish 2015-06-07 21:00:00 bullish 2015-06-08 01:00:00 bullish And my desired result would look like this: time state trend 2015-06-05 05:00:00 bullish bearish 2015-06-05 09:00:00 bullish bearish 2015-06-05 13:00:00 bullish bearish 2015-06-05 17:00:00 bullish bearish 2015-06-07 21:00:00 bullish bullish 2015-06-08 01:00:00 bullish bullish Any help much appreciated!!
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51531300
tagged with: python
type: AnsweredQuestion
score: 1
has title: How to add data from another DataFrame, where differing granularities of dates match?

http://stackoverflow.com/a/51557448
score: 1
has body: In Python 3.7: import asyncio import websockets CAPTURE_INTERVAL = 1 running = True queues = set() async def handle(ws, path): queue = asyncio.Queue() queues.add(queue) while running: data = await queue.get() if not data: break await ws.send(data) def capture_screen(): # Do some work here, preferably in C extension without holding the GIL return b'screenshot data' async def main(): global running loop = asyncio.get_running_loop() server = await websockets.serve(handle, 'localhost', 8765) try: while running: data = await loop.run_in_executor(None, capture_screen) for queue in queues: queue.put_nowait(data) await asyncio.sleep(CAPTURE_INTERVAL) finally: running = False for queue in queues: queue.put_nowait(None) server.close() await server.wait_closed() if __name__ == '__main__': asyncio.run(main()) Please note, this is only for demonstrating the producer-consumer fan-out pattern. The queues are not essential - you can simply send data to all server.sockets in main() directly, while in handle() you should worry about incoming websocket messages. For example, client may control image compression rate like this: import asyncio import websockets CAPTURE_INTERVAL = 1 DEFAULT = b'default' qualities = {} async def handle(ws, path): try: async for req in ws: qualities[ws] = req finally: qualities.pop(ws, None) def capture_screen(): # Do some work here, preferably in C extension without holding the GIL return { DEFAULT: b'default screenshot data', b'60': b'data at 60% quality', b'80': b'data at 80% quality', } async def main(): loop = asyncio.get_running_loop() server = await websockets.serve(handle, 'localhost', 8765) try: while True: data = await loop.run_in_executor(None, capture_screen) for ws in server.sockets: quality = qualities.get(ws, DEFAULT) if quality not in data: quality = DEFAULT asyncio.create_task(ws.send(data[quality])) await asyncio.sleep(CAPTURE_INTERVAL) finally: server.close() await server.wait_closed() if __name__ == '__main__': asyncio.run(main())
answers question: http://stackoverflow.com/q/51548025
upvote count: 1
has comment: http://stackoverflow.com/comment/90090852
accepted answer of: http://stackoverflow.com/q/51548025
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/51590480
has body: I've got two models (participant, holder) which have the same fields: first_name, last_name and date_of_birth In the detail view of my participant Model I check if those fields are the same as in my holder model: for holder in Holder.objects.all(): if participant.last_name == holder.last_name and participant.first_name == holder.first_name and participant.date_of_birth == holder.date_of_birth: has_item = True and then return that with a render_to_response return self.render_to_response({ 'has_item': has_item, }) And in my HTML I've got then this: {% if has_item %}Voucher(s) found {% else %}No voucher found{% endif %} This links the user from the detail view of my participant to my ListView of my Vouchers with all Holders listed in a table. Now my question would be, when redirecting the user to this List, is it possible to somehow highlight the exact user that was found having the vouchers? So for example if John Doe has a voucher, show the link in his profile, which redirects him to the list of all holders and highlights every row where his FirstName, Lastname and Date of birth is the same. Is that possible with maybe using JavaScript?
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/51590725
answer count: 1
tagged with: javascript
has comment: http://stackoverflow.com/comment/90146542
has comment: http://stackoverflow.com/comment/90146232
has comment: http://stackoverflow.com/comment/90146488
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51590725
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90146574
has comment: http://stackoverflow.com/comment/90146609
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90146353
has title: Django: Highlight Table Row when user is found

http://stackoverflow.com/comment/90064129
type: Comment
type: QuestionComment
has text: take a look here : https://pip.readthedocs.io/en/1.4/configuration.html
comment on: http://stackoverflow.com/q/51548114
score: 0

http://stackoverflow.com/q/51504586
has answer: http://stackoverflow.com/a/64816003
tagged with: python
type: AnsweredQuestion
has body: I'm using a functools.lru_cache to serve temp file paths given certain input*. However in case the path no longer exists, I would like to remove/replace the single corresponding key. The cache_clear() method would be overkill and cache_info() do not appear to help. Thanks for your help! * The method being cached streams a fileobj from S3 to a local temp file.
possible better answer: http://stackoverflow.com/a/55993346
has answer: http://stackoverflow.com/a/55993346
type: Question
tagged with: functools
score: 10
upvote count: 10
tagged with: caching
has answer: http://stackoverflow.com/a/52101715
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/52101715
favorite count: 0
tagged with: python-3.x
has title: Can One Replace or Remove a specific key from functools.lru_cache?
tagged with: lru

http://stackoverflow.com/comment/90206568
has text: Yes, I am testing it in "python manage.py shell", however in the website the same error message
type: AnswerComment
comment on: http://stackoverflow.com/a/51620355
score: 0
type: Comment

http://stackoverflow.com/comment/90067670
comment on: http://stackoverflow.com/q/51549941
has text: @MadLee Its the same error ` from src.account.api.serializers import UserDisplaySerializer ModuleNotFoundError: No module named 'src' `
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90227083
type: Comment
has text: You can refer to [this example](https://github.com/tensorflow/serving/blob/aa35cfdb24016f6d88f82c53d45c8ce9fa550499/tensorflow_serving/model_servers/tensorflow_model_server_test_client.py)
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51615972

http://stackoverflow.com/a/51628793
has body: I found the original code that you are talking about. I assume it's : import matplotlib.pyplot as plt # Load the image into an array: img img = plt.imread('myImage.jpg') # Print the shape of the image print(img.shape) # Outputs : (480, 480, 3) Then it calculates the sum of intensities over the third channel. Remember the axes are : 0, 1 and 2. # Compute the sum of the red, green and blue channels: intensity intensity = img.sum(axis=2) If you print the shape of the intensity : # Print the shape of the intensity print(intensity.shape) # Output : (480, 480) This means that for each couple of position (axe0_point, axe1_point), you sum the values of the axe 2. For example, if img[50,50] == [10,10,10], you'll have intensity[50,50] = 30
accepted answer of: http://stackoverflow.com/q/51628437
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51628437

http://stackoverflow.com/comment/90147805
type: QuestionComment
comment on: http://stackoverflow.com/q/51546255
score: 1
has text: What tools do you use to bind the Fortran code? (f2py, iso_c_binding, other?) Are you aware of NumPy's distutils modification for this purpose? https://docs.scipy.org/doc/numpy/reference/distutils.html
type: Comment

greatest-n-per-group
tag name: greatest-n-per-group
tags question: http://stackoverflow.com/q/51509141
type: Tag

http://stackoverflow.com/comment/89947325
comment on: http://stackoverflow.com/q/51489205
has text: Filter by the second axis to filter by column: `arr[:, arr[2]>0]`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90235710
has text: @VeltzerDoron if the complexity is `O(n/log(n))` it will look like `O(n)` on a smaller scale. `log(n)` grows so slowly that it is hard to find a scale on which the slope of the curve is visibly changing.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51632183

http://stackoverflow.com/comment/90041886
has text: @RogerLePatissier, Yes, sometimes it's useful to explore ways to *avoid* double masks. Usually it's possible in a vectorised way.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51535580
type: Comment

http://stackoverflow.com/a/51621897
has body: Code that works - import os import shutil from tkinter import * from tkinter import filedialog root = Tk() root.withdraw() filePath = filedialog.askopenfilename() folderPath = filedialog.askdirectory() destination = filedialog.askdirectory() # First, create a list and populate it with the files # you want to find (1 file per row in myfiles.txt) filesToFind = [] with open(filePath, "r") as fh: for row in fh: filesToFind.append(row.strip()) # Had an issue here but needed to define and then reference the filename variable itself for filename in os.listdir(folderPath): if filename in filesToFind: filename = os.path.join(folderPath, filename) shutil.copy(filename, destination) else: print("file does not exist: filename") Note - Need to included the file extension in the file being read. Thanks to @lenik and @John Gordon for the help getting there! Time to refine it to make it more userfriendly
answers question: http://stackoverflow.com/q/51528103
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51528103
upvote count: 2
has comment: http://stackoverflow.com/comment/112441631
score: 2

http://stackoverflow.com/comment/90233065
has text: For that individual: yes. For the community: not so much ;)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51633861
type: Comment

http://stackoverflow.com/q/51545685
tagged with: python
type: AnsweredQuestion
tagged with: sys
has title: Why do i need to explicitly import modules when they're already imported?
upvote count: 1
type: Question
score: 1
has answer: http://stackoverflow.com/a/51545766
has body: Whenever I run the command on Ubuntu Linux: python3 -v I get a verbose output which tells me: import _frozen_importlib # frozen import _imp # builtin import sys # builtin import '_warnings' # &lt;class '_frozen_importlib.BuiltinImporter'&gt; import '_thread' # &lt;class '_frozen_importlib.BuiltinImporter'&gt; import '_weakref' # &lt;class '_frozen_importlib.BuiltinImporter'&gt; import '_frozen_importlib_external' # &lt;class '_frozen_importlib.FrozenImporter'&gt; import '_io' # &lt;class '_frozen_importlib.BuiltinImporter'&gt; And much much more. However, I see that import sys was executed, yet I still need to manually import sys to use it. Why is this happening?
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51545766
has comment: http://stackoverflow.com/comment/90059088

http://stackoverflow.com/comment/90060955
comment on: http://stackoverflow.com/a/51546570
type: Comment
has text: Why compare just first elements, not entire lists?
score: 0
type: AnswerComment

http://stackoverflow.com/a/51511769
downvote count: 0
has comment: http://stackoverflow.com/comment/89998290
has body: You can't call your model within the loss function of Keras model, you can only use the input tensors y_true and y_pred. So the loss function cannot access intermediate layers. I had the same need and the tricky solution I found was to concatenate the output tensor with the intermediate layer as a new output of the model. It may be much simpler working directly with tensorflow though.
has comment: http://stackoverflow.com/comment/90048218
has comment: http://stackoverflow.com/comment/90096935
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90045565
has comment: http://stackoverflow.com/comment/90015967
upvote count: 2
answers question: http://stackoverflow.com/q/51508190
has comment: http://stackoverflow.com/comment/90082261

http://stackoverflow.com/comment/90178248
type: Comment
has text: "Alternation does not reset the group numbers". Thank you for a clear and concise explanation.
comment on: http://stackoverflow.com/a/51606314
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90140912
type: Comment
comment on: http://stackoverflow.com/a/51587327
has text: iam actually following this cool youtube tutorial. https://www.youtube.com/watch?v=2sRoLN337cs&index=2&list=PL8B63F2091D787896
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90201958
type: Comment
has text: I can't say you that, I'm not sure what the API does, so you know that the parameter are 2, one of them is mandatory, the parameter name is symbol and have to be a string (I suppose whatever you want), the second parameter is called limit is an integer and it's not mandatory, the default value if you don't configure it is 100 and the accepted values are 5, 10, 20, 50, 100, 500, 1000 but I can't say to you which of those values gave you that specific result, you should know what the API does, so read all the documentation
score: 0
comment on: http://stackoverflow.com/q/51617924
type: QuestionComment

http://stackoverflow.com/comment/89957187
has text: need `address = '^""$'`, in question you forget assign value to variable `address`
type: AnswerComment
comment on: http://stackoverflow.com/a/51493182
score: 0
type: Comment

http://stackoverflow.com/q/51639168
favorite count: 0
has body: I have just gotten a spanking new EPYC server, running Ubuntu 18.04, with 48 cores, and imagine my dismay when I found that using the python (3.6.6) multiprocessing module and then mapping a function over a list randomly drops list elements on the floor (meaning, my list, which is a list of dates and has length 234, sometimes returns a result of length 234, sometimes of length 176, sometimes of length 11...) The same code works fine under Ubuntu 16.04 and the exact same python version on a Xeon server. Is this a known problem? If so, is the OS or the CPU or the Python responsible?
type: UnansweredQuestion
tagged with: amd-processor
has comment: http://stackoverflow.com/comment/90242791
tagged with: python
has comment: http://stackoverflow.com/comment/90243103
score: 3
answer count: 0
upvote count: 3
type: Question
tagged with: multiprocessing
tagged with: ubuntu-18.04
has title: python 3.6.6 multiprocessing under ubuntu 18.04
has comment: http://stackoverflow.com/comment/136060928
downvote count: 0

http://stackoverflow.com/comment/90044944
comment on: http://stackoverflow.com/q/51537837
score: 0
type: Comment
has text: @rvinas I have included the reproducible code in my question. Could you please tell me what I've done wrong?
type: QuestionComment

http://stackoverflow.com/comment/90055968
score: 0
type: QuestionComment
type: Comment
has text: @FTHMitchell The edited python-2.x tag is not exactly correct, because I check in the beginning of script the python version and set raw_input = input if python-3.x
comment on: http://stackoverflow.com/q/51543478

svd
type: Tag
tags question: http://stackoverflow.com/q/51500114
tags question: http://stackoverflow.com/q/51482918
tag name: svd
tags question: http://stackoverflow.com/q/51498712

http://stackoverflow.com/q/51621579
has title: Parsing xml - join split xml files into 1 pandas dataframe by file name in same directory
has body: I have 4-10 xml files in a folder, these files are broken down from a large single xml file. Luckily parsing the xml was easy because I could use xmltodict package. So I can do whatever I need to already with a single xml file. I converted it into pandas dataframe for analysis requirement. However, I need to combine 4 xml files into one pandas dataframe. Assume there is no data/ index issue, the files are surely correctly named as 00001.xml, 00002.xml, 00003.xml, 00004.xml in order. import xmltodict import numpy as np import pandas as pd from collections import Counter with open('00001.xml') as fd: doc = xmltodict.parse(fd.read()) def panda_maker (xml_dict): channel_list = xml_dict ['logs']['log']['logData']['mnemonicList'].split(",") logData_list = [i.split(",") for i in xml_dict ['logs']['log']['logData']['data']] logData_list.insert(0, xml_dict ['logs']['log']['logData']['unitList'].split(",")) return pd.DataFrame(np.array(logData_list).reshape(len(logData_list),len(channel_list)), columns = channel_list) logData_frame_01 = panda_maker(doc) logData_frame_01.head() #all good How can I neatly combine logData_frame_01 + _02 + _03 + _04 to one dataframe? Any further abstractions tips in above program is also highly welcome.
type: Question
score: 0
tagged with: pandas
answer count: 1
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/51621764
accepted answer: http://stackoverflow.com/a/51621764
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90080858
score: 0
comment on: http://stackoverflow.com/q/51557076
type: Comment
type: QuestionComment
has text: You want to merge those lists?

http://stackoverflow.com/q/51540702
has title: Apply function returning a 1D array to all elements of numpy array
favorite count: 0
has comment: http://stackoverflow.com/comment/90052475
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90052524
has comment: http://stackoverflow.com/comment/90052403
has answer: http://stackoverflow.com/a/51544405
type: Question
tagged with: numpy
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/90052758
has body: Say I have an array of d dimensions, and I want to apply a function which returns a 1D array to each element, yielding a d+1-dimensional array. Very much as an embedding lookup works. For instance: def f(x): return np.array([x * i for i in range(6)]) m = np.random.randint(0,10, (2,3,4,5)) g = np.vectorize(f) h = np.vectorize(f, otypes=[np.ndarray]) I expect n=g(m) to have shape (2,3,4,5,6) just as if I had written 4 for loops, applying f to each element in m. However, g raises an error: ValueError: setting an array element with a sequence. and h returns an odd array ending like: ... [array([0, 9, 18, 27, 36, 45, 54, 63, 72]), array([0, 5, 10, 15, 20, 25, 30, 35, 40]), array([0, 7, 14, 21, 28, 35, 42, 49, 56]), ..., array([0, 1, 2, 3, 4, 5, 6, 7, 8]), array([0, 4, 8, 12, 16, 20, 24, 28, 32]), array([0, 3, 6, 9, 12, 15, 18, 21, 24])]]]], dtype=object) which I can't change to what I expect. I get @hpaulj's comment, I just can't find how to do otherwise.
accepted answer: http://stackoverflow.com/a/51544405
answer count: 1

http://stackoverflow.com/comment/90058040
type: Comment
comment on: http://stackoverflow.com/q/51544847
score: 1
has text: Try printing `dir(vf1)` to see if there's a method for modifying text boxes.
type: QuestionComment

http://stackoverflow.com/q/51516510
has comment: http://stackoverflow.com/comment/90001939
has title: Passing information between web pages in Django
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90001672
has answer: http://stackoverflow.com/a/51517015
has comment: http://stackoverflow.com/comment/90001816
has comment: http://stackoverflow.com/comment/90001902
has body: I have an Image Gallery System where I'm building a feature to edit the attributes of an uploaded image. @login_required def edit(request): if request.method == 'POST': ZSN = request.POST['ZSN'] ZSN = 'images/' + ZSN + '.' image = Images.objects.filter(file__startswith=ZSN) if image: return HttpResponseRedirect('/home/photo-edit', {'image':image}) else: return HttpResponse("Invalid ZSN.") else: return render(request, 'cms/edit.html') This is my edit method in views.py. Notice that I am getting the image object as the image whose attributes has to be edited. If the image is found then I'm redirecting to home/photo-edit where I want to display a HTML page containing a form with image attributes, pre-filled with existing attributes. My views.py method for home/photo-edit/ URL is @login_required def photoedit(request): return render(request, 'cms/photo-edit.html', {'image':image}) But image here isn't getting recognised even though I am sending it from home/edit to home/photo-edit. How do I do this? Is he syntax wrong?
favorite count: 0
has comment: http://stackoverflow.com/comment/90002016
has comment: http://stackoverflow.com/comment/90001728
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/90001854
has comment: http://stackoverflow.com/comment/90005274
score: 1
has comment: http://stackoverflow.com/comment/90001843
has comment: http://stackoverflow.com/comment/90001775
has comment: http://stackoverflow.com/comment/90004236
has comment: http://stackoverflow.com/comment/90004622
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: django-models
tagged with: django-forms
has comment: http://stackoverflow.com/comment/90002311
has comment: http://stackoverflow.com/comment/90003901
type: Question
has comment: http://stackoverflow.com/comment/90002106

keras
tags question: http://stackoverflow.com/q/51575433
tags question: http://stackoverflow.com/q/51577885
tags question: http://stackoverflow.com/q/51530901
tags question: http://stackoverflow.com/q/51484969
tags question: http://stackoverflow.com/q/51502983
tags question: http://stackoverflow.com/q/51625357
tags question: http://stackoverflow.com/q/51486073
tags question: http://stackoverflow.com/q/51544407
tags question: http://stackoverflow.com/q/51485573
tags question: http://stackoverflow.com/q/51559118
tags question: http://stackoverflow.com/q/51636337
tags question: http://stackoverflow.com/q/51588186
tags question: http://stackoverflow.com/q/51508190
tags question: http://stackoverflow.com/q/51504022
tags question: http://stackoverflow.com/q/51581139
tags question: http://stackoverflow.com/q/51544666
tags question: http://stackoverflow.com/q/51587279
tags question: http://stackoverflow.com/q/51524143
tags question: http://stackoverflow.com/q/51539926
tags question: http://stackoverflow.com/q/51531532
tags question: http://stackoverflow.com/q/51609981
tags question: http://stackoverflow.com/q/51507322
tags question: http://stackoverflow.com/q/51566573
tags question: http://stackoverflow.com/q/51638837
tags question: http://stackoverflow.com/q/51566229
tags question: http://stackoverflow.com/q/51502835
tags question: http://stackoverflow.com/q/51506691
tags question: http://stackoverflow.com/q/51494860
tags question: http://stackoverflow.com/q/51599931
tags question: http://stackoverflow.com/q/51536166
tags question: http://stackoverflow.com/q/51540068
tags question: http://stackoverflow.com/q/51615972
tags question: http://stackoverflow.com/q/51623191
tags question: http://stackoverflow.com/q/51548878
tags question: http://stackoverflow.com/q/51498199
tags question: http://stackoverflow.com/q/51628450
tags question: http://stackoverflow.com/q/51585339
tags question: http://stackoverflow.com/q/51543875
tags question: http://stackoverflow.com/q/51537837
tags question: http://stackoverflow.com/q/51522011
tags question: http://stackoverflow.com/q/51573864
tags question: http://stackoverflow.com/q/51511887
tags question: http://stackoverflow.com/q/51497370
tags question: http://stackoverflow.com/q/51560331
tags question: http://stackoverflow.com/q/51554242
tags question: http://stackoverflow.com/q/51618251
tags question: http://stackoverflow.com/q/51638053
tags question: http://stackoverflow.com/q/51503939
tags question: http://stackoverflow.com/q/51609643
tags question: http://stackoverflow.com/q/51632716
tags question: http://stackoverflow.com/q/51485084
tags question: http://stackoverflow.com/q/51626527
tags question: http://stackoverflow.com/q/51600250
tags question: http://stackoverflow.com/q/51503274
tags question: http://stackoverflow.com/q/51611512
tags question: http://stackoverflow.com/q/51489390
tags question: http://stackoverflow.com/q/51546602
tags question: http://stackoverflow.com/q/51492778
tags question: http://stackoverflow.com/q/51557940
tags question: http://stackoverflow.com/q/51549799
tags question: http://stackoverflow.com/q/51541385
tags question: http://stackoverflow.com/q/51496802
tags question: http://stackoverflow.com/q/51621798
tags question: http://stackoverflow.com/q/51578532
tags question: http://stackoverflow.com/q/51576642
tags question: http://stackoverflow.com/q/51636620
tags question: http://stackoverflow.com/q/51615888
tags question: http://stackoverflow.com/q/51506404
tags question: http://stackoverflow.com/q/51543011
tags question: http://stackoverflow.com/q/51573188
tags question: http://stackoverflow.com/q/51575306
tags question: http://stackoverflow.com/q/51586563
tags question: http://stackoverflow.com/q/51635187
tags question: http://stackoverflow.com/q/51572083
tags question: http://stackoverflow.com/q/51622364
tags question: http://stackoverflow.com/q/51581521
tags question: http://stackoverflow.com/q/51595618
tags question: http://stackoverflow.com/q/51524005
tags question: http://stackoverflow.com/q/51598437
tags question: http://stackoverflow.com/q/51602088

http://stackoverflow.com/comment/90038468
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51534296
score: 0
has text: @khelwood uhm no it says it uses python 3 :/

http://stackoverflow.com/q/51495939
has comment: http://stackoverflow.com/comment/89964067
type: Question
has comment: http://stackoverflow.com/comment/89965809
has title: How can I reuse this tensorflow layer ?
score: 0
has body: I'm writing a model in Tensorflow that I was used to use with PyTorch. Some mechanisms being very much different, I'm stuck at some points. In particular: dense = tf.layers.dense adam = tf.train.AdamOptimizer nb_joints= 3 code_size = 8 joints_info = tf.placeholder(tf.float32, shape = [None,nb_joints], name = 'joints_state') target_info = tf.placeholder(tf.float32, shape = [None,2], name = 'target_pos') next_joint_info = tf.placeholder(tf.float32, shape = [None,nb_joints], name = 'next_joints_state') with tf.variable_scope('Encoder'): e1 = dense(joints_info, 32, activation = tf.nn.relu, name ='encoding_1') code = dense(e1, code_size, activation = tf.nn.relu, name ='code') d1 = dense(code, code_size, activation = tf.nn.relu, name ='decoding_1') recon = dense(d1, code_size, activation = tf.nn.relu, name ='reconstructed') with tf.variable_scope('EncoderLoss'): encoder_loss = tf.squared_difference(joints_info, recon) train_encoder = adam(3e-4).minimize(encoder_loss) with tf.variable_scope('Task'): t1 = dense(code, 32, activation = tf.nn.relu, name ='task_code') t1_targ = dense(target_info, 32, activation = tf.nn.relu, name ='task_target') task_joint = tf.concat([t1,t1_targ],1, name ='States_concatenation') t2 = dense(task_joint, 128, activation = tf.nn.relu, name = 'task_joint_transformation') task_prediction = dense(t2, code_size, activation = None, name = 'task_prediction') with tf.variable_scope('TaskLoss'): task_real = here, I want to call the CODE operation from the encoder but using next_joint_info placeholder task_loss = tf.squared_difference(task_prediction, task_real) Could someone point me in the right direction ? I have no idea on how to proceed here. Thanks a lot !
tagged with: tensorflow
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90117180
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51571646
has text: does that mean, that without this command pandas would try to check for ever "row" if and if yes, than which datetime format is used in each row?
type: AnswerComment

http://stackoverflow.com/q/51617367
has answer: http://stackoverflow.com/a/51617439
has title: How to call data in batches from select statement and append into dataframe?
tagged with: python
favorite count: 0
tagged with: python-3.x
upvote count: 3
tagged with: pyodbc
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/51617439
has body: I have a file with a sql statement that I am reading into python using pyodbc. The sql statement is just a select statement like so: select distinct (columns) from table1 However the data I am calling is 30 million rows. I can do this for smaller tables, and put the information in a dataframe. Is there anyway to batch the select statement to pull only an X number of rows and append into a dataframe and keep doing this till the end of the 30million records? code so far: import os.path import pandas as pd import tinys3 import psycopg2 import pyodbc from datetime import datetime import uuid import glob from os import listdir from os.path import isfile, join import time startTime = datetime.now() #reading in data for db server = 'xxxx' database = 'xxx' username = 'xxx' password = 'xxxx' driver= '{ODBC Driver 17 for SQL Server}' cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=xxx;DATABASE='+database+';UID='+username+';PWD='+ password) cursor = cnxn.cursor() path = "path/to/folder" for infile in glob.glob( os.path.join(path, '*.sql') ): with open(infile, 'r') as myfile: sql = myfile.read() print(sql) myfile.close() cursor.execute(sql) row = cursor.fetchall() columns = [column[0] for column in cursor.description] columns = [element.lower() for element in columns] df = pd.DataFrame([tuple(t) for t in row]) df.columns = columns
type: Question
answer count: 1
downvote count: 0
tagged with: pandas

http://stackoverflow.com/comment/130532095
type: Comment
has text: Fill your series with missing dates then shift. Maybe. @gvo
comment on: http://stackoverflow.com/a/51487114
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90159670
has text: Like in this second runs where the 2 values presents are: `1532962720779231.5` and `1532962720779732.2`, separated by 500.75 us.
comment on: http://stackoverflow.com/a/51596533
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90009333
type: QuestionComment
has text: In your title you ask for a pythonci way but in the body, you want something on the shell level? Please clarifiy: Do you want to replace the `stdout.write()` with something that prints to a gzip file or do you want to redirect stdout?
type: Comment
comment on: http://stackoverflow.com/q/51520172
score: 2

http://stackoverflow.com/comment/90242805
type: QuestionComment
type: Comment
score: 7
has text: Count your parentheses!
comment on: http://stackoverflow.com/q/51639200

http://stackoverflow.com/comment/90050577
has text: Please provide a **[mcve]**.
score: 0
comment on: http://stackoverflow.com/q/51541422
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51534069
upvote count: 2
tagged with: mysql
has title: Calculate results between columns according different parameters in sql, r or python
type: Question
has body: Hi All I have this problem, I'm looking to calculate the days between Dates, with the following premises: Status A is the base date, all the calculations have to take this date as a reference (group by ID) I must take the older date for status B, C, D I must calcule the days and showing in different columns Ex. generate the table with R ColID = c(1, 1, 1, 1, 1, 2, 2, 2) ColStatus = c("A", "B", "B", "C", "D", "A", "C", "C") ColDate = c("01/01/2018","02/03/2018", "05/04/2018", "04/05/2018", "04/05/2018", "02/01/2018", "04/03/2018", "05/04/2018") data.frame(ColID, ColStatus, ColDate) How I proceed with the calculation For ColID = 1 Status A = 01/01/2018 Status B (I Have to select the older one) = 02/03/2018 Status C = 04/05/2018 Status D = 04/05/2018 ResultColB = 02/03/2018 - 01/01/2018 = 60 ResultColC = 04/05/2018 - 01/01/2018 = 123 ResultColD = 04/05/2018 - 01/01/2018 = 123 Result table (in days) generate the table with R ColID = c(1,2) ResultColStatusB = c(60,0) ResultColStatusC = c(123,61) data.frame(ColID, ResultColStatusB, ResultColStatusC, ResultColStatusB) The problem can be solved in R, Python or SQL, what recommend me to solve this problem?
possible better answer: http://stackoverflow.com/a/51534491
has answer: http://stackoverflow.com/a/51534491
accepted answer: http://stackoverflow.com/a/51534592
answer count: 2
score: 2
tagged with: sql
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51534592

http://stackoverflow.com/q/51493828
tagged with: google-analytics
has body: I'm just getting my head around the Google Analytics Reporting API with python and have been trying to get their demo file to work and pull out some data, the full sample code can be found here - https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py All I have done is simply copied the code and replaced the Key File Location and View ID as instructed within the tutorial, however, I keep getting the error message = "File "HelloAnalytics.py", Line 67 print 'Date range: ' + str(i) SyntaxError: invalid syntax I was wondering if someone could help me out as my python knowledge is currently very limited. My code can be found below... """Hello Analytics Reporting API V4.""" from apiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] KEY_FILE_LOCATION = 'test-developments-maps-a9eb7ab2d2cf' VIEW_ID = '151121821' def initialize_analyticsreporting(): """Initializes an Analytics Reporting API V4 service object. Returns: An authorized Analytics Reporting API V4 service object. """ credentials = ServiceAccountCredentials.from_json_keyfile_name( KEY_FILE_LOCATION, SCOPES) # Build the service object. analytics = build('analyticsreporting', 'v4', credentials=credentials) return analytics def get_report(analytics): """Queries the Analytics Reporting API V4. Args: analytics: An authorized Analytics Reporting API V4 service object. Returns: The Analytics Reporting API V4 response. """ return analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}], 'metrics': [{'expression': 'ga:sessions'}], 'dimensions': [{'name': 'ga:country'}] }] } ).execute() def print_response(response): """Parses and prints the Analytics Reporting API V4 response. Args: response: An Analytics Reporting API V4 response. """ for report in response.get('reports', []): columnHeader = report.g…
has comment: http://stackoverflow.com/comment/89956942
downvote count: 0
has comment: http://stackoverflow.com/comment/89956305
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Google Reporting API V4 Issue
answer count: 0
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/90106602
type: QuestionComment
has text: Well, as I did not work with this library, all I can suggest is to place breakpoint into `get_queryset` method and inspect stacktrace. Somewhere in the stacktrace there will be a request and you can see how is it going to `ModelResource`
comment on: http://stackoverflow.com/q/51570074
score: 0
type: Comment

http://stackoverflow.com/q/51556728
type: Question
has comment: http://stackoverflow.com/comment/90082014
duplicate of: http://stackoverflow.com/q/7828867
has comment: http://stackoverflow.com/comment/90081264
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51557085
answer count: 3
has comment: http://stackoverflow.com/comment/90082139
has comment: http://stackoverflow.com/comment/90081134
has comment: http://stackoverflow.com/comment/90080051
has comment: http://stackoverflow.com/comment/90082837
has comment: http://stackoverflow.com/comment/90081232
has comment: http://stackoverflow.com/comment/90081324
has answer: http://stackoverflow.com/a/51556918
has answer: http://stackoverflow.com/a/51556807
has comment: http://stackoverflow.com/comment/90080394
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90082810
tagged with: python
has comment: http://stackoverflow.com/comment/90081228
has comment: http://stackoverflow.com/comment/90090778
has title: Compare list within dictionary in Python
linked to: http://stackoverflow.com/q/7828867
has comment: http://stackoverflow.com/comment/90081160
score: 0
has comment: http://stackoverflow.com/comment/90080111
has comment: http://stackoverflow.com/comment/90080972
has comment: http://stackoverflow.com/comment/90080993
has body: I have two dictionaries with a list in the value part. Something like this dict1 = {red:[1,2,3], blue:[7,6,9], green:[3,9,3,1]} dict2 = {red:[2,1,3], blue:[9,7,6], green:[3,9,1,3]} In this case, the comparison must give a True as in both the dictionaries contains the same values in the list for a given key. I come up with a solution in which I access the list values using the key. Then check if the length of the lists are same and each value in one list present in the other list. I think there is some other way to do this in python. What is the best "pythonic" way to do this?

http://stackoverflow.com/comment/90166210
has text: Could you share your `__init__` method? How are you storing the values? You probably don't want a [`__next__`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__) method, as those are part of the iterator protocol, not the iterable protocol
comment on: http://stackoverflow.com/q/51599979
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51596722
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51596798
has comment: http://stackoverflow.com/comment/90159506
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: How to know if an exception has occured in a Parent class method while overriding the same method in the child class ? class Customer: def withdraw(self, amount): if self.__account_balance &lt; self.get_min_balance: raise LimitException() class PrivCustomer(Customer): def withdraw(self, amount): """ here how do I detect if an exception has occurred in the withdraw method of Customer class ?""""
has comment: http://stackoverflow.com/comment/90159452
score: 1
type: Question
has title: Detecting Exceptions in Parent class
answer count: 1
downvote count: 0

http://stackoverflow.com/a/52223502
has comment: http://stackoverflow.com/comment/95204019
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91832908
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/91837901
accepted answer of: http://stackoverflow.com/q/51605277
score: 3
has body: A few things to check. Presumably you're using the swift / tensorflow toolchain from latest download link here (and you've configured Xcode to use it. View Xcode’s (Preferences, Components > Toolchains, and select the installed Swift for TensorFlow toolchain.) https://github.com/tensorflow/swift/blob/master/Installation.md Make sure you change the Xcode build system to legacy (File > Project Settings > Build System). Check the runtime search path /Library/Developer/Toolchains/swift-latest/usr/lib/swift/macosx UPDATE: Have a look at XcodeGen which can automagically create an xcode project with relevant settings for swift for tensorflow. I crafted a project.yml file here DO NOT include libppython2.7.tbd in the linked frameworks. tensorflow will automagically find relevant python version 3 or 2.
answers question: http://stackoverflow.com/q/51605277

http://stackoverflow.com/q/51506916
tagged with: python
score: 2
upvote count: 2
has body: I have a Profile class which is a OneToOne with Location model. Every profile has one and only location. class Location(models.Model): profile = models.OneToOne(Profile) point = PointField() In one of my views, I display a list of profiles. For example, I first find profiles with locations and then find associated profiles. ref_location = Point(0,0) # point to calculate distances from locations = Location.objects.filter(point__distance_lte=(ref_location, D(m=50 * 1000))) \ profiles = Profile.objects.filter(pk__in=locations.values('profile_id')) What I would want is to be able to know the distance to each of these profile instances, e.g. I want to do something like: profiles = Profile.objects.filter(pk__in=locations.values('profile_id'))\ .annotate(distance=Distance('location__point', ref_location)) and then iterate over for p in profiles: print(p.distance.km) Which is not possible What I can do is annotate the locations instead, which isn't much use, because in the template I loop over profiles, not locations
tagged with: django
type: Question
accepted answer: http://stackoverflow.com/a/51515229
type: AnsweredQuestion
tagged with: geodjango
has title: GeoDjango Distance() Annotation on Related Model
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51515229

http://stackoverflow.com/comment/90013098
score: 0
comment on: http://stackoverflow.com/q/51521879
type: QuestionComment
type: Comment
has text: Please show the full traceback. Which query is causing the error? (And please, tidy up your code before posting; there's no reason to include all those commented-out lines.)

http://stackoverflow.com/comment/89943558
type: AnswerComment
type: Comment
has text: I don´t know how your data looks like. Seems like you have 69 y values?
comment on: http://stackoverflow.com/a/51485308
score: 0

http://stackoverflow.com/q/51609461
score: 0
has comment: http://stackoverflow.com/comment/90183797
answer count: 3
has answer: http://stackoverflow.com/a/51609547
has answer: http://stackoverflow.com/a/51610028
has comment: http://stackoverflow.com/comment/90183867
type: UnansweredQuestion
tagged with: python
tagged with: delimiter
tagged with: text
has answer: http://stackoverflow.com/a/51609795
has body: trying to replace comma between 2 words Durango and PC in the second line by &amp; and then remove the quotes " as well. Same for third line with Orbis and PC I would like to retain the rest of the lines using Python: 2,SIN-Rendering,Core Tech - Rendering,PC,147,Reopened 2,Kenny Chong,Core Tech - Rendering,"Durango, PC",55,Reopened 3,SIN-Audio,AAA - Audio,"Orbis, PC",13,Open ... ... ... Like these, there can be 100 lines in my sample. So the expected output is: 2,SIN-Rendering,Core Tech - Rendering,PC,147,Reopened 2,Kenny Chong,Core Tech - Rendering, Durango &amp; PC,55,Reopened 3,SIN-Audio,AAA - Audio, Orbis &amp; PC,13,Open ... ... ... So far, I could think of reading line by line and then if the line contains quote replace it with no character but then replacement of symbol inside is something I am stuck with. How to achieve this, any suggestion? Learning Python.
type: Question
tagged with: processor
linked to: http://stackoverflow.com/q/51626343
has comment: http://stackoverflow.com/comment/90184012
has comment: http://stackoverflow.com/comment/90183805
has comment: http://stackoverflow.com/comment/90217473
has title: Python to replace a symbol between between 2 words in a quote

http://stackoverflow.com/q/51508549
favorite count: 0
has answer: http://stackoverflow.com/a/51520646
tagged with: eve
has comment: http://stackoverflow.com/comment/89990631
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: python-requests
has body: I just bumped into somewhat strange behavior while doing my RESTful Eve project For this step i have to add some data to eve's db. I wanted to use python's requests module to make a POST with data I have to save Here is what I'm sending (author is a variable that contains some data): data = {"author_id": author.author_id, "orcid": author.orcid, "hindex": author.hindex, "ndocuments": author.hindex, "ncited_by": author.ncited_by, "citation_count": author.citation_count, "current_affiliation": author.affiliation_history[0].affiliation_id, "affiliation_history": [x.affiliation_id for x in author.affiliation_history], "subject_areas": [{"name": x[0], "frequency": x[1]} for x in author.subject_areas], "publication_history": [{"title": x[0], "issn": x[3]} for x in author.publication_history], "firstname": author.firstname, "lastname": author.lastname} r = requests.post('http://localhost:5000/professors', data=data) return r.status_code Which returns 422. I have printed to console what data contains before sending and looks like this { "author_id":"57190708172", "orcid":"", "hindex":"1", "ndocuments":"1", "ncited_by":"18", "citation_count":"18", "current_affiliation":"104571568", "affiliation_history":[ "104571568", "60022084", "116039394", "100252088" ], "subject_areas":[ { "name":"Biomaterials", "frequency":"4" }, { "name":"Biomedical Engineering", "frequency":"4" } ], "publication_history":[ { "title":"Czechoslovak Medicine", "issn":"01399179" }, { "title":"Ceskoslovenska Patologie", "issn":"00090611" } ], "firstname":"Albert Vlastimil", "lastname":"V\u00e1lek" } It looks fine and has all data from author. Now here is the problem which I cannot understand. Sending the request with requests.post(...) always fails with code 422 - Unprocessable Entity BUT coping the output from above and sending it with a REST client works perfectly (code 201 - Created) Here is also a video https://drive.google.com/open?id=1SwslPKMv0hn1CN8rDnOk7YrTjpr-4OZO
has answer: http://stackoverflow.com/a/51519999
score: 1
has comment: http://stackoverflow.com/comment/89987672
has title: Python + Requests + Eve : Sending data to post fails with error code 422
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/q/51566465
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/90100875
has answer: http://stackoverflow.com/a/51567738
score: -2
has comment: http://stackoverflow.com/comment/90099810
type: Question
has title: Running Python Code from Website via PHP - but how to disable button after it is puhed
upvote count: 0
answer count: 1
tagged with: button
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/90100097
tagged with: python
tagged with: php
has body: Help with the following &lt;?php if(isset($_POST['MEASURE'])) { shell_exec("sudo python /var/www/html/lab/mkdir.py"); } ?&gt; HTML PART &lt;form method="post" &gt; &lt;input type="submit" value="Start Measuring" name="MEASURE" class="search"&gt; &lt;/form&gt; I try to use a HTML page with a button to execute a Python script via PHP -> this works... However when I try to disable the button once clicked to avoid multiple starts of the Python script using "onClick="disableButton();" or similar the script will not be executed anymore....

http://stackoverflow.com/comment/90170458
has text: That was quick... nice
comment on: http://stackoverflow.com/a/51602192
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90257511
type: Comment
has text: Thanks, this is exactly what I need. This code is awesome. Just to understand the code, let me recap what is happening. I will do this in another answer. It would be great if you can agree/disagree on my explanantion and update it, if it is missing a detail.
type: AnswerComment
comment on: http://stackoverflow.com/a/51636301
score: 0

sensors
type: Tag
tags question: http://stackoverflow.com/q/51604748
tags question: http://stackoverflow.com/q/51577694
tag name: sensors
tags question: http://stackoverflow.com/q/51606283
tags question: http://stackoverflow.com/q/51568203

http://stackoverflow.com/a/62447964
type: Answer
accepted answer of: http://stackoverflow.com/q/51600696
answers question: http://stackoverflow.com/q/51600696
type: AcceptedAnswer
has body: I encountered the same issue with Tensorflow 2.1.1. Adadelta optimizer seems to have no support on GPU nor TPU.
score: 0

http://stackoverflow.com/q/51604235
answer count: 2
has comment: http://stackoverflow.com/comment/90174334
tagged with: function
has comment: http://stackoverflow.com/comment/90174838
possible better answer: http://stackoverflow.com/a/51604519
has answer: http://stackoverflow.com/a/51604519
has answer: http://stackoverflow.com/a/51604246
accepted answer: http://stackoverflow.com/a/51604246
favorite count: 0
linked to: http://stackoverflow.com/q/19326004
has comment: http://stackoverflow.com/comment/90174386
linked to: http://stackoverflow.com/q/7664779
tagged with: python
tagged with: method-call
downvote count: 4
duplicate of: http://stackoverflow.com/q/3052793
type: AnsweredQuestion
tagged with: python-3.x
linked to: http://stackoverflow.com/q/9059349
upvote count: 0
tagged with: return
score: -4
has body: If I had a function that I made: def a(): n = 2*2 How could I access n out of the function without calling a?
type: Question
has title: Using a variable outside of a defined function
linked to: http://stackoverflow.com/q/3052793

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/51525364
tags question: http://stackoverflow.com/q/51621613
tags question: http://stackoverflow.com/q/51581654
tags question: http://stackoverflow.com/q/51563435
tags question: http://stackoverflow.com/q/51592488
tags question: http://stackoverflow.com/q/51563202
tags question: http://stackoverflow.com/q/51501541
tags question: http://stackoverflow.com/q/51594431
tags question: http://stackoverflow.com/q/51602661
tags question: http://stackoverflow.com/q/51548416
type: Tag

http://stackoverflow.com/a/51530521
answers question: http://stackoverflow.com/q/51530216
has body: This question is a bit ambiguous. If you're asking for the simple attributes for instances of simple classes, this is exactly what the vars builtin is for: def get_dict(self): return vars(self) While we're at it, it's pretty weird to call a parameter self when you're not writing a method; let's call it something different: def get_dict(obj): return vars(obj) But there are a lot of things this won't pick up, including: Properties. Any attributes of a __slots__ class. Class attributes. Dynamic attributes from __getattr__/__getattribute__ and __dir__. If you want as many of those as possible, that's what the dir builtin is for. But dir just returns a list of names; you then have to look each one up: def get_dict(obj): return {name: getattr(obj, name) for name in dir(obj)} This is pretty close to "every whatever I could do an obj.whatever with". But that's probably more than you want. It'll include private members, and bound methods, and special stuff used by the Python interpreter. You have to decide exactly what you want to filter out, but once you have a rule, it should be easy to implement. For example: def get_dict(obj): public = ((name, getattr(obj, name)) for name in dir(obj) if not name.startswith('_')) noncallablepublic = {name: value for name, value in everything if not callable(value)} return noncallablepublic If you want to get fancier, look at the inspect module, which has helper functions for this kind of filtering. While we're at it, if you have a good reason for doing this on some particular set of classes, you might want to design those classes to be easier to convert to a dict—and to be able to customize how they're converted. For example, if you build your classes with @dataclass—or with the third-party attrs library, which is more powerful and doesn't require Python 3.7—it's trivial: &gt;&gt;&gt; @dataclasses.dataclass ... class A: ... b: int = 1 ... c: int = 2 &gt;&gt;&gt; a = A() &gt;&gt;&gt; a A(b=1, c=2) &gt;&gt;&gt; print(dataclasses.asdict(a)) …
type: Answer
score: 0

http://stackoverflow.com/comment/90027580
comment on: http://stackoverflow.com/a/51528060
type: Comment
score: 0
has text: Because my macbook pro touchbar uses i7-6700hq.. This is for mobile processor. Slow more than my 3-years desktop pc which i5-6600.
type: AnswerComment

http://stackoverflow.com/comment/90087047
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51559204
has text: @trollster, starting with a few thousand and going upto 4 million records got processed under a minute. But going to 5 million records, system is again running for long. Thats where is seemingly the break point.

http://stackoverflow.com/q/51587602
has answer: http://stackoverflow.com/a/55448367
type: Question
has body: I'm using python shell to run python on nodeJS. I need to return python shell out put as the response. but when i try to send the response it shows an error Can't set headers after they are sent. here is my code app.post('/therun', (req, res)=&gt;{ var pyshell = new PythonShell('hello.py'); pyshell.on('message', function (message) { console.log(message); //value is correct res.send(message); //error here }); res.send(message); //if i use here message undefined }); How to slove this?
tagged with: flask
score: 0
answer count: 3
tagged with: angular
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51587836
tagged with: python
has answer: http://stackoverflow.com/a/51588294
has title: return value from python-shell as response
tagged with: node.js
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/90213625
has text: You've only solved half the problem - `unicode_literals` allows you to put Unicode characters into your program. The error is now generated by `print` itself because the encoding for output is set to `ascii`.
comment on: http://stackoverflow.com/q/51623871
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51633439
has comment: http://stackoverflow.com/comment/90317994
has comment: http://stackoverflow.com/comment/90317939
has comment: http://stackoverflow.com/comment/104447709
type: Answer
has comment: http://stackoverflow.com/comment/90339415
has body: The activatoin 'relu' should not be used as the model's output. (This seed will probably make the sequential model stuck as well, but without a seed, you may get lucky/unlucky with any of the models). This activation has a zero zone that has zero gradients. If your model reaches this zone (and this is specially probable when you have a single neuron) it will completely stop backpropagation. If your model is intended to output between 0 and 1, use Activation('sigmoid'). If it's intended to ouput from 0 to infinity, try the Activation('softplus'). If it's intended to output from 0 to C, use Lambda(lambda x: C*K.sigmoid(x))
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/90316017
answers question: http://stackoverflow.com/q/51627825
upvote count: 3

docblocks
tag name: docblocks
tags question: http://stackoverflow.com/q/51619769
type: Tag

http://stackoverflow.com/comment/90033488
type: QuestionComment
comment on: http://stackoverflow.com/q/51532832
score: 0
has text: Seems like it is in iframe. can you share little bit more HTML around this `textarea`
type: Comment

http://stackoverflow.com/a/70407466
score: 2
answers question: http://stackoverflow.com/q/51560196
upvote count: 2
has body: Bit late but I was looking for this too and found out that you can use self.QTextEdit.textCursor().position() to get an integer of the cursor position.
downvote count: 0
has comment: http://stackoverflow.com/comment/124491133
type: Answer

http://stackoverflow.com/comment/89945897
comment on: http://stackoverflow.com/q/51488313
type: Comment
has text: @ChrisI have adjusted it
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89976872
score: 0
type: Comment
type: QuestionComment
has text: Final thought: pretty sure these are all built in. Just type `import os` or `import sys` or whatever in your Python shell or at the top of your file and start using them.
comment on: http://stackoverflow.com/q/51503974

http://stackoverflow.com/q/51529879
favorite count: 0
has answer: http://stackoverflow.com/a/54745680
tagged with: python
score: 4
type: UnansweredQuestion
has body: I am beginner of the VisPy. All I want to do is: Click the point then this point will change color and print the position (x,y,z) of this point. But I can't find how to do this. Here is my code. import numpy as np import sys from vispy import app, visuals, scene class Canvas(scene.SceneCanvas): """ A simple test canvas for testing the EditLineVisual """ def __init__(self): scene.SceneCanvas.__init__(self, keys='interactive', size=(800, 800), show=True) # # Create some initial points self.unfreeze() # Add a ViewBox to let the user zoom/rotate self.view = self.central_widget.add_view() self.view.camera = 'turntable' self.view.camera.fov = 30 self.show() self.selected_point = None scene.visuals.GridLines(parent=self.view.scene) self.freeze() def on_mouse_press(self, event): print(event.pos) # How to convert this pos to canvas position?? Scatter3D = scene.visuals.create_visual_node(visuals.MarkersVisual) canvas = Canvas() p1 = Scatter3D(parent=canvas.view.scene) p1.set_gl_state('translucent', blend=True, depth_test=True) # fake data x = np.random.rand(100) * 10 y = np.random.rand(100) * 10 z = np.random.rand(100) * 10 # Draw it point_list = [x, y, z] point = np.array(point_list).transpose() p1.set_data(point, symbol='o', size=6, edge_width=0.5, edge_color='blue') if __name__ == "__main__": if sys.flags.interactive != 1: app.run()
has title: How to get the position of the point in Vispy 3d plot?
tagged with: vispy
type: Question
upvote count: 4
tagged with: 3d
answer count: 1
downvote count: 0
tagged with: scatter

http://stackoverflow.com/comment/90135686
type: QuestionComment
has text: If you can't use the builtin tools for this, you have to write them yourself. You could do this just by looping `for ch in orig_string:` and adding each `ch` to the start of a `new_string` instead of to the end. (If you want it to be more efficient, build a list, or, better, a `collections.deque` and `''.join` it, but your teacher probably isn't expecting that from you.)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51584994

http://stackoverflow.com/comment/90232915
score: 1
has text: You need to read about, understand and start using parameterized queries before bobby tables comes to visit. http://bobby-tables.com/ Your code is wide open to sql injection.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51633117

http://stackoverflow.com/comment/89982515
type: AnswerComment
comment on: http://stackoverflow.com/a/51505881
score: 0
type: Comment
has text: You can create new functions with `exec('''def f_new(x, y):return f([x, y])''')`, but the use of `exec` is strongly discouraged.

http://stackoverflow.com/q/51585444
favorite count: 0
has comment: http://stackoverflow.com/comment/90136804
has body: I am trying to extract tables from a multi-page PDF with tabula-py, and while the tables on some of the pages of the PDF are extracted perfectly, some pages are omitted entirely. The omissions seem to be random and don't follow any visible visual features on the PDF (as each page looks the same), and so tabula omitted page 1, extracted page 2, omitted pages 3 and 4, extracted page 5, omitted page 6, extracted pages 8 and 9, omitted 10, extracted 11, etc. I have macOS Sierra 10.12.6 and Python 3.6.3 :: Anaconda custom (64-bit). I've tried splitting the PDF into shorter sections, even into one-pagers, but the pages that are omitted don't seem to be possible to extract no matter what I've tried. I've read the related documentation and filed issues on the Tabula-py GitHub page as well as here on Stack Overflow, but I don't seem to find a solution. The code I use through iPython notebooks is as follows: To install tabula through the terminal: pip install tabula-py To extract the tables in my PDF: from tabula import read_pdf df = read_pdf("document_name.pdf", pages="all") I also tried the following, which didn't make any difference df = read_pdf("document_name", pages="1-361") To save the data frame into csv: df.to_csv('document_name.csv') I'd be really thankful if you could help me with this, as I feel like I'm stuck with a PDF from which I've only managed to extract around 50% of data. This is infuriating, as the 50% looks absolutely perfect, but the other 50% seems out of my reach and renders the larger project of analyzing the data impossible. I also wonder if this might be an issue of the PDF rather than Tabula - could the file be mistakenly set as protected or locked and whether any of you knows how I could check for that and open it up? Thanks a ton in advance!
has comment: http://stackoverflow.com/comment/90148002
has answer: http://stackoverflow.com/a/60885490
score: 3
tagged with: http://stackoverflow.com/tag/pdf
has title: Tabula-py omitting pages from a PDF document I am trying to extract
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90136523
tagged with: python
tagged with: pdf-extraction
tagged with: tabula
has comment: http://stackoverflow.com/comment/90141356
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51740642

http://stackoverflow.com/q/51618985
tagged with: python
has answer: http://stackoverflow.com/a/51619029
linked to: http://stackoverflow.com/q/20528328
score: -1
has answer: http://stackoverflow.com/a/51619412
has title: How to filter a Pandas DataFrame using multiple conditions?
downvote count: 2
upvote count: 1
has body: i have a data frame object as below Issue Type Status Reporter Issue id 0 Eng Activity Closed snalanag 98908 1 Eng Activity In Progress snalanag 98452 2 Eng Activity Closed snalanag 98425 3 Dev-Defect Closed snalanag 97244 4 Dev-Defect Closed snalanag 96716 5 Eng Activity Closed snalanag 96698 6 Dev-Defect Closed snalanag 96696 Now i want to filter data based on multiple conditions. Condition will be in dictionary. Example:{'Issue Type': 'Dev-Defect', 'Status': 'Closed', 'Reporter': 'snalanag'} Based on the condition, i have to filter the data frame by forming the query dynamically. Please note that i need to filter the data by applying AND condition . That means i have to apply the filter for the given data frame with "Issue Type = Dev-Defect","Status = Closed","Reporter = snalanag" at once. Something like this but it should be generated dynamically based on the condition dictionary. print (df[(df["Issue key"] == 'BUG-22212') &amp; (df["Issue id"] == 97244) &amp; (df["Status"] == 'Closed')])
accepted answer: http://stackoverflow.com/a/51619412
tagged with: pandas
has comment: http://stackoverflow.com/comment/90203866
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90203964
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/51619029
answer count: 2

http://stackoverflow.com/comment/89942913
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/51486897
type: Comment
has text: If you use head instead of tail you can drop the ascending=False.

http://stackoverflow.com/q/51483722
has answer: http://stackoverflow.com/a/51484237
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51483871
has answer: http://stackoverflow.com/a/51483893
downvote count: 0
score: 1
has body: I have a df that looks like this: ID Component IDDate EmployeeID CreateUserID 24 1 2017-09-11 00:00:00.000 0907036 Afior 24 2 2017-09-11 00:00:00.000 0907036 Afior 24 3 2017-09-11 00:00:00.000 0907036 Afior 25 1 2017-09-12 00:00:00.000 0907036 Afior 25 3 2017-09-12 00:00:00.000 0907036 Afior 26 8 2017-09-16 00:00:00.000 1013842 JHyde 26 11 2017-09-16 00:00:00.000 1013842 JHyde 26 12 2017-09-16 00:00:00.000 1013842 JHyde 26 23 2017-09-16 00:00:00.000 1013842 JHyde 27 21 2017-09-16 00:00:00.000 0907036 Afior 27 22 2017-09-16 00:00:00.000 0907036 Afior 27 23 2017-09-16 00:00:00.000 0907036 Afior 28 15 2017-10-16 00:00:00.000 1013842 JHyde 28 16 2017-10-16 00:00:00.000 1013842 JHyde 28 19 2017-10-16 00:00:00.000 1013842 JHyde 28 25 2017-10-16 00:00:00.000 1013842 JHyde 28 26 2017-10-16 00:00:00.000 1013842 JHyde I'm trying to use cumcount to create a variable that holds the order of observations for each ID/EmployeeID combo. I haven't been able to get the count to apply at the level I want, but have tried variations on cumcount() that aren't getting me quite to where I want to be, like: df['seq'] = df.groupby(['EmployeeID', 'ID', 'Date']).cumcount().add(1) df['seq'] = df.groupby(['EmployeeID', 'Date']).cumcount().add(1) df['seq'] = df.groupby(['EmployeeID', 'ID']).cumcount().add(1) Ideally, my output looks like this: ID Component IDDate EmployeeID CreateUserID seq 24 1 2017-09-11 00:00:00.000 0907036 Afior 1 24 2 2017-09-11 00:00:00.000 0907036 Afior 1 24 3 2017-09-11 00:00:00.000 0907036 Afior 1 25 1 2017-09-12 00:00:00.000 0907036 Afior 2 25 3 2017-09-12 00:00:00.000 0907036 Afior 2 26 8 2017-09-16 00:00:00.000 1013842 JHyde 1 26 11 2017-09-16 00:00:00.000 1013842 JHyde 1 26 12 2017-09-16 00:00:00.000 1013842 JHyde 1 26 23 2017-09-16 00:00:00.000 1013842 JHyde 1 27 21 2017-09-16 00:00:00.000 0907036 Afior 3 27 22 2017-09-16 00:00:00.000 0907036 Afior 3 27 23 2017-09-16 00:00:00.000 0907036 Afior 3 28 15 2017-10-16 00:00:00.000 1013842 JHyde 2 28 16 2017-10-16 00:00:00…
type: Question
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
upvote count: 1
tagged with: python
has title: Using cumcount() with dups
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/51490765
accepted answer of: http://stackoverflow.com/q/51490114
answers question: http://stackoverflow.com/q/51490114
type: Answer
has comment: http://stackoverflow.com/comment/89951808
score: 2
downvote count: 0
has body: The company name you can scrap from the "https://finance.yahoo.com/quote/{ticker}" URL, but however all other data (like volumes and prices) is loaded through Ajax from "https://query1.finance.yahoo.com". This example will load company name and close price: import requests from bs4 import BeautifulSoup import json from pprint import pprint tickers = ['BABA', 'AAPL'] stockname = [] for ticker in tickers: stock_company = f"https://finance.yahoo.com/quote/{ticker}" soup = BeautifulSoup(requests.get(stock_company).text, "html.parser") name = soup.h1.text.split('-')[1].strip() ticker_data_url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker}?region=US&amp;lang=en-US&amp;includePrePost=false&amp;interval=2m&amp;range=1d&amp;corsDomain=finance.yahoo.com&amp;.tsrc=finance" ticker_data = json.loads(requests.get(ticker_data_url).text) price = ticker_data['chart']['result'][0]['meta']['previousClose'] if name: stockname.append( [ticker, name, price] ) pprint(stockname, width=60) Will print: [['BABA', 'Alibaba Group Holding Limited', 187.25], ['AAPL', 'Apple Inc.', 191.44]] Apple has ticker AAPL, not APPL.
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/51617995
has comment: http://stackoverflow.com/comment/90201920
score: 0
has body: I write a custom OP for TF (with c++ and a cuda kernel) that runs on GPU. A toy identity-OP runs fine, it relies on tf::Tensor inputs and outputs, and then simply copies elements from input tensors to output ones. However when I try to pass int inputs (a single int number) I get a segmentation fault. In the REGISTER_OP declaration I use `.Input( "image_size: int32" )` and then in void Compute(OpKernelContext* context) override { I try to read this int argument, first as a tf::Tensor and then to convert to int. const Tensor&amp; inn_image_size_T = context-&gt;input(0); auto inn_image_size_Tflat = inn_image_size_T.flat&lt;int&gt;(); int inn_image_size = inn_image_size_Tflat(0); This is in compliance with samples I find online, e.g. this one (relevant lines: 46, 70). The Op has been checked and runs normally on the GPU without the last line (int inn_image_size = inn_image_size_Tflat(0);), and for the tensor arguments indeed inputs are copied to outputs. However for the int arguments, when I try to convert from an int-Tensor to int, things compile but when I run I get a segmentation fault. Any hint why this happens? ========================================================= ======================================= Updates: ========================================================= I also print for sanity check inn_image_size_T.NumElements() and inn_image_size_T.size() and the result is 1 as expected, since I pass just a single number. So the information seems to be there, but reading it is unexpectedly problematic.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90202014
answer count: 0
tagged with: tensorflow
has title: TF custom OP on GPU - Tensor inputs work fine, int inputs fail
type: Question
tagged with: operator-overloading
tagged with: casting
has comment: http://stackoverflow.com/comment/90202607

http://stackoverflow.com/comment/90104919
type: AnswerComment
has text: You have used this code `driver.find_elements_by_css_selector("#mceu_108 > button:nth-child(1)").click()` , when you use `find_elements` then you will have list of web element and invoking click on list is not applicable.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51561049

http://stackoverflow.com/comment/89974004
has text: @RohanSingh: ok, creating a global variable is the same, whether in a function or a method
comment on: http://stackoverflow.com/a/51502562
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90073448
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51553003
has text: maybe ` if re.match('MY RULES', line) is not None:` this is not letting it pass to the line with adds `x` as `msg`
score: 0

http://stackoverflow.com/q/51626088
type: UnansweredQuestion
tagged with: python
has title: BeautifulSoup get_text only i want
has answer: http://stackoverflow.com/a/51626800
type: Question
score: 0
answer count: 2
tagged with: beautifulsoup
has body: 판타지 , 드라마 | 141분 | 2018.08.01 개봉 **strong text** how can i get only 141분(text) in < dd > tags another text, i use find_all("tag", class_="name") but, this < dd > 141분(text) don't have class 'get_text' result is 판타지, 드라마, 141분, 2018.08.01 개봉 i want only 141분(text)
has answer: http://stackoverflow.com/a/51626569

http://stackoverflow.com/q/51583544
answer count: 4
score: 2
type: AnsweredQuestion
has body: I have a pandas data frame and am looking to remove everything before and the last \ so that all that is left is the executable. This is what I would like to achieve: C:\Windows\System32\services.exe to just services.exe Parent Child PID PID System_Or_User 0 C:\Windows\System32\services.exe C:\Windows\System32\svchost.exe 10396 752 System 1 C:\Windows\System32\services.exe C:\Windows\System32\svchost.exe 11688 752 System 2 C:\Windows\System32\services.exe C:\Windows\System32\svchost.exe 11624 752 System I have tried a few things like this but can't seem to get it right maybe because of the \ used in windows and python not liking it: PID['Parent'] = PID['Parent'].apply(lambda x: x[0].split('\ ')[-1]) PID['Parent'] = PID['Parent'].apply(lambda x: x[0].split(' \ ')[+1])
possible better answer: http://stackoverflow.com/a/51583559
tagged with: dataframe
has title: Pandas dataframe remove last "\" from Parent and Child columns
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51583799
tagged with: pandas
has answer: http://stackoverflow.com/a/51583559
has answer: http://stackoverflow.com/a/51583658
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/51583563
tagged with: python
accepted answer: http://stackoverflow.com/a/51583563
tagged with: regex

http://stackoverflow.com/q/51487332
has answer: http://stackoverflow.com/a/51487657
tagged with: servicenow
type: Question
has body: I am currently working on a project and I have been stuck in exporting a table from the servicenow website using the code below, but is returning a URL redirection instead of the CSV. Code: url = "https://url.service-now.com/nav_to.do?" \ "uri=server_list.do?sysparm_query=active=false%26CSV" response = requests.get(url, stream=True, headers=headers, allow_redirects=True, verify="C:\\Users\user\PycharmProjects\cert.crt") LocalFilePath = "C:\\Users\user\Documents\Projects\Reporting\server.csv" with open(LocalFilePath, 'wb') as csv2: csv2.write(response.content) Any help and suggestion is much appreciated.
tagged with: export
score: 0
has comment: http://stackoverflow.com/comment/89943785
answer count: 1
has comment: http://stackoverflow.com/comment/89946009
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
linked to: http://stackoverflow.com/q/18439851
has title: Service Now CSV Export Redirection Python

http://stackoverflow.com/q/51521436
score: 3
has body: Say I have a nested list of objects that have a method called get_name(), which gives you a name for the object, and you have to sort the lists by alphabetical order. my_list = [[obj1, obj2, obj3], [obj4, obj5, obj6], [obj7, obj8]] But I don't know how to make it work with a list of objects, specifically with get_name() as the main method to use, it also has to be assumed that only the list within the list has to be sorted. Any help is appreciated!
upvote count: 3
has title: Sorting a nested list of Objects with specific method
type: Question
tagged with: object
has answer: http://stackoverflow.com/a/51521494
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51521502
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51608408
accepted answer: http://stackoverflow.com/a/51610568
answer count: 1
has title: TensorFlow Serving: Pass image to classifier
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90182335
upvote count: 3
has answer: http://stackoverflow.com/a/51610568
tagged with: tensorflow-serving
has comment: http://stackoverflow.com/comment/90183131
tagged with: tensorflow
type: Question
has body: I have built a simple classifier in Tensorflow (Python, tensorflow 1.9.0 and tensorflow-serving 1.9.0) which classifies objects into one of 5 classes. Now, I would like to serve that model. I have exported it and given it a classification signature (and only a classification signature): classification_signature = tf.saved_model.signature_def_utils.build_signature_def( inputs={signature_constants.CLASSIFY_INPUTS: classification_inputs}, outputs={ signature_constants.CLASSIFY_OUTPUT_CLASSES: classification_outputs_classes }, method_name=signature_constants.CLASSIFY_METHOD_NAME) which, further down the line, becomes: builder.add_meta_graph_and_variables( sess, [tag_constants.SERVING], signature_def_map={ 'classification_results': classification_signature }, clear_devices=True, legacy_init_op=legacy_init_op) And when I start the TF server I can see that the model is being served. My problem is how to pass an image to is from the client. The code is as follows: request = classification_pb2.ClassificationRequest() request.model_spec.name = model request.model_spec.signature_name = 'classification_results' And this is where I am sort of lost and somewhat confused. For a PredictionRequest the code is: request.inputs['inputs'].CopyFrom( tf.contrib.util.make_tensor_proto(image.astype(dtype=np.uint8), shape=[1, height, width, 3])) but that does not work for a ClassificationRequest. The error is: File "TestServices.py", line 99, in make_request request.inputs['inputs'].CopyFrom( AttributeError: 'ClassificationRequest' object has no attribute 'inputs' Neither does: request.input.CopyFrom(input_pb2.Input( tf.contrib.util.make_tensor_proto(image.astype(dtype=np.uint8), shape=[1, height, width, 3]) ) ) which gives the error: File "TestServices.py", line 102, in make_request tf.contrib.util.make_tensor_proto(image.astype(dtype=np.uint8), shape=[1,height, width, 3]) TypeError: Parameter to CopyFrom() must be instance of same class: expected tensorflow.serving.Input got tensorflow.Ten…
downvote count: 0

http://stackoverflow.com/a/51508059
score: 4
has comment: http://stackoverflow.com/comment/89985419
type: AcceptedAnswer
type: Answer
upvote count: 4
has body: I came up with this: def stretch(*lists): length = max([len(l) for l in lists]) return [[l[i * len(l) // length] for i in range(length)] for l in lists] It computes the the target length as the maximum over all lists, and then stretches the list based on their index, similar to how you would implement naïve, one-dimensional image scaling.
downvote count: 0
answers question: http://stackoverflow.com/q/51507943
accepted answer of: http://stackoverflow.com/q/51507943

http://stackoverflow.com/a/51557840
has comment: http://stackoverflow.com/comment/90082668
has comment: http://stackoverflow.com/comment/90082714
upvote count: 9
has comment: http://stackoverflow.com/comment/90083619
type: Answer
downvote count: 0
has body: Your question is really unclear. However you can use pandas library to read file excel format. import pandas as pd print(pd.read_excel('file.xlsx').columns) Call to .columns list the headers of all the columns Output example: Index(['id', 'email','server','profession'], dtype='object') EDIT: Ok now I see you have very odd first to rows which do not comply with pandas data structure. The simplest solution is to skip the first two rows. And then import it into panadas DataFrame use skiprows to skip first n rows. In your case 2 import pandas as pd print(pd.read_excel('file.xlsx',skiprows=2).columns)
score: 9
answers question: http://stackoverflow.com/q/51557701

http://stackoverflow.com/q/51599622
has comment: http://stackoverflow.com/comment/90166050
has comment: http://stackoverflow.com/comment/90166189
has comment: http://stackoverflow.com/comment/90165770
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90166156
has title: File open randomly doesn't work
has comment: http://stackoverflow.com/comment/90165463
type: Question
has comment: http://stackoverflow.com/comment/90165732
has comment: http://stackoverflow.com/comment/90165850
has body: I am using Python code(written by someone else) which basically scans a folder, and reads all the Wav files in it, and sends them to a Cloud Voice service. if there are "N" distinct folders, it runs this in parallel, by opening 'N" python instances. This is run on Win10 machine. The code looks like: try: for i in range(3): files = "" if wavEnding == ".wav": with open(fName+wavEnding, 'rb') as inf: inf.seek(40) s = inf.read(4) dLengt = struct.unpack("&lt;I",s) tosend = inf.read(dLengt[0]) files = [ ('file', ('request', json.dumps(ASRService), 'application/json; charset=UTF-8')), ('file', ('audio', tosend, 'audio/L16; rate=16000; channels=1')) ] except IOError as ierr: currentDT = datetime.datetime.now() with open(os.getcwd() + "\\sendUtterance.txt", "a") as aF: print "File: " + fName + wavEnding+" not found" aF.write(str(currentDT) + " " + fName + wavEnding+ " + not found\n") aF.close() Now, every now and then, I can see "sendUtterance.txt" shows errors for missing files,for different folders, while I can clearly see that files are present in those folders (timing of errors and folders are random). Below is snapshot of error for error file: If there was something wrong with code, I would expect this to throw error for each file in each folder, bit it doesn't. Could running this as parallel process, be straining/chocking the system, so that file open doesn't work? or is it something else? and what can I do for possible solution?
score: 0

http://stackoverflow.com/comment/90207655
comment on: http://stackoverflow.com/a/51619869
score: 0
type: AnswerComment
type: Comment
has text: This works great. Thanks --- actions = ActionChains(driver) menu = driver.find_element(By.XPATH, '//a[text()="Luke Wilson"]') actions.context_click(menu) actions.perform()

http://stackoverflow.com/comment/89977936
type: QuestionComment
has text: data = pickle.dumps(open(args["encodings"], "rb").read())
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51504480

http://stackoverflow.com/comment/90023845
type: QuestionComment
comment on: http://stackoverflow.com/q/51527495
has text: I would like to know if I can use the data.positive.map to directly map to the "XX" values in BLIP or if I have to create a new field with True and False values.
score: 0
type: Comment

http://stackoverflow.com/a/51601154
answers question: http://stackoverflow.com/q/51597754
accepted answer of: http://stackoverflow.com/q/51597754
type: AcceptedAnswer
score: 0
has body: Given: $ cat file.txt ...some lines before this... MY TEST MATRIX (ROWS) 0.5056E+03 0.8687E-03 -0.1202E-02 0.5056E+03 0.8687E-03 -0.1202E-02 MY TEST END 0.5056E+03 0.8687E-03 -0.1202E-02 0.3776E+03 0.8687E-03 0.1975E-04 STOP ---some lines after this MY TEST MATRIX (ROWS) 2E+04 2E+04 0.8687E-03 2E+04 2E+04 0.8687E-03 MY TEST END 0.5056E+03 0.8687E-03 -0.1202E-02 0.5056E+03 0.8687E-03 -0.1202E-02 STOP ---some lines after this ---this repeats in txt file---- In sed, perl or awk you have the concept of a range regex to do something along the lines of: $ sed -nE '/^MY TEST MATRIX/,/^MY TEST END/p' file.txt MY TEST MATRIX (ROWS) 0.5056E+03 0.8687E-03 -0.1202E-02 0.5056E+03 0.8687E-03 -0.1202E-02 MY TEST END MY TEST MATRIX (ROWS) 2E+04 2E+04 0.8687E-03 2E+04 2E+04 0.8687E-03 MY TEST END You can replicate this functionality in Python with a FlipFlop class: class FlipFlop: ''' Class to imitate the bahavior of /start/, /end/ flip flop in awk ''' def __init__(self, start_pattern, end_pattern): self.patterns = start_pattern, end_pattern self.state = False def __call__(self, st): ms=[e.search(st) for e in self.patterns] if all(m for m in ms): self.state = False return True rtr=True if self.state else False if ms[self.state]: self.state = not self.state return self.state or rtr Then capture the blocks as you read the file line-by-line: di={} blocks=[FlipFlop(re.compile(r'^MY TEST MATRIX \(ROWS\)'), re.compile(r'^MY TEST END')), FlipFlop(re.compile(r'^MY TEST END'), re.compile(r'^STOP'))] for i, ff in enumerate(blocks): with open(fn) as f: di[i]=[line.strip() for line in f if ff(line)] Result: &gt;&gt;&gt; di {0: ['MY TEST MATRIX (ROWS)', '0.5056E+03 0.8687E-03 -0.1202E-02', '0.5056E+03 0.8687E-03 -0.1202E-02', 'MY TEST END', 'MY TEST MATRIX (ROWS)', '2E+04 2E+04 0.8687E-03', '2E+04 2E+04 0.8687E-03', 'MY TEST END'], 1: ['MY TEST END', '0.5056E+03 0.8687E-03 -0.1202E-02', '0.3776E+03 0.8687E-03 0.1975E-04', 'STOP', 'MY TEST END', '0.5056E+03 0.8687E-03 -0.1202E-02', '0.5056E+03 0.…
type: Answer
has comment: http://stackoverflow.com/comment/90185919

http://stackoverflow.com/q/51483394
downvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51484024
has body: I'm trying to find pages in my network where full download size is too big, let's say, bigger than 10-20MiB. I already know how to crawl, I need something that will find out the size of everything a browser would be downloading for each page, preferably without actually downloading it, but this condition is of minor importance. Preferably in python, but if not at least something that I could use inside a bash script (for example curl or wget). I would call that bash script from inside python. As for more context, in python, right now I'm using requests and beautiful soup for crawling and checking the status response of all the web pages.
tagged with: web-crawler
has title: In python, how to check the full size of a web page, including images, and other embedded elements?
tagged with: bash
type: AnsweredQuestion
upvote count: 0
tagged with: wget
favorite count: 0
accepted answer: http://stackoverflow.com/a/51484024
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89936557
score: -1
tagged with: curl

http://stackoverflow.com/a/51498795
downvote count: 0
answers question: http://stackoverflow.com/q/51498464
type: Answer
score: 1
upvote count: 1
has body: You can try this to print only those whose values match. for tr in table_body.find_all('tr'): fields = ['Description','Category','Department','Justification'] for td in tr: print (['{}:{}'.format(i,html_check(td,i)) for i in fields if html_check(td,i)])

http://stackoverflow.com/comment/90196627
comment on: http://stackoverflow.com/a/51598416
score: 0
has text: This works on the dummy data but not on the real data, where the line "Di_3[k] = Di_1[k] .groupby('Material') .apply(fun) .to_frame() .transpose()" gives the "AttributeError: 'DataFrame' object has no attribute 'to_frame'"
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51508700
linked to: http://stackoverflow.com/q/31490436
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/89986576
type: UnansweredQuestion
has title: Is there a function to draw a horizontal ray on matplotlib?
has comment: http://stackoverflow.com/comment/89986438
has comment: http://stackoverflow.com/comment/89986671
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89986710
tagged with: python
has answer: http://stackoverflow.com/a/51509570
has body: I am trying to draw a horizontal ray instead of horizontal line. Matplotlib has axhline() function. But it starts drawing from at the beginning of the chart. I am setting points at the high and low of the bar as you can see in the attached picture. Is there a way to draw a line on a specific point? I have tried fillstyle="right" but i think this is not something i am looking for.
has comment: http://stackoverflow.com/comment/93116734
upvote count: 2
has comment: http://stackoverflow.com/comment/89986698
has comment: http://stackoverflow.com/comment/89986620
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/51536531

http://stackoverflow.com/comment/90251470
type: AnswerComment
score: 0
has text: Thank you so much! This is a superb answer. And you didn't discuss it, but the way you initialized the lengths as timedeltas is another good improvement. I benchmarked this new code on the same 1,000,000 calls as before, and it runs in 3.5 seconds now, compared to 40.0 before.
type: Comment
comment on: http://stackoverflow.com/a/51628813

http://stackoverflow.com/comment/90067788
type: Comment
has text: What's `X` used in this code? Seems useless? `a` just a arithmetic progression, ignore any value of `X`
comment on: http://stackoverflow.com/q/51550074
score: 0
type: QuestionComment

http://stackoverflow.com/a/51587563
has body: OR change: print('roll is: '(random.randrange(1, dsize))) To: print('roll is: {}'.format(random.randrange(1, dsize))) Or: print('roll is: %s'%random.randrange(1, dsize)) Or the new f-strings (only works with python version > 3.6): print(f'roll is: {random.randrange(1, dsize)}') Full code: import sys import random import getopt def main(argv): dsize = '' try: opts, args = getopt.getopt(argv, "hi:o:", ["dsize="]) except getopt.GetoptError: print("Roll.py -d &lt;dsize&gt;") sys.exit(2) for opt, arg in opts: if opt == '-h': print('Roll.py -d &lt;dsize&gt;') sys.exit() # elif opt in ("-d", "--dsize"): # dsize = arg print('Die size is ', dsize) print('roll is: {}'.format(random.randrange(1, dsize))) # here i just use the first option if __name__ == "__main__": main(sys.argv[1:])
answers question: http://stackoverflow.com/q/51587502
score: 0
type: Answer

http://stackoverflow.com/q/51564667
score: 2
tagged with: xbox
upvote count: 3
has comment: http://stackoverflow.com/comment/99432992
has comment: http://stackoverflow.com/comment/90125777
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90126961
has body: I'm using Evdev to read the XBOX ONE inputs of A, B, X, Y to great success. However, I am battling to pick up the Analog Stick inputs. Can anyone help me with the Python code for this? I am trying to control a Servo. This is my code so far, it works "perfectly". I need to know how to read the outupts of the (xbox)joystick so i can us "GPIO.PWM" for the servo. from evdev import InputDevice, categorize, ecodes, KeyEvent import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BOARD) GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(7, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(11, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(12, GPIO.OUT, initial=GPIO.LOW) gamepad = InputDevice('/dev/input/event2') #evdev takes care of polling the controller in a loop for event in gamepad.read_loop(): if event.type == ecodes.EV_KEY: keyevent = categorize(event) if keyevent.keystate == KeyEvent.key_down: if keyevent.keycode[0] == "BTN_A": print "Button A Pressed" GPIO.output (8, GPIO.HIGH) elif keyevent.keycode[0] == "BTN_B": print "Button B Pressed" GPIO.output (7, GPIO.HIGH) elif keyevent.keycode[0] == "BTN_WEST": print "Button Y Pressed" GPIO.output (11, GPIO.HIGH) elif keyevent.keycode[0] == "BTN_NORTH": print "Button X Pressed" GPIO.output (12, GPIO.HIGH) if keyevent.keystate == KeyEvent.key_up: if keyevent.keycode[0] == "BTN_A": print "Button A Released" GPIO.output (8, GPIO.LOW) elif keyevent.keycode[0] == "BTN_B": print "Button B Released" GPIO.output (7, GPIO.LOW) elif keyevent.keycode[0] == "BTN_WEST": print "Button Y Released" GPIO.output (11, GPIO.LOW) elif keyevent.keycode[0] == "BTN_NORTH": print "Button X Released" GPIO.output (12, GPIO.LOW)
has comment: http://stackoverflow.com/comment/90096610
answer count: 1
tagged with: evdev
favorite count: 0
has comment: http://stackoverflow.com/comment/90130110
has comment: http://stackoverflow.com/comment/90128582
tagged with: servo
has answer: http://stackoverflow.com/a/56419190
type: UnansweredQuestion
tagged with: python
has title: XBox One Wireless control of Servo using Analogue Stick withevdev

http://stackoverflow.com/comment/89959141
score: 0
comment on: http://stackoverflow.com/q/51493106
type: Comment
type: QuestionComment
has text: Here an example from [Odoo sale app](https://github.com/odoo/odoo/blob/6e71cf8a71d0713945947a4e96a9b70978d7f90d/addons/sale/views/sale_views.xml#L366-L378). Usually the sales order lines are inline editable. But if a user is in special access groups (packaging, mrp properties) he will get a popup on the lines.

http://stackoverflow.com/comment/90201029
has text: Please fix the indentation of the first for statement.
type: QuestionComment
comment on: http://stackoverflow.com/q/51617624
score: 0
type: Comment

http://stackoverflow.com/a/57081252
upvote count: 10
downvote count: 1
score: 9
has comment: http://stackoverflow.com/comment/114602255
has body: If you face the issue in Ubuntu you can try the below two steps to remove it from your command prompt. conda config conda config --set changeps1 False
type: Answer
has comment: http://stackoverflow.com/comment/103669085
answers question: http://stackoverflow.com/q/51526503

http://stackoverflow.com/comment/90205452
score: 0
type: AnswerComment
type: Comment
has text: Another problem with MinMaxScaler is that obtaining an output of 'Test Score: 0.00 MSE (0.01 RMSE)" which is confusing as ofcourse the loss values are of the order 10^-6, so would such low values indicate overfitting or just that is expected given the magnitude of the scaled values?
comment on: http://stackoverflow.com/a/51608754

mfcc
type: Tag
tag name: mfcc
tags question: http://stackoverflow.com/q/51634111

http://stackoverflow.com/comment/90056193
has text: You need to mention engine configurations include pool configuration as well in the post
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51543936

http://stackoverflow.com/comment/90560093
score: 0
has text: Yes -thanks for your help. Actually I integrated all the scripts into one. Problem solved.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51627156

http://stackoverflow.com/comment/89947068
comment on: http://stackoverflow.com/a/51488938
type: Comment
has text: I can't believe you put the coolest part of your answer in a comment :)
score: 2
type: AnswerComment

http://stackoverflow.com/comment/89965188
type: QuestionComment
score: 0
has text: '/home.user/directory/file1.ext' here is a typo? Because is different from '/home/user/directory/file1.ext'. Is not the same path. You have home.user here.
comment on: http://stackoverflow.com/q/51498612
type: Comment

http://stackoverflow.com/comment/104596793
comment on: http://stackoverflow.com/a/51570044
score: 0
type: AnswerComment
type: Comment
has text: @Hendy if you can see element in inspector, you can interact with it via Selenium. I guess your element is under `frame` or `iframe` element or even `shadow-root` element. If it is the case, just google it and you will find answer(also in SO)

http://stackoverflow.com/comment/89973593
type: AnswerComment
comment on: http://stackoverflow.com/a/51501255
score: 0
type: Comment
has text: Thank you, good call! The error is on the line `next_home_index = df[(df['date_rank'] == next_home_fixture) & (df['localteam_id'] == df.at[index,'localteam_id'])].index.item()` due to `df[(df['date_rank'] == next_home_fixture) & (df['localteam_id'] == df.at[index,'localteam_id'])].index` returning zero elements despite expecting one

http://stackoverflow.com/comment/90052375
comment on: http://stackoverflow.com/q/51542203
type: Comment
has text: Have you imported this `from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC `
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90194784
type: QuestionComment
has text: Are you sure you don't want to filter out `None`s from `row['my_row_1']`? The `finish` function is returning a list that may have `None`s in it.
comment on: http://stackoverflow.com/q/51614459
score: 0
type: Comment

http://stackoverflow.com/comment/90475616
type: Comment
has text: Thank you for all your inputs, apologies for the delay, I am following the approach you suggested :)
comment on: http://stackoverflow.com/a/51622826
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90214473
comment on: http://stackoverflow.com/a/51604387
type: Comment
type: AnswerComment
has text: Nvm, one more question... self.__class__(), what does this do when you assign it to _l. I specifically don't know __class__() function; does that create a class?
score: 0

http://stackoverflow.com/a/51519237
score: 8
downvote count: 0
has comment: http://stackoverflow.com/comment/90012468
upvote count: 8
type: Answer
has body: A recursive approach: def remove(lst, sub): if not lst: return [] if lst[:len(sub)] == sub: return remove(lst[len(sub):], sub) return lst[:1] + remove(lst[1:], sub) print(remove(big_list, sub_list)) This outputs: [2, 3, 4]
answers question: http://stackoverflow.com/q/51518601

http://stackoverflow.com/a/51552492
score: 3
accepted answer of: http://stackoverflow.com/q/51552453
downvote count: 0
has comment: http://stackoverflow.com/comment/90072361
has body: Use str.strip with punctuation: import string df['fruits'] = df['fruits'].str.strip(string.punctuation) print (df) id price fruits 0 1 1 apple 1 2 2 apple, banana 2 3 3 orange print (string.punctuation) !"#$%&amp;'()*+,-./:;&lt;=&gt;?@[\]^_`{|}~ EDIT: For custom punctuation is possible use string, only necessary escape " if value for check: df['fruits'] = df['fruits'].str.strip(",\"?'.") print (df) id price fruits 0 1 1 apple 1 2 2 apple, banana 2 3 3 orange
has comment: http://stackoverflow.com/comment/90074306
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90072257
type: Answer
answers question: http://stackoverflow.com/q/51552453
has comment: http://stackoverflow.com/comment/90074291

http://stackoverflow.com/q/51495091
has comment: http://stackoverflow.com/comment/89961763
answer count: 0
has comment: http://stackoverflow.com/comment/89962387
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89963326
has comment: http://stackoverflow.com/comment/89961541
has comment: http://stackoverflow.com/comment/89961595
tagged with: pyqt5
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89962202
has comment: http://stackoverflow.com/comment/89958573
has title: How to move picbutton? Pyqt5 python
has comment: http://stackoverflow.com/comment/89961840
has comment: http://stackoverflow.com/comment/89961660
has comment: http://stackoverflow.com/comment/89961473
score: 0
has body: I want to make a button from a picture. I found this code in here, but i cant move the picture, how can i do that? import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * class PicButton(QAbstractButton): def __init__(self, pixmap, parent=None): super(PicButton, self).__init__(parent) self.pixmap = pixmap def paintEvent(self, event): painter = QPainter(self) # painter.drawPixmap(100,1, self.pixmap) painter.drawPixmap(500,1,100,100, self.pixmap,0,0,100,100) def sizeHint(self): return self.pixmap.size() def close(): print("xxx") app = QApplication(sys.argv) window = QWidget() layout = QHBoxLayout(window) window.setFixedSize(740, 850) #window size. button = PicButton(QPixmap("thinking.png")) button.clicked.connect(close) layout.addWidget(button) window.show() sys.exit(app.exec_()) I can move in x axis but cant in y axis. How can i do that? And is there any cursor style to make this more like button? Thank you. here is output
has comment: http://stackoverflow.com/comment/89968119
tagged with: pyqt
has comment: http://stackoverflow.com/comment/89967760
has comment: http://stackoverflow.com/comment/89963591
favorite count: 0
has comment: http://stackoverflow.com/comment/89961515
has comment: http://stackoverflow.com/comment/89962410
has comment: http://stackoverflow.com/comment/89963252
tagged with: python

http://stackoverflow.com/q/51563435
has comment: http://stackoverflow.com/comment/90094864
downvote count: 0
answer count: 0
tagged with: pivot
score: 1
has title: Pandas complex GroupBy or Pivot with non numerical data
type: Question
tagged with: pandas-groupby
tagged with: pandas
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90094327
has comment: http://stackoverflow.com/comment/90094566
tagged with: pivot-table
type: UnansweredQuestion
has body: I have a set of data that I'm trying to filter and group. For each unique ID, I want to get a count of unique users, IPs, and names, then list those things out. I've used this line to filter the data down to what I want, and I think its working: df = df[df.isin(df[df.duplicated(subset=['id'], keep=False)])] The result looks something like this: id user ip name x123.blah 123 1.1.1.1 whatever x123.blah 212 1.1.1.1 whatever x123.blah 212 2.2.2.2 whatever x123.blah 345 1.1.1.1 something_else y321.blah 444 3.3.3.3 mom y321.blah 555 3.3.3.3 mom y321.blah 666 3.3.3.3 mom Currently I'm having to output this as 2 separate files, one doing a groupby to get a count of unique values per name, and another is just the whole DF. I have to check both, which is not ideal. df_g = df.groupby(['id','name']).user.nunique(dropna=False).reset_index() id name user x123.blah whatever 2 x123.blah something_else 1 y321.blah mom 3 What I want is this: id name ip user x123.blah 2 2 3 whatever 1.1.1.1, 2.2.2.2 123, 212 something_else 1.1.1.1 345 y321.blah 1 1 3 mom 3.3.3.3 444, 555, 666 Is this something that can even be accomplished with GroupBy? I messed around a bit with pivot tables but i got errors because of non numerical values
tagged with: python

http://stackoverflow.com/q/51565534
score: 0
has body: I'm using Pandas to read a CSV data file into a DataFrame. The data is basically a bunch of dimensions in one column and the next one is the unit. I.E. Perameter | measurement | unit Height | 72 | inches Length | 20 | mm I would then like to search through the DataFrame, find all places where the unit does not match what it should (i.e. lbs vs kg) and then simply convert it to the units that the rest of the script uses. I'm stumped on how to search through based on one column, read that value, divide/multiply that value by the conversion factor, then replace the value in the DataFrame. I can't get this to work: df = pd.read_csv('path/to/Input.csv') data.loc[ data.Units == 'in' ] = x data[measurement][x] = ((data[measurement][x])/25.4) # convert to mm. Any ideas?
tagged with: python
answer count: 1
has title: Update value if a condition in the adjacent cell is true
has answer: http://stackoverflow.com/a/51565582
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51565582
type: Question
tagged with: pandas

http://stackoverflow.com/q/51494886
has body: My apologies if this is a dumb question. I am trying to make a zoom-able interface but I want it to reset it's self after a while. I managed to make it zoom-able using a scatterLayout but I can't get it to revert back to its original size after that, unless the user zooms back out himself. Any way to reset my scatterLayout to its original size after I zoom in on it?
has title: Kivy scatterLayout revert to original size
has answer: http://stackoverflow.com/a/51497161
answer count: 1
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/51497161
type: AnsweredQuestion
tagged with: python
tagged with: kivy
favorite count: 0
tagged with: kivy-language
type: Question
upvote count: 1

http://stackoverflow.com/q/51630880
has comment: http://stackoverflow.com/comment/90226623
has title: Python parse webpage links counter
type: Question
accepted answer: http://stackoverflow.com/a/51631426
answer count: 2
downvote count: 0
tagged with: hyperlink
tagged with: counter
has body: I'm just parsing links from a url using the code below. The links are found however my counter does not work. any ideas on how to fix my counter please? thanks def parse_all_links(html): links = re.findall(r"""a href=(['"].*['"])""", html)#find links starting with href print("found the following links addresses: ".format(len(html)))#print a message before the output if len(links) ==0: print("Sorry, no links found") else: count = 1#this count how many links are displayed for e in links: print(e) count += 1 print('--------------')
has comment: http://stackoverflow.com/comment/90226344
tagged with: url
tagged with: parsing
favorite count: 0
has answer: http://stackoverflow.com/a/51631426
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/51631395
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90241240
has answer: http://stackoverflow.com/a/51631395
has comment: http://stackoverflow.com/comment/90235651
score: 1

http://stackoverflow.com/q/51506632
tagged with: instantiation
has comment: http://stackoverflow.com/comment/89982814
score: 0
has title: Create subclass from within superclass - Python
has body: I've checked a few of the stackoverflow articles, but couldn't find an answer to my question, so sorry if this is a duplicate. The closes I could find was Instantiate subclass from superclass but this still isn't exactly what I want. So imagine I have three class: 1 super class and 2 subclasses and I want to do some weird copy method that is the same for all my classes. But in particular, my copy needs to be a new instantiation of said object. Example: class Pet(object): def __init__(self,name): self._name = name def weird_copy(self): name = self._name + " weird" z = XXX(name) class Dog(Pet): def __init__(self,name): self._name = name + " dog" class Cat(Pet): def __init__(self,name): self._name = name + " cat" The XXX part is where I don't know what to do. If I do d = Dog('ralph') d2 = d.weird_copy() I want d2 to be a Dog object instead of a Pet object. I tried replacing XXX with self and that started causing problems. I know there's a way to do @classmethod, but the problem with that is that I need to use properties from self, so I need to not switch "self" to "cls". Thanks.
linked to: http://stackoverflow.com/q/14186073
answer count: 1
has answer: http://stackoverflow.com/a/51506662
has comment: http://stackoverflow.com/comment/89984717
tagged with: subclass
has comment: http://stackoverflow.com/comment/89984927
tagged with: python
accepted answer: http://stackoverflow.com/a/51506662
has comment: http://stackoverflow.com/comment/89986856
tagged with: superclass
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/51509985
tagged with: python
type: AnsweredQuestion
has title: Using external script in Views.py
type: Question
has body: I have a file that sends a request to an API and retrieves information. Let's call this file get_info.py. I am now building a GUI that uses Django and the views.py file, with methods 'GET' and 'POST'. I am now importing the function from get_info.py into views.py and using it as follows from get_info import get_info @api_view(['GET']) def generate_route(request): """ :param request: 1. lat: posx 2. lng: pos, 3. r: radius in km 4. strategy, 5. edge_num, 6. deep, :return: """ posx = request.query_params.get('lat', None) posy= request.query_params.get('lng', None) r= request.query_params.get('r', None) strategy = request.query_params.get('strategy', None) strategy = strategy if strategy else 3 edge_num = request.query_params.get('edge_num', None) edge_num = edge_num if edge_num else 3 deep = request.query_params.get('deep', None) deep = deep if deep else 3 print("BEFORE", posx, posy, r, strategy, edge_num, deep) route = get_info(posx, posy, r) print("AFTER", route) if request.query_params.get('lat', None) is not None \ and request.query_params.get('lng', None) is not None \ and request.query_params.get('r', None) is not None: return Response({}, status=status.HTTP_200_OK) else: return Response({ "Error": 'Need lat, lng, and r {}'.format(request.query_params.get('lat', None)) }, status=status.HTTP_400_BAD_REQUEST) ``` However, I get the response &gt; (u'BEFORE', u'112.34', u'14.55', u'300.3', 3, 3, 3) Internal Server Error: /app/api/v1/get_info/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/cor…
has answer: http://stackoverflow.com/a/51514791
accepted answer: http://stackoverflow.com/a/51514791
score: 0
has comment: http://stackoverflow.com/comment/89989621
answer count: 1
has comment: http://stackoverflow.com/comment/89996503
tagged with: django

http://stackoverflow.com/q/51612737
has comment: http://stackoverflow.com/comment/90190385
has answer: http://stackoverflow.com/a/51612948
score: 0
has body: Here is a typical exception process but it doesn't write it to the file later. What could be wrong? Summary: The with statement is used to write the files that are not existent. In this case they are not being written to the txt file. Possible solution would be to simply change how the writing process is happening. AST = [] ASTOTA = [] folder = path.Path(r"C:\Users\user\Desktop\testn") with open('log.txt', 'w') as fw: for shpfile in glob.iglob('/*/*/Desktop/testn/*/*/*'): try: df = geopandas.read_file(shpfile).assign(col = get_folder(shpfile)) if shpfile.endswith('AST.shp'): AST.append(df) else: ASTOTA.append(df) except FionaValueError as ex: if not os.listdir(shpfile): fw.write(f'{shpfile} is empty' + '\n') &lt;- Here is where should write to the txt file The position of the fw.write is obviously the wrong part because if I replace it with a print statement it still doesn't show anything even though there are things to write because some folders are indeed empty.
answer count: 1
has title: txt file doesn't contain the results?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90190581
has comment: http://stackoverflow.com/comment/90190480
type: Question
tagged with: try-catch

http://stackoverflow.com/q/51496304
has comment: http://stackoverflow.com/comment/89960657
score: 2
tagged with: ubuntu-16.04
has answer: http://stackoverflow.com/a/61775525
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/89960867
tagged with: django-staticfiles
answer count: 1
favorite count: 0
has title: Django: collectstatic raises OSError: [Errno 39] Directory not empty: (ckeditor)
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: Suddenly, I can't do collectstatic. python manage.py collectstatic Type 'yes' to continue, or 'no' to cancel: yes Found another file with the destination path 'admin/js/jquery.init.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/django/maklerienv36/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle collected = self.collect() File "/home/django/maklerienv36/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/home/django/maklerienv36/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 344, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/home/django/maklerienv36/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 294, in delete_file self.storage.delete(prefixed_path) File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/files/storage.py", line 299, in delete os.rmdir(name) OSError: [Errno 39] Directory not…

http://stackoverflow.com/comment/90152604
type: AnswerComment
type: Comment
has text: `from static_method_2 import Sample as sam` and then try to use `sam.calculate(num)` or `import static_method_2.Sample.calculate as sam` and then try to use `sam.calculate(num)`
score: 1
comment on: http://stackoverflow.com/a/51593251

http://stackoverflow.com/a/70908262
downvote count: 0
upvote count: 1
has body: Normally, the icons are corrected once the script is compiled into an app (tested with pyinstaller). However, on macOS this is not perfect and there is still issues with some icons (like the showerror icon)... So I suggest you to manage the icons manually with the command: root.tk.call('wm', 'iconphoto', root._w, PhotoImage(file="path/to/icon.png")) This allows you to display a custom png image as icon, but this will also change the app icon. So I advise you to reinitialize the icon once the message is closed: root.tk.call('wm', 'iconphoto', root._w, PhotoImage(file="path/to/icon.png")) messagebox.showerror("Error", "Oups...") root.tk.call('wm', 'iconphoto', root._w, PhotoImage(file="path/to/original_app_icon.png"))
has comment: http://stackoverflow.com/comment/128144665
answers question: http://stackoverflow.com/q/51530310
type: Answer
score: 1

http://stackoverflow.com/comment/90225322
comment on: http://stackoverflow.com/a/51629142
score: 0
type: Comment
has text: I'm really looking for a structlog-only solution. How do I filter based on level in a structlog-only world? How do I render to multiple destinations in a structlog-only world?
type: AnswerComment

http://stackoverflow.com/a/51530287
has comment: http://stackoverflow.com/comment/90050230
has body: Your last section has a problem. for file in os.listdir(folderPath): for file in files: if file in filesToFind: shutil.copy(file, destination) The first for loops over each filename in the directory, which is perfectly understandable. The second for is an error, because files does not exist. What did you intend it to do?
answers question: http://stackoverflow.com/q/51528103
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51552292
has title: Make PyCharm autocomplete arguments of super’s method
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
has body: Consider the following code: class A: def __init__(self, foo=None): pass class B(A): def __init__(self, bar=None, **kwargs): super().__init__(**kwargs) When I start typing B(, PyCharm helpfully shows bar in the autocomplete windows, quick doc, etc. However, it does not show foo. I have resorted to making foo an explicit argument of class B, but this gets highly repetitive since I have a lot of such arguments. I would like to avoid doing so while still having PyCharm show me all the arguments. How can I make PyCharm do this?
has answer: http://stackoverflow.com/a/51552366
accepted answer: http://stackoverflow.com/a/51552366
tagged with: autocomplete
downvote count: 0
has comment: http://stackoverflow.com/comment/115584403
duplicate of: http://stackoverflow.com/q/51494723
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/51494723
tagged with: pycharm
tagged with: python

http://stackoverflow.com/a/70312421
upvote count: 0
answers question: http://stackoverflow.com/q/51602617
downvote count: 2
has body: from discord.ext.commands import Bot from discord.ext import commands import asyncio import time Client = discord.Client() client = commands.Bot(command_prefix = "!") @client.event async def on_ready(): print("Bot is ready!") @client.event async def on_message(message): if message.content == "cookie": await message.client.send(":cookie:") client.run("PUT YOUR TOKEN HERE")
score: -2
has comment: http://stackoverflow.com/comment/140085095
type: Answer

jupyter
tags question: http://stackoverflow.com/q/51610821
type: Tag
tags question: http://stackoverflow.com/q/51540659
tags question: http://stackoverflow.com/q/51617979
tags question: http://stackoverflow.com/q/51562173
tags question: http://stackoverflow.com/q/51590030
tag name: jupyter
tags question: http://stackoverflow.com/q/51551056
tags question: http://stackoverflow.com/q/51609864
tags question: http://stackoverflow.com/q/51515137
tags question: http://stackoverflow.com/q/51584430
tags question: http://stackoverflow.com/q/51487877
tags question: http://stackoverflow.com/q/51548928
tags question: http://stackoverflow.com/q/51523301
tags question: http://stackoverflow.com/q/51602472
tags question: http://stackoverflow.com/q/51527868
tags question: http://stackoverflow.com/q/51613845

http://stackoverflow.com/a/51550269
has comment: http://stackoverflow.com/comment/90101765
has body: Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. CPython implementation detail: This is the address of the object in memory. Source: https://docs.python.org/3.7/library/functions.html#id There are situations that some values have the same id, because they are implemented as singletons. These are usually values that are statistically going to occur often in a typical program. Some obvious examples of this are None, True, and False. &gt;&gt;&gt; variable = True &gt;&gt;&gt; variable is True True Some non-obvious examples of this are relatively small numbers. &gt;&gt;&gt; variable = 256 &gt;&gt;&gt; variable is 256 True &gt;&gt;&gt; variable = 257 &gt;&gt;&gt; variable is 257 False This is also why people advise using the == operator over is for value comparison.
has comment: http://stackoverflow.com/comment/90068365
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51550056
upvote count: 0
has comment: http://stackoverflow.com/comment/90068161
has comment: http://stackoverflow.com/comment/90068502
score: -1

http://stackoverflow.com/comment/89988825
comment on: http://stackoverflow.com/a/51509795
type: Comment
has text: @Marcus.Aurelianus Yes. (They’re classes, so it’s a _bit_ confusing to call them instances, but it’s not incorrect—classes are just instances of their metaclasses.)
score: 0
type: AnswerComment

http://stackoverflow.com/a/51542811
answers question: http://stackoverflow.com/q/51542700
score: 3
type: AcceptedAnswer
downvote count: 0
has body: Use where for get values by mask and then join columns together: L = ['col_1','col_2'] L1 = ['col_n_1','col_n_2'] df['new'] = (df[L1].astype(str).where(df[L].eq(1).values, axis=1) .apply(lambda x: ','.join(x.dropna()), 1)) Solution if only 2 columns: L = ['col_1','col_2'] L1 = ['col_n_1','col_n_2'] df1 = df[L1].astype(str).where(df[L].eq(1).values, axis=1) df['new'] = (df1['col_n_1'] .fillna('') + ',' + df1['col_n_2'] .fillna('')).str.strip(',') Or solution with add , and then sum, last remove trailing ,: df['new'] = (df[L1].astype(str).where(df[L].eq(1).values) .add(', ') .fillna('') .sum(axis=1) .str.strip(', ')) print (df) col_1 col_2 col_n_1 col_n_2 new 0 1 2 3 6 3 1 2 1 4 3 3 2 1 1 4 5 4,5
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51542700

http://stackoverflow.com/comment/89962668
has text: No. That's the complete code, also shown here https://github.com/werowe/KerasExample/blob/master/kerasExample.py
comment on: http://stackoverflow.com/q/51497370
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51649192
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51620113
upvote count: 2
answers question: http://stackoverflow.com/q/51620113
type: AcceptedAnswer
has body: The method _onchange_product_id_check_availability is defined in sale_stock module. If you want to replace its behaviour don't forget to add the sale_stock module in the depends array of your __manifest__.py. Otherwise your method won't be called and the source code will be executed as always. 'depends': [ 'sale_stock', ... ],
type: Answer
score: 2

http://stackoverflow.com/comment/90089244
comment on: http://stackoverflow.com/q/51558182
has text: I have tried using the weights in the embedding layer. But that restricts the amount of words to the embedding layer dimensions. Also I want to use fasttext to predict words not in the vocabulary when running on test data.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90205966
has text: when i use, result["Ratio"] = (1 / result["Server_count"]) * 100 am getting error as "Keyword can't be expression". I checked type of result.it shows as dataframe but still it's not working
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51617228

ssl
tags question: http://stackoverflow.com/q/51606054
tags question: http://stackoverflow.com/q/51554189
type: Tag
tag name: ssl
tags question: http://stackoverflow.com/q/51502329

http://stackoverflow.com/q/51539738
has title: Form field not getting stored in Django User model
tagged with: python
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/51539800
type: Question
answer count: 1
has body: I have a signup form which I have defined below forms.py from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django import forms class SignUpForm(UserCreationForm): display_name = forms.CharField(max_length=30, required=True, help_text='Please provide a display name for your profile') class Meta: model = User fields = ('username', 'password1', 'password2', 'display_name') In the views.py, I handle the signup process views.py from django.contrib.auth.models import User from django.contrib.auth import login, authenticate from .forms import SignUpForm from django.shortcuts import render, redirect @csrf_exempt def signup_users(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data.get('username') display_name = form.cleaned_data.get('display_name') raw_password = form.cleaned_data.get('password1') user.set_password(raw_password) user.display_name = display_name user.save() user = authenticate(username=username, password=raw_password) print("signup authencticate", user) login(request, user) return render(request, 'index.html') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) The user is able to signup successfully however their display_name doesn't get stored in the django User model.Even in the django admin, I do not see the field display_name.I have even performed a query like serializers.serialize("json",User.objects.filter(username=username)) but even here it shows every other field except the display_name. What am I doing wrong?
score: 0
has comment: http://stackoverflow.com/comment/90047152
has comment: http://stackoverflow.com/comment/90047115

http://stackoverflow.com/q/51595838
accepted answer: http://stackoverflow.com/a/51596029
answer count: 1
score: 0
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
type: AnsweredQuestion
has body: I have a dataframe like looks like this: id A B date a 1 NAN 2016-01-01 a NAN 6 2016-01-02 a 7 NAN 2016-10-01 b 3 5 2016-12-01 I'd like to collapse by date and id (each group goes to a single row, using data from the last date in the group, and filling missing data with the most recent data in the group). The groupby would roughly look like this: df.groupby(['id', pd.Grouper(key='date', freq='30D')]) This would result in a dataframe like so: id A B date a 1 6 2016-01-02 a 7 NAN 2016-10-01 b 3 5 2016-12-01 A very simple example. I believe my groupby would work, but I'm not sure how to combine the rows into a single row, and aggregate the data using the most recent data from each column, forward filling data if necessary (if they are all NANs, just use a NAN).
has title: Collapsing a Dataframe with Pandas to a single row per group
type: Question
has answer: http://stackoverflow.com/a/51596029

http://stackoverflow.com/comment/89963174
comment on: http://stackoverflow.com/q/51497423
has text: @Adamso your description of the problem doesn't really match your code - as Jean-François Fabre mentions, your code snippet can NOT "return None" with this indentation (it can goes in an infinite loop but that's another problem). Please check your code for indentation mismatch (tabs / spaces mix - you can use tabnanny for this) and post the REAL code.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90027071
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51484023
type: AnswerComment
has text: Here's a direct [link to the old answer](https://stackoverflow.com/revisions/c9ea280e-ce1b-45b8-84d2-5c51ef070551/view-source). You can also find it by clicking on the "edited ... days ago" link located in the center, below the answer, but above the comments.

http://stackoverflow.com/q/51529286
tagged with: django
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51529540
score: 1
type: Question
answer count: 1
downvote count: 0
tagged with: bootstrap-4
favorite count: 0
has answer: http://stackoverflow.com/a/51529540
has title: Modal Bootstrap - Source Code is different than info rendered by Chrome
tagged with: python
has body: I'm doing an e-commerce project and I rant into an issue. I'm using Bootstrap and Django. I apologize for the long question I basically have a loop that runs through my list of products in the database and lists them. It's a table. Each row is a new product and the cells are specific info about the product. The last cell creates a little modal to edit the current information on the project. The information is being passed correctly through the loop, but on Chrome's rendering I see the information for product one listed in all products. This is what the table looks like: This is what my loop to generate the table looks like: &lt;tbody&gt; {% for product in products %} &lt;tr&gt; &lt;td&gt; &lt;img src="{% static product.main_picture %}" style="width: 100px;"&gt; &lt;/td&gt; &lt;td&gt;{{product.id}}&lt;/td&gt; &lt;td&gt;{{product.name}}&lt;/td&gt; &lt;td&gt;{{product.inventory_count}}&lt;/td&gt; &lt;td&gt;{{product.sold_count}}&lt;/td&gt; &lt;td&gt; &lt;!-- Button trigger edit modal --&gt; &lt;button type="button" class="btn btn-secondary btn-sm" data-toggle="modal" data-target="#editModal"&gt;Edit&lt;/button&gt; &lt;!-- Edit product Modal --&gt; &lt;div class="modal fade" id="editModal" tabindex="-1" role="dialog"&gt; &lt;div class="modal-dialog" role="document"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;h5 class="modal-title" id="exampleModalLabel"&gt;Edit the product&lt;/h5&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"&gt; &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;!-- Form to edit product --&gt; &lt;form method='post' action='/dashboard/products/update'&gt; {% csrf_token %} &lt;div class="form-group"&gt; &lt;label&gt;Name:&lt;/label&gt; &lt;input type="text" class="form-control" name="product_name" value="{{product.name}}"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label&gt;Picture:&lt;/label&gt; &lt;input type=…
tagged with: twitter-bootstrap
upvote count: 1

http://stackoverflow.com/a/51571965
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51527523
has body: We are talking about a game built on Unreal Engine, and you cannot find an address being changed every frame. This makes me concerned about where/how you are trying to find the addresses being changed each frame. Perhaps try a memory scanning tool such as CheatEngine just in case. There should be a few addresses changing each frame. One that comes to mind would be: One of the addresses referenced when using this function: UGameplayStatics::GetRealTimeSeconds(GetWorld()); If you really cannot find a variable changing each frame, then I offer you a solution to hook into a function called in the process every frame by doing the following: This is not a complete solution by any means as this covers a subjectively complex topic that you will likely need to learn about from other sources. [NOTE] If this game uses an anti-cheat, you may be banned for this behaviour, I would suggest doing your research before attempting this. I take no responsibility for any issues or loss you may incur from the use of the following advice. Backup Option: Using CheatEngine, open the target process. Look for a function that is being called every frame (like so): Find a variable you suspect is READ every frame (does not have to be changed) Add it to your address list Right-click the entry from the address list and select: Find out what accesses this address Accept the prompt to attach a debugger to the process Watch the count, is it going up extremely fast? Great! this is likely being read every frame Stop the tool and click on the Instruction entry in the list that has the high count Click the Show Disassembler button You are now looking at the interpreted opcodes for the function that is accessing your address every frame Simply right click the highlighted row and click Select current function to find the start of the function I would personally toggle a breakpoint on this line (F5) with the game visible on the side to ensure it is being triggered each frame (continuing after each break wit…
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90097199
has text: it would be helpful if you give us `final_data['CleanedText'].head()`
score: 0
comment on: http://stackoverflow.com/q/51564639
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51558072
upvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/93610251
favorite count: 0
tagged with: 3d-modelling
tagged with: meshlab
has comment: http://stackoverflow.com/comment/97508684
answer count: 0
type: UnansweredQuestion
score: 3
tagged with: blender
downvote count: 0
type: Question
has body: I have to take input 3D models (can be of format .off, .obj, .pcd) and output the 2D projections i.e, the images like screenshots of that model from various angles. As I want to use them for fine tuning my neural network. So far I have researched a lot but everywhere there is 2D to 3D projections not the opposite. Plus I am a little confused in the difference of pyWavefront, strawlab, pymesh, Asset(it can import bunch of 3D formats). I also have to apply various translations on the obtained images like brightness, reflections etc. if anyone could guide me for that. Then I would really be thankful. P.S, I would appreciate if any of you also shared some sample code.
has comment: http://stackoverflow.com/comment/93724496
has title: import 3D mesh and output its 2D projections
tagged with: 3d-model

http://stackoverflow.com/a/55875973
type: Answer
has body: A simple form: df['MM-DD'] = df['date'].dt.strftime('%m-%d')
has comment: http://stackoverflow.com/comment/98411874
score: 23
answers question: http://stackoverflow.com/q/51603690
upvote count: 23
downvote count: 0

http://stackoverflow.com/q/51482640
has comment: http://stackoverflow.com/comment/89934490
has comment: http://stackoverflow.com/comment/89934182
tagged with: valueerror
type: UnansweredQuestion
has title: ValueError: 'date' needs to be str
has comment: http://stackoverflow.com/comment/89934127
downvote count: 1
has body: I got a nice Python script, that will pull STYLE and YEAR based on MASTER release, with ARTIST+TITLE in mp3/flac as given input on autopilot from Discogs. Using the frontend since backend needs ALBUM to be filled in proper. All works, except when the value being pulled isn't there, which results in value: None. Then, I get this ValueError: 'date' needs to be str error. How to fix? I've added str(year) which fixed it. def write_tag_data(flacfile, style, year): audio = FLAC(flacfile) audio['genre'] = style audio['date'] = str(year) audio.save()
score: -1
type: Question
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/51485960
has answer: http://stackoverflow.com/a/51482870
tagged with: string
has comment: http://stackoverflow.com/comment/89934177
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/90228712
comment on: http://stackoverflow.com/a/51625757
score: 0
type: AnswerComment
type: Comment
has text: Thank you for your help once again. I've read chapter about classes and things are more clear now, but I still have some questions about the code you wrote. I don't understand what does ` super().__init__(x, y, w, h)` do. And why do I need `self.vel = vel` in rectangle class if I am using special velocity for moving rectangles. vel is only for my rectangle that I am controlling or?

http://stackoverflow.com/q/51503913
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51511050
has body: When I use pipreqs, I have this problem. I use anaconda and Russian Windows. root@DESKTOP-ETLLRI1 C:\Users\root\Desktop\resumes $ pipreqs C:\Users\root\Desktop\resumes Traceback (most recent call last): File "C:\Users\root\Anaconda3\Scripts\pipreqs-script.py", line 9, in <module> sys.exit(main()) File "C:\Users\root\Anaconda3\lib\site-packages\pipreqs\pipreqs.py", line 396, in main init(args) File "C:\Users\root\Anaconda3\lib\site-packages\pipreqs\pipreqs.py", line 341, in init extra_ignore_dirs=extra_ignore_dirs) File "C:\Users\root\Anaconda3\lib\site-packages\pipreqs\pipreqs.py", line 75, in get_all_imports contents = f.read() File "C:\Users\root\Anaconda3\lib\encodings\cp1251.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 1206: character maps to <undefined>
tagged with: python
type: AnsweredQuestion
type: Question
upvote count: 40
has title: Pipreqs: UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 1206: character maps to <undefined>
tagged with: anaconda
has answer: http://stackoverflow.com/a/51511050
tagged with: python-unicode
tagged with: character-encoding
score: 40

http://stackoverflow.com/comment/122183964
type: Comment
has text: It is an "elif" condition and 2 more lines on the code above. One should be able to that on their own. (I won't be updatinbg the answer now, but I might rewrite this code as a gist so it works with lists)
comment on: http://stackoverflow.com/a/51565863
type: AnswerComment
score: 0

http://stackoverflow.com/q/51547168
has answer: http://stackoverflow.com/a/51548424
has comment: http://stackoverflow.com/comment/90062607
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90064770
type: Question
answer count: 2
has body: I have two dataframes that I want to join based on a relationship described in a dictionary of lists, where the keys in the dictionary refer to ids from dfA idA column, and the items in the list are ids from dfB idB column. The dataframes and dictionary look something like this: dfA colA colB idA 0 a abc 3 1 b def 4 2 b ghi 5 dfB colX idB colZ 0 bob 7 a 1 bob 7 b 2 bob 7 c 3 jim 8 d 4 jake 9 a 5 jake 9 e myDict = { '3': [ '7', '8' ], '4': [], '5': ['7', '9'] } How can I use myDict to join the two dataframes to produce a dataframe like the following? dfC colA colB idA colX idB colZ 0 a abc 3 bob 7 a 1 b 2 c 3 jim 8 d 4 b def 4 None None None 5 b ghi 5 bob 7 a 6 b 7 c 8 jake 9 a 9 e
has answer: http://stackoverflow.com/a/51548700
has comment: http://stackoverflow.com/comment/90063792
has comment: http://stackoverflow.com/comment/90085036
favorite count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/90064382
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51548424
tagged with: python
possible better answer: http://stackoverflow.com/a/51548700
has comment: http://stackoverflow.com/comment/90063732
has comment: http://stackoverflow.com/comment/90062406
has title: Pandas join two dataframes based on relationship described in dictionary
has comment: http://stackoverflow.com/comment/90098433

http://stackoverflow.com/q/51549941
tagged with: python
type: AnsweredQuestion
has title: Relative import beyond top-level package Error
score: 1
upvote count: 1
has body: I have a project named tweetme which has two apps account and tweets,i have serializers.py file in both of the apps to serialize data. So when i try to relative import the serializer class from account/api/serializers.py to another app tweets/api/serializers.py, the relative import shows error. 1- 1st i tried full path from src.account.api.serializers import UserDisplaySerializer, it gave error in console that ModuleNotFoundError: No module named 'src' 2- Then i tried from ...account.api.serializers import UserDisplaySerializer,its showing error ValueError: attempted relative import beyond top-level package. So what am i doing wrong? How to do relative import properly? @edit adding init.py in src Directory: D:\django\tweetme\src Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 26-07-2018 23:56 account d----- 25-07-2018 13:56 static-storage d----- 25-07-2018 19:06 template d----- 26-07-2018 19:39 tweetme d----- 26-07-2018 10:54 tweets -a---- 25-07-2018 20:17 143360 db.sqlite3 -a---- 13-07-2018 22:40 554 manage.py -a---- 27-07-2018 08:34 0 __init__.py Still same error persisting... [![User Serializer class in account app][4]][4]
type: Question
has comment: http://stackoverflow.com/comment/90067622
has comment: http://stackoverflow.com/comment/90067670
has comment: http://stackoverflow.com/comment/90067683
has comment: http://stackoverflow.com/comment/90067504
has comment: http://stackoverflow.com/comment/90067563
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90067977
tagged with: django-rest-framework
favorite count: 0
has answer: http://stackoverflow.com/a/51550097
accepted answer: http://stackoverflow.com/a/51550097
has comment: http://stackoverflow.com/comment/90068610
tagged with: django

http://stackoverflow.com/a/51606493
accepted answer of: http://stackoverflow.com/q/51603299
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90209078
downvote count: 0
answers question: http://stackoverflow.com/q/51603299
type: Answer
has body: If you have your positional arguments in a sequence, just use the * operator to unpack them into function's positional arguments. _oids = ('1.3.6.1.2.1.1.1.0', '1.3.6.1.2.1.1.4.0', '1.3.6.1.2.1.1.5.0', '1.3.6.1.2.1.1.6.0') cmdGen.getCmd( cmdgen.UsmUserData( user, authKey=authKe, privKey=privKe, authProtocol=authProto, privProtocol=privProto ), cmdgen.UdpTransportTarget((sHost, 161)), *[ObjectType(ObjectIdentity(oid)) for oid in _oids] )
score: 2

http://stackoverflow.com/a/51544787
score: 0
answers question: http://stackoverflow.com/q/51544130
has comment: http://stackoverflow.com/comment/90057889
type: Answer
has comment: http://stackoverflow.com/comment/90058219
has body: use dask instead, its has similar syntax to pandas only its parallel (essentially its lots of parallel pandas datafames) and lazy (this helps with avoiding ram limitations). if the files you are extracting are for example of type csv, do this: from dask.distributed import Client import dask.dataframe as dd client = Client() # ensures multiprocessing ddf = dd.read_csv(r'sub\**\*.csv') # reads all the csv files inside of the subdirectories of the subdirectories if the files are of a different type and pandas can read them dask most likely can also read them. for xml it would look something like this: import dask from glob import iglob @dask.delayed # this function will now run via the multiprocessing client def work(files_path): df_local = function_which_returns_dataframe(files_path) if not df_local.empty: return df_local else: print("Empty:", files_path) client = Client() # ensures multiprocessing files_paths = iglob(r'sub\**\*.xml') # an iterator of all the xml file paths # read lazily all the xml files delayed_objs = (work(files_path) for files_path in files_paths) ddf = dd.from_delayed(delayed_objs) # combine to one dataframe I suggest you read this and provide a meta to from_delayed if you wish to turn ddf to a pandas.DataFrame simply do this: df = ddf.compute()
has comment: http://stackoverflow.com/comment/90058154

http://stackoverflow.com/q/51578978
type: Question
has comment: http://stackoverflow.com/comment/90129921
has comment: http://stackoverflow.com/comment/90124364
answer count: 1
tagged with: javascript
has comment: http://stackoverflow.com/comment/90129635
score: 0
has comment: http://stackoverflow.com/comment/90129638
has body: I have a django application that is successfully able to signup and login a user.However I am unable to logout a user. In the front end, I have a webpage that contains a power button icon, which on clicking should trigger a logout request. I am using angular js for front end index.html &lt;div class="col-xs-2"&gt; &lt;span style="opacity: 0.5;font-family: FontAwesome;font-size: 14px;color:#838F98;text-align:center;cursor:pointer" ng-click="logout()"&gt; &lt;i class="fa fa-power-off" aria-hidden="true"&gt;&lt;/i&gt; &lt;/span&gt; &lt;/div&gt; Here I use ngclick to call the logout() function that is defined in my index.js index.js $scope.logout = function() { var url = '/logout'; var toSend = { username: username_id, } $http({ method: 'POST', url: url, data: toSend, }).then(function(response) { response.data; }) }; This function calls the /logout url for which I have defined an auth views in urls.py urls.py from django.contrib.auth.views import login, logout url(r'^logout$', logout, {'template_name': 'login.html'}), But when I click the power icon on the webpage, nothing happens.The user stays in the page and I don't event get any error message. What am I doing wrong? UPDATE Ok I changed the Javascript POST call to the /logout url to a GET call and it seems to work.However the page doesn't redirect to the login.html page and stays on the same page.If I close the tab and reopen it, it asks for login again which means the logout works now.But why doesn't it redirect to the login page and just stays there?
tagged with: angularjs
has comment: http://stackoverflow.com/comment/90130430
has answer: http://stackoverflow.com/a/51583300
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90123349
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90123285
has title: Django doesn't logout a user
has comment: http://stackoverflow.com/comment/90123280

http://stackoverflow.com/a/51615961
has body: if you want to create a flag column, you can try substring: import pyspark.sql.functions as F df=df.withColumn('flag', F.substring(df.columnName,1,1).isin(['W', 'I', 'E', 'U']) it checks the first letter only. But you can discard creating a new column and directly filter rows: df=df.filter(F.substring(df.columnName,1,1).isin(['W', 'I', 'E', 'U']==False)
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51608432
type: Answer
answers question: http://stackoverflow.com/q/51608432

http://stackoverflow.com/q/51588754
answer count: 2
favorite count: 0
has body: I need to filter only the word which is "shutdown" alone. Its mentioned in seperate line. But also its available in between different line as well. i have used this filter "^shutdown" and "^(shutdwon)", its not helping me. I am using python program to filter. ! interface GigabitEthernet5/19 switchport access vlan 102 switchport mode access switchport voice vlan 100 qos trust device cisco-phone ! interface GigabitEthernet5/20 ! interface GigabitEthernet5/21 description Test AP 335 switchport access vlan 999 switchport mode access shutdown spanning-tree portfast ! interface GigabitEthernet5/22 ! interface GigabitEthernet5/23 switchport access vlan 102 switchport shutdown mode access switchport voice vlan 100 shutdown
tagged with: python
has comment: http://stackoverflow.com/comment/90144045
tagged with: regex
possible better answer: http://stackoverflow.com/a/51589429
downvote count: 4
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/90142994
score: -4
type: Question
has comment: http://stackoverflow.com/comment/90142845
has answer: http://stackoverflow.com/a/51589285
accepted answer: http://stackoverflow.com/a/51589285
has comment: http://stackoverflow.com/comment/90142684
has title: Python Regex: Identify the first name
has answer: http://stackoverflow.com/a/51589429

http://stackoverflow.com/q/51566069
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
tagged with: ctypes
upvote count: 3
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51566158
accepted answer: http://stackoverflow.com/a/51566158
answer count: 1
favorite count: 0
has body: From what I understand about Python's ctypes, ctypes.sizeof(...) should return the size, in bytes, of the structure passed in, as if using C's sizeof operator. However, I always get 0 as a result: $ python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import ctypes &gt;&gt;&gt; class testStruct(ctypes.Structure): ... _fields = [ ... ("testField", ctypes.c_uint*4) ... ] ... &gt;&gt;&gt; ctypes.sizeof(testStruct) 0 &gt;&gt;&gt; test = testStruct() &gt;&gt;&gt; ctypes.sizeof(test) 0 Why is this happening?
has title: Python ctypes.sizeof(...) always returns 0

http://stackoverflow.com/q/51563007
has answer: http://stackoverflow.com/a/61027090
tagged with: mongoengine
type: Question
tagged with: mongodb
answer count: 1
downvote count: 0
has body: I want to use mongoengine with flask define two documents, user contains following topics and topic contains publish user. I define User document in user.py and Topic document in topic.py. Only in topic.py I import User clakk, in user.py I don't import Topic class in order to avoid import loop. user.py: class User(Document): username = StringField(unique=True, required=True) following_topics = ListField(ReferenceField('Topic', reverse_delete_rule=PULL, unique=True)) topic.py: from user import User class Topic(Document, ModelMixin): title = StringField(default='') user = ReferenceField(User, required=True) But when I start flask, there exits a error, how do i fix? mongoengine.errors.NotRegistered: `Topic` has not been registered in the document registry. Importing the document class automatically registers it, has it been imported?
tagged with: flask
tagged with: python
favorite count: 0
has title: mongoengine with flask 'mongoengine.errors.NotRegistered' issue
score: 2
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/103238817

http://stackoverflow.com/a/52093118
score: 2
has comment: http://stackoverflow.com/comment/91500707
upvote count: 2
has comment: http://stackoverflow.com/comment/91176564
has body: R has one function t.test() to perform the Student's T test, while Python employs more methods. If you want to perform a one sample t-test with mu as the true mean μ of the population from which the data is sampled, you should use scipy.stats.ttest_1samp and pass the parameter through popmean. Docs are here. If you want to perform a two sample t-test with mu as the difference in means, statsmodels.stats.weightstats.ttest_ind from the statsmodels module is the right function, with mu passed through value. Docs are here, as well as a link to a useful answer. Other links you may find useful are these: https://plot.ly/python/t-test/ - T-tests with plotly https://towardsdatascience.com/inferential-statistics-series-t-test-using-numpy-2718f8f9bf2f T-test using Python and Numpy https://pythonfordatascience.org/independent-t-test-python/ - T-test | Python for Data Science
has comment: http://stackoverflow.com/comment/91459506
has comment: http://stackoverflow.com/comment/95239650
has comment: http://stackoverflow.com/comment/91459489
has comment: http://stackoverflow.com/comment/91236873
has comment: http://stackoverflow.com/comment/91501444
downvote count: 0
has comment: http://stackoverflow.com/comment/101037209
has comment: http://stackoverflow.com/comment/91500043
type: Answer
has comment: http://stackoverflow.com/comment/91180772
answers question: http://stackoverflow.com/q/51536111

elementtree
tags question: http://stackoverflow.com/q/51488156
type: Tag
tags question: http://stackoverflow.com/q/51532300
tags question: http://stackoverflow.com/q/51544389
tags question: http://stackoverflow.com/q/51613290
tag name: elementtree
tags question: http://stackoverflow.com/q/51544765
tags question: http://stackoverflow.com/q/51604532
tags question: http://stackoverflow.com/q/51546336
tags question: http://stackoverflow.com/q/51497810
tags question: http://stackoverflow.com/q/51626950

http://stackoverflow.com/comment/90092021
has text: Yes, you're right, I deleted it. But how about my issue?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51561450
type: QuestionComment

http://stackoverflow.com/comment/90065664
type: QuestionComment
comment on: http://stackoverflow.com/q/51548928
score: 1
has text: Is your default shell actually bash?
type: Comment

http://stackoverflow.com/comment/90120285
has text: No, when i upload multiple images through browse button, hotel_main_img contains multiple images in it, its working, but not working through html upload photos button, how can i make that?
type: Comment
comment on: http://stackoverflow.com/a/51576728
score: 0
type: AnswerComment

http://stackoverflow.com/a/51613235
upvote count: 2
has comment: http://stackoverflow.com/comment/90194640
has comment: http://stackoverflow.com/comment/90192691
has comment: http://stackoverflow.com/comment/90195139
answers question: http://stackoverflow.com/q/51613034
has comment: http://stackoverflow.com/comment/90193185
has comment: http://stackoverflow.com/comment/90192271
downvote count: 0
has body: This is the most portable solution. A more difficult one is sketched below for PyCharm. Kind of depends on the debugger, but if you use pdb (which would be cross platform), the docs state: The typical usage to break into the debugger from a running program is to insert import pdb; pdb.set_trace() you want this to be conditional, so you can paste at each breakpoint: try: pdb.set_trace() except NameError: pass and when you want to debug just import pdb at the top. If it must be one line you cannot use duck typing. Instead: if 'pdb' in globals(): pdb.set_trace() PyCharm only Assuming you insist on not marking debugging lines with the mouse this might work: Using exception breakpoints: PyCharm provides exception breakpoints for Python, Django, and JavaScript. Exception breakpoints are triggered when the specified exception is thrown. Unlike the line breakpoints, which require specific source references, exception breakpoints apply globally to the exception condition, rather than to a particular code reference. Depending on the type of processing an exception, the debugging can break when a process terminates with an exception, or as soon as an exception occurs. You could: Create a custom exception in your project, DebugException Set the exception breakpoint as per the link above. Make sure it is set to trigger immediately, not when program exits. Finally, paste try: raise DebugException() Exception: pass wherever you want to break. This seems like a lot of trouble to not double click with your mouse to mark a breakpoint.
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90194815

http://stackoverflow.com/comment/90066457
score: 2
has text: How do you know your data is space-delimited? Have you opened your data and looked at? Your traceback seems to think you don't have any data.
type: QuestionComment
comment on: http://stackoverflow.com/q/51549448
type: Comment

http://stackoverflow.com/comment/89938349
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51484497
has text: how do you rename the files like what is seen in the output? I got it to print to screen the way I wanted them to, but I can't figure out how to actually rename them.
score: 0

http://stackoverflow.com/comment/117222131
type: Comment
has text: Shouldn't that be `client[<database-name>][<collection-name>].insert(<document>);` ?
score: 1
comment on: http://stackoverflow.com/a/51489185
type: AnswerComment

http://stackoverflow.com/q/51637374
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90239135
tagged with: dynamic
score: 1
has comment: http://stackoverflow.com/comment/105926002
type: Question
has title: Python: Dynamic instantiation
has answer: http://stackoverflow.com/a/51637664
accepted answer: http://stackoverflow.com/a/51637664
answer count: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90239353
downvote count: 0
tagged with: python
has body: I need to make the usage of an object variable to cut way down on lines of code and complexity. Here's the code I'm about to use: exchange = ccxt.binance({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', 'enableRateLimit': True, }) I need to make the binance part dynamic since there's probably a few hundred different things that could be in this case. Is there an easy way to do that? Thanks in advance.
tagged with: instantiation

http://stackoverflow.com/a/73775360
has body: You should write the config lines manually like that : tesseract input_image out -c tessedit_create_tsv=1 -c tessedit_create_txt=1
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51533254
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/137174266

http://stackoverflow.com/q/51504938
has answer: http://stackoverflow.com/a/51505101
has answer: http://stackoverflow.com/a/51505467
type: Question
has comment: http://stackoverflow.com/comment/89978768
has title: Python - append() operation in list comprehension resulting in memory balloon
has comment: http://stackoverflow.com/comment/89978797
tagged with: python-3.x
score: 0
accepted answer: http://stackoverflow.com/a/51505053
has comment: http://stackoverflow.com/comment/89979029
possible better answer: http://stackoverflow.com/a/51505120
tagged with: python
has comment: http://stackoverflow.com/comment/89979159
has answer: http://stackoverflow.com/a/51505120
has comment: http://stackoverflow.com/comment/89979030
has body: Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux 2 GB RAM, 4 GB Swap ---- import re fieldname_groups = ("(ip,clienthost,ip_addr)", "(username,user,id)") srcgroup = [x.strip() for x in re.sub('[\(\)]+', '', fieldname_groups[0]).split(',')] dstgroup = [x.strip() for x in re.sub('[\(\)]+', '', fieldname_groups[1]).split(',')] if not srcgroup or not dstgroup: raise Exception("No srcgroup or dstgroup specified!") # srcgroup is now ['ip', 'clienthost', 'ip_addr'] # dstgroup is now ['username', 'user', 'id'] # Now append the string '.keyword' to a copy of every string in each list [srcgroup.append('%s.keyword' % x) for x in srcgroup] [dstgroup.append('%s.keyword' % x) for x in dstgroup] # srcgroup should now be ['ip', 'clienthost', 'ip_addr', 'ip.keyword', 'clienthost.keyword', 'ip_addr.keyword'] # dstgroup should be similar Every time I run this code, once I hit the list comprehensions the memory balloons up and the process is killed. I'm not understanding what the problem is here; I feel like this is something I do all the time yet this time it's not working, so it's probably an amateur mistake but I'd appreciate any help in sorting it out. I've even tried rewriting the code to use a standard for loop but it still explodes. Thanks!
has comment: http://stackoverflow.com/comment/89979730
answer count: 5
has comment: http://stackoverflow.com/comment/89978963
type: AnsweredQuestion
tagged with: python-3.5
has answer: http://stackoverflow.com/a/51505053
has answer: http://stackoverflow.com/a/51505045

http://stackoverflow.com/comment/89949431
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51490454
has text: 500 error code represents an error in the server-side code. Check the logs, and post the relevant excerpts from it, which you cannot understand.

http://stackoverflow.com/comment/90143014
type: Comment
comment on: http://stackoverflow.com/q/51588759
type: QuestionComment
has text: You can avoid introducing a python variable `x` and simply use `k.subs('x', 0)`.
score: 0

http://stackoverflow.com/comment/90134355
comment on: http://stackoverflow.com/a/51583925
type: AnswerComment
score: 0
type: Comment
has text: Thank you for the answer. I am noticing that for groups that have no non-zero values(all of them are 0s in `Value` column), `NewCol` shows a 1 for the first element. How do I show zeroes for all elements if there are no non-zero element?

http://stackoverflow.com/q/51620173
tagged with: mysql-python
tagged with: python
has comment: http://stackoverflow.com/comment/90212978
has comment: http://stackoverflow.com/comment/90234295
has body: I get the following error: _mysql_exceptions.ProgrammingError: (1146, "Table 'test.imageupload' doesn't exist") The database and table are there. I have dropped and created them again. I have also tried restarting the server. Nothing seems to work. db = MySQLdb.connect(host="localhost", # your host, usually localhost user="root", # your username passwd=" ", # your password db="test") # name of the data base cur = db.cursor() cur.execute("""INSERT INTO imageupload (uid, image_path,image_name) values (%s,%s,%s)""", (122, "kkk", "lll")) db.commit() db.close()
has title: MySQL/Python - MySQLdb does not recognise table
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90232730
tagged with: mysql
has answer: http://stackoverflow.com/a/51620218
answer count: 1
has comment: http://stackoverflow.com/comment/90234628
score: 0

http://stackoverflow.com/comment/90228126
score: 0
type: AnswerComment
type: Comment
has text: thanks! in `both = (dg[dg == se])`, how can `0-30` have a value of 1.0? That would imply that both columns have all values between `0-30` (which is not the case)
comment on: http://stackoverflow.com/a/51631883

http://stackoverflow.com/q/51607349
has comment: http://stackoverflow.com/comment/90179934
tagged with: distutils
tagged with: python
has comment: http://stackoverflow.com/comment/90461069
has title: Creating a python module for distribution from a single shared library file
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90210431
has comment: http://stackoverflow.com/comment/90409127
linked to: http://stackoverflow.com/q/37316177
score: 2
has comment: http://stackoverflow.com/comment/90433624
has body: I have a shared library that I have created using pybind11. called dddd.so when I open python and type import dddd print(dddd.test_function()) I get my desired result, and that's fantastic. However, my goal is to create a conda installable package, so that I could create a conda environment, and then type: conda install dddd And have that work. So I am trying to create a setup.py file that will allow me to create this using python setup.py bdist or python setup.py bdist_conda I have not been able to get my shared library to go into a bdist module. My directory structure at the moment is dddd/ - dddd/ -dddd.so -__init__.py setup.py I have tried a lot of things, including Distribute a Python package with a compiled dynamic shared library , but I have not been able to get it to work. When I try this as my setup.py: from distutils.core import setup setup( name='dddd', version='0.2', packages=['dddd'], package_dir={'dddd': 'dddd'}, package_data={'dddd': ['dddd.so']}, ) I am able to get python setup.py bdist_conda to work. However when I run this conda module, my module can now not be directly accessed, I have to do: import dddd.dddd dddd.dddd.test_function() Which is not what I want. I can't seem to achieve what was achieved in the answer in my link.
type: Question
has comment: http://stackoverflow.com/comment/90211590
downvote count: 0
has comment: http://stackoverflow.com/comment/90212398
has comment: http://stackoverflow.com/comment/90211529
favorite count: 0
has comment: http://stackoverflow.com/comment/90189789

http://stackoverflow.com/comment/90207986
comment on: http://stackoverflow.com/q/51619188
type: QuestionComment
score: 0
type: Comment
has text: MandyShaw - thanks very much for pointing out the error. I have corrected this, but the problem remains.

http://stackoverflow.com/comment/90130317
type: Comment
type: QuestionComment
has text: That's the problem.. I get none. Nothing happens ( but there is a laps of 1 second ).
comment on: http://stackoverflow.com/q/51582331
score: 0

http://stackoverflow.com/comment/90164855
type: Comment
comment on: http://stackoverflow.com/a/51599145
score: 0
type: AnswerComment
has text: So where exactly did I convert it a second time? Sorry I am confused thank you for sticking with me

http://stackoverflow.com/comment/116547501
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/55099349
has text: And why did you import print?

http://stackoverflow.com/q/51524514
tagged with: python
has answer: http://stackoverflow.com/a/51524815
has comment: http://stackoverflow.com/comment/90017864
has comment: http://stackoverflow.com/comment/90018191
type: Question
has title: Why does python hang in virtualenv?
has body: I'm using a virtualenv from within a Cygwin terminal on a Windows machine. When I haven't activated the virtualenv, I can run $ python to start up a python shell fine. I can also run scripts via $ python my_script.py fine within the virtualenv, but as soon as I try to start up a python shell in the virtual environment directly, it hangs indefinitely. $ virtualenv --version 15.2.0 $ python --version Python 2.7.13 $ which python /usr/bin/python (virtualenv) $ python --version Python 2.7.9 (virtualenv) $ which python /path/to/virtualenv/dir/Scripts/python (virtualenv) $ python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # C:\Users\WiegreS\test_project\test\lib\site.pyc matches C:\Users\WiegreS\test_project\test\lib\site.py import site # precompiled from C:\Users\WiegreS\test_project\test\lib\site.pyc # C:\Users\WiegreS\test_project\test\lib\os.pyc matches C:\Users\WiegreS\test_project\test\lib\os.py import os # precompiled from C:\Users\WiegreS\test_project\test\lib\os.pyc import errno # builtin import nt # builtin # C:\Users\WiegreS\test_project\test\lib\ntpath.pyc matches C:\Users\WiegreS\test_project\test\lib\ntpath.py import ntpath # precompiled from C:\Users\WiegreS\test_project\test\lib\ntpath.pyc # C:\Users\WiegreS\test_project\test\lib\stat.pyc matches C:\Users\WiegreS\test_project\test\lib\stat.py import stat # precompiled from C:\Users\WiegreS\test_project\test\lib\stat.pyc # C:\Users\WiegreS\test_project\test\lib\genericpath.pyc matches C:\Users\WiegreS\test_project\test\lib\genericpath.py import genericpath # precompiled from C:\Users\WiegreS\test_project\test\lib\genericpath.pyc # C:\Users\WiegreS\test_project\test\lib\warnings.pyc matches C:\Users\WiegreS\test_project\test\lib\warnings.py import warnings # precompiled from C:\Users\WiegreS\test_project\test\lib\warnings.pyc # C:\Users\WiegreS\test_project\test\lib\linecache.pyc matches C:\Users\WiegreS\test_project\test\lib\linecache.py import linecache # precompil…
score: 0
answer count: 1
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/90018208
has comment: http://stackoverflow.com/comment/90018114
has comment: http://stackoverflow.com/comment/90017840
type: UnansweredQuestion

http://stackoverflow.com/comment/90040826
type: QuestionComment
comment on: http://stackoverflow.com/q/51536508
has text: Thanks for the notice. updated it. Do you know how to get the needed result though?
score: 0
type: Comment

http://stackoverflow.com/q/51623320
tagged with: beautifulsoup
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51648999
tagged with: python
has title: Find specific comments Entries in HTML code using python BeautifulSoup
tagged with: html-parsing
type: Question
has body: I am trying to parse the specific entries from the comments session from HTML. I am trying to use BeautifulSoup to do it. I get stuck after I was able to extract the comment part. Here's an example: example import urllib import sys from bs4 import BeautifulSoup, Comment soup = BeautifulSoup(open("test.html"), 'html.parser') comments = soup.findAll(text=lambda text:isinstance(text, Comment)) Do you guys know how can I get the correct info? Appreciate it!!
tagged with: comments
has comment: http://stackoverflow.com/comment/90247222
score: 0
has comment: http://stackoverflow.com/comment/90212354
answer count: 1

http://stackoverflow.com/a/51554293
answers question: http://stackoverflow.com/q/51554088
has comment: http://stackoverflow.com/comment/90075532
score: 0
has body: You are probably using wrong decimal separator on input. Perhaps comma "," instead of full stop "." You need to replace that or catch the error (or both together). I suggest: try: centimetre = float(centimetre.replace(',', '.')) except ValueError: print('Input is not a valid number or in invalid format!')
type: Answer

http://stackoverflow.com/q/51639115
score: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90292944
tagged with: php
type: Question
has title: Python - how to send IP address to PHP?
tagged with: zend-framework
has body: Why isn't Python sending the IP address to PHP? Python always telling me that result=fail instead of OK - working Python: import requests; r = requests.post('https://stackoverflow.com/unittest', data = { 'test' : 'test' } ); r.content; // fail PHP: public static function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } public function unittestAction() { $this-&gt;_response-&gt;setHeader('Access-Control-Allow-Origin', '*'); $this-&gt;_helper-&gt;layout()-&gt;disableLayout(); $this-&gt;_helper-&gt;viewRenderer-&gt;setNoRender(); $post = $this-&gt;getRequest()-&gt;getPost(); $data = (object) $post; $db = Application_Model_Db::db_load(); $request_IP = self::getRealIpAddr(); $sql = "SELECT * FROM `sh_av_site_iptable` WHERE ip='{$request_IP}' limit 1"; $result = $db-&gt;fetchAll($sql); if (count($result) &gt; 0) { } else { $json = array( 'result' =&gt; 'fail', 'reason' =&gt; '???? i dont know your IP, get out of my door, thank you spammer ????' ); $content = Zend_Json::encode($json); $this-&gt;getResponse() -&gt;setHeader('Content-Type', 'application/json') -&gt;setBody($content) -&gt;sendResponse(); exit; } echo "OK - working"; exit; }
has comment: http://stackoverflow.com/comment/90242719

http://stackoverflow.com/q/51557271
type: Question
tagged with: duplicates
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90082176
has comment: http://stackoverflow.com/comment/90081301
has title: Python: Efficient looping in dataframe to find duplicates for multiple columns
score: 0
has comment: http://stackoverflow.com/comment/90081954
tagged with: pandas
answer count: 1
has body: I am using python and I want to go through a dataset and highlight the most used locations. This is my dataset (but with 300,000+ records): Longitude Latitude 14.28586 48.3069 14.28577 48.30687 14.28555 48.30678 14.28541 48.30673 First I add a density column: df['Density'] = 0 And this is the code that I am using to increase the density value for each record: for index in range(0,len(df)): for index2 in range(index + 1, len(df)): if df['Longitude'].loc[index] == df['Longitude'].loc[index2] and df['Latitude'].loc[index] == df['Latitude'].loc[index2]: df['Density'].loc[index] += 1 df['Density'].loc[index2] += 1 print("match") print(str(index) + "/" + str(len(df))) The code above is simply iterating through the dataframe, comparing the first record against all the other records in the dataset (inner loop) and when a match is found both of their density values are incremented. I want to find the Longitudes and Latitudes that match and increase their density value. The code is obviously very slow and I am sure that Python will have a cool technique for doing something like this, any ideas?
has comment: http://stackoverflow.com/comment/90082294
has answer: http://stackoverflow.com/a/51557865
tagged with: python
has comment: http://stackoverflow.com/comment/90081559
type: AnsweredQuestion
tagged with: loops
accepted answer: http://stackoverflow.com/a/51557865

http://stackoverflow.com/comment/90212424
has text: This is the error I get when I run that: Traceback (most recent call last): File "sublap_finder_updated.py", line 28, in <module> findNearestRegion = KDTree(zip(lat_s, lon_s)).query File "/Users/nalin/anaconda3/lib/python3.6/site-packages/scipy/spatial/kdtree.py", line 235, in __init__ self.n, self.m = np.shape(self.data) ValueError: not enough values to unpack (expected 2, got 0)
type: AnswerComment
comment on: http://stackoverflow.com/a/51623189
score: 0
type: Comment

django
tags question: http://stackoverflow.com/q/51574501
tags question: http://stackoverflow.com/q/51485063
tags question: http://stackoverflow.com/q/51538588
tags question: http://stackoverflow.com/q/51520535
tags question: http://stackoverflow.com/q/51636423
tags question: http://stackoverflow.com/q/51605360
tags question: http://stackoverflow.com/q/51586393
tags question: http://stackoverflow.com/q/51577441
tags question: http://stackoverflow.com/q/51524567
tags question: http://stackoverflow.com/q/51570681
tags question: http://stackoverflow.com/q/51522826
tags question: http://stackoverflow.com/q/51636190
tags question: http://stackoverflow.com/q/51599532
tags question: http://stackoverflow.com/q/51572059
tags question: http://stackoverflow.com/q/51636195
tags question: http://stackoverflow.com/q/51584556
tags question: http://stackoverflow.com/q/51521075
tags question: http://stackoverflow.com/q/51596433
tags question: http://stackoverflow.com/q/51498016
tags question: http://stackoverflow.com/q/51578636
tags question: http://stackoverflow.com/q/51505989
tags question: http://stackoverflow.com/q/51501231
tags question: http://stackoverflow.com/q/51571940
tags question: http://stackoverflow.com/q/51520564
tags question: http://stackoverflow.com/q/51607214
tags question: http://stackoverflow.com/q/51518733
tags question: http://stackoverflow.com/q/51549941
tags question: http://stackoverflow.com/q/51501111
tags question: http://stackoverflow.com/q/51548871
tags question: http://stackoverflow.com/q/51551402
tags question: http://stackoverflow.com/q/51621957
tags question: http://stackoverflow.com/q/51551135
tags question: http://stackoverflow.com/q/51575053
tags question: http://stackoverflow.com/q/51526849
tags question: http://stackoverflow.com/q/51542243
tags question: http://stackoverflow.com/q/51514481
tags question: http://stackoverflow.com/q/51507794
tags question: http://stackoverflow.com/q/51618685
tags question: http://stackoverflow.com/q/51603358
tags question: http://stackoverflow.com/q/51552100
tags question: http://stackoverflow.com/q/51591659
tags question: http://stackoverflow.com/q/51619976
tags question: http://stackoverflow.com/q/51577929
tags question: http://stackoverflow.com/q/51603430
tags question: http://stackoverflow.com/q/51518894
tags question: http://stackoverflow.com/q/51491745
tags question: http://stackoverflow.com/q/51544703
tags question: http://stackoverflow.com/q/51580885
tags question: http://stackoverflow.com/q/51603888
tags question: http://stackoverflow.com/q/51528096
tags question: http://stackoverflow.com/q/51509833
tags question: http://stackoverflow.com/q/51530276
tags question: http://stackoverflow.com/q/51576868
tags question: http://stackoverflow.com/q/51510690
tags question: http://stackoverflow.com/q/51599979
tags question: http://stackoverflow.com/q/51509710
tags question: http://stackoverflow.com/q/51605064
tags question: http://stackoverflow.com/q/51488313
tags question: http://stackoverflow.com/q/51506025
type: Tag
tags question: http://stackoverflow.com/q/51517349
tags question: http://stackoverflow.com/q/51563692
tags question: http://stackoverflow.com/q/51543105
tags question: http://stackoverflow.com/q/51504144
tags question: http://stackoverflow.com/q/51530835
tags question: http://stackoverflow.com/q/51555207
tags question: http://stackoverflow.com/q/51637070
tags question: http://stackoverflow.com/q/51588913
tags question: http://stackoverflow.com/q/51562870
tags question: http://stackoverflow.com/q/51572708
tags question: http://stackoverflow.com/q/51540598
tags question: http://stackoverflow.com/q/51558265
tags question: http://stackoverflow.com/q/51631651
tags question: http://stackoverflow.com/q/51636721
tags question: http://stackoverflow.com/q/51583268
tags question: http://stackoverflow.com/q/51578978
tags question: http://stackoverflow.com/q/51573619
tags question: http://stackoverflow.com/q/51529286
tags question: http://stackoverflow.com/q/51568544
tags question: http://stackoverflow.com/q/51583196

http://stackoverflow.com/q/51573941
upvote count: 6
type: AnsweredQuestion
tagged with: autocomplete
has body: I use VS Code v1.25.1 with the Python extension added. Although it suggests me the attributes and methods of libraries and classes, i.e. I type from sklearn. it makes suggestions like ensemble, exception etc., when I generate a numpy array x_data = np.linspace(0.0, 10.0, 1000000) and on the next line say I would like to use a method or an attribute such as argmax it does not show me the suggestion list after typing x_data.. In Jupyter Notebook I used to press tab after typing x_data. to see the list. I wonder if there is any shortcut to achieve the same.
tagged with: code-complete
has answer: http://stackoverflow.com/a/61142845
type: Question
tagged with: visual-studio-code
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/61142845
tagged with: python
has title: Visual Studio Code Does Not Suggest Python Object Attributes
favorite count: 0
score: 6

http://stackoverflow.com/a/51638276
has comment: http://stackoverflow.com/comment/90250776
has comment: http://stackoverflow.com/comment/90241238
has comment: http://stackoverflow.com/comment/90241076
has comment: http://stackoverflow.com/comment/90265913
has body: You can wrap arbitrary tensorflow functions in a keras Lambda layer and add them to your model. Minimal working example from this answer: import tensorflow as tf from keras.layers import Dense, Lambda, Input from keras.models import Model W = tf.random_normal(shape=(128,20)) b = tf.random_normal(shape=(20,)) inp = Input(shape=(10,)) x = Dense(128)(inp) # Custom linear transformation y = Lambda(lambda x: tf.matmul(x, W) + b, name='custom_layer')(x) model = Model(inp, y)
has comment: http://stackoverflow.com/comment/90241120
upvote count: 5
has comment: http://stackoverflow.com/comment/90244658
has comment: http://stackoverflow.com/comment/90241158
accepted answer of: http://stackoverflow.com/q/51638053
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51638053
downvote count: 0
has comment: http://stackoverflow.com/comment/90240978
score: 5
type: Answer

http://stackoverflow.com/comment/90214525
type: Comment
comment on: http://stackoverflow.com/a/51624703
type: AnswerComment
has text: Thank you because I just affraid might cause some problem just like the visual studio one. Anyway, thank you for your answer.
score: 0

http://stackoverflow.com/comment/90209895
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51621752
score: 0
has text: @UnknownProgrammer Something is wrong with your PHP deployment or you copy/pasted incorrectly. `var_dump` of `"picture matched"` is 15 characters, not 16, and no space/new line. https://3v4l.org/DPAmJ

http://stackoverflow.com/comment/90033934
score: 0
type: Comment
has text: @joe: 4!. Generate all permutations which start with `1` (i.e. generate all permutations of the last `n-1` elements.) No two of these are rotations of each other because they all have `1` in the same place. I suspect that your real goal is different.
comment on: http://stackoverflow.com/a/51532160
type: AnswerComment

http://stackoverflow.com/comment/90139173
type: Comment
comment on: http://stackoverflow.com/a/51585908
score: 1
type: AnswerComment
has text: After updating statsmodels to 0.9, the problem still remains, with a new error. The first is "TypeError: 'int' object is not subscriptable", and the last on the bottom (after a lot more text) is "invalid literal for int() with base 10: '2014-01-03'". After confirming, the same dynamic exists as before, either I cannot use dates, or I cannot run the time series analysis :( .

http://stackoverflow.com/comment/90007474
has text: @jpp. I don't think the questions are equivalent. There are things you can do to get just the first element that wouldn't be possible here, like short circuiting the loop. At the same time, getting all the subsequences is more general than getting just the one.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51518791
type: Comment

http://stackoverflow.com/q/51536001
score: -1
has comment: http://stackoverflow.com/comment/90039556
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has title: how to use "position" in insert() in python list
has body: I am trying basics of list() in python, and apart from expend(), in insert(), it says it can insert an element at given position. If my list has 3 elements and I try to insert at 7th position it totally inserts it, I can't understand how does it work ? is there 4th and 5th position in between and if yes what is stored there? for example below the length of a_list is 3, because it has 3 elements then how does position matter? &gt;&gt;a_list = ['1', '2'] &gt;&gt;a_list.insert( 7, 'a') &gt;&gt;print (a_list) &gt;&gt;print (len(a_list)) thanks in advance !
has comment: http://stackoverflow.com/comment/90039611
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/25840177
has answer: http://stackoverflow.com/a/51536265
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90040791
duplicate of: http://stackoverflow.com/q/25840177

http://stackoverflow.com/q/51583365
upvote count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51583387
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51583387
type: Question
tagged with: performance
possible better answer: http://stackoverflow.com/a/51583454
tagged with: dataframe
has answer: http://stackoverflow.com/a/51583454
answer count: 2
linked to: http://stackoverflow.com/q/22820292
has body: I have a dataframe: import numpy as np import pandas as pd np.random.seed(18) df = pd.DataFrame(np.random.randint(0,50,size=(10, 2)), columns=list('AB')) df['Min'] = np.nan n = 3 # can be changed I need to fill column 'Min' with minimum values of next n enrties of column 'B': Currently I do it using iteration: for row in range (0, df.shape[0]-n): low = [] for i in range (1, n+1): low.append(df.loc[df.index[row+i], 'B']) df.loc[df.index[row], 'Min'] = min(low) But it is quite a slow process. Is there more efficient way, please? Thank you.
downvote count: 1
has title: How to fill DataFrame column with minimum values of next n entries of other column
favorite count: 0

http://stackoverflow.com/a/51626903
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51626666
score: 1
has body: This should help. import glob import os path = "YourPath" for i in tmp2: #Iterate Your List files=glob.glob('*.{}.*'.format(i)) #Check for files for file in files: fPath = os.path.join(path, file) #Form full path to file os.remove(fPath) #Remove
upvote count: 1

http://stackoverflow.com/comment/89969289
type: Comment
comment on: http://stackoverflow.com/a/51499472
score: 0
type: AnswerComment
has text: Good to know, glad I asked.

http://stackoverflow.com/comment/90120951
type: Comment
type: QuestionComment
has text: @DavidWinder I have added it in the question now. Hope now my question is more clear. Thanks.
comment on: http://stackoverflow.com/q/51577527
score: 0

http://stackoverflow.com/comment/89988779
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51489632
score: 0
has text: That works. Thanks. If you want, make that an answer and I'll give you the correct answer points.

http://stackoverflow.com/comment/90285957
comment on: http://stackoverflow.com/a/51601080
has text: Ahh i figured it out. I ended up uninstalling python and anaconda and reinstalling them.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51613337
has answer: http://stackoverflow.com/a/51639379
tagged with: pivot
has comment: http://stackoverflow.com/comment/90192119
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90192304
tagged with: join
has comment: http://stackoverflow.com/comment/90194846
tagged with: dataframe
upvote count: 10
score: 9
type: Question
has title: pandas pivot and join in two dataframes
has answer: http://stackoverflow.com/a/51614045
has comment: http://stackoverflow.com/comment/90192076
has answer: http://stackoverflow.com/a/51613655
favorite count: 0
has answer: http://stackoverflow.com/a/51614138
tagged with: pandas
answer count: 5
accepted answer: http://stackoverflow.com/a/51613655
tagged with: python
has body: I have two dataFrames : df1 mag cat 0 101 A1 1 256 A2 2 760 A2 3 888 A3 ... df2 A1 A2 A3 ... 0 E50R AZ33 REZ3 1 T605 YYU6 YHG5 2 IR50 P0O9 BF53 3 NaN YY9I NaN And I would like to create a final DataFrame which looks like : df 101 256 760 888 ... 0 E50R AZ33 AZ33 REZ3 1 T605 YYU6 YYU6 YHG5 2 IR50 P0O9 P0O9 BF53 3 NaN YY9I YY9I NaN I tried something with pivot, but it doesn't seem to do the job Could you help me ?
possible better answer: http://stackoverflow.com/a/51614915
has answer: http://stackoverflow.com/a/51614915

http://stackoverflow.com/a/59799152
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51619615
upvote count: 1
downvote count: 1
has body: This is how I would calculate the days until birthday: from datetime import datetime def get_user_birthday(): year = int(input('When is your birthday? [YY] ')) month = int(input('When is your birthday? [MM] ')) day = int(input('When is your birthday? [DD] ')) birthday = datetime(year,month,day) return birthday def calculate_dates(birthyday): now = datetime.now() birthday = datetime(now.year, birthday.month, birthday.day) return (birthday - now.today()).days + 1 bd = get_user_birthday() c = calculate_dates(bd) print(c)

http://stackoverflow.com/q/51518500
type: Question
tagged with: odoo
score: 1
has answer: http://stackoverflow.com/a/51541871
tagged with: odoo-9
has comment: http://stackoverflow.com/comment/90035387
answer count: 3
has body: I am very new to odoo, I want to update the value of discount_type and discount as I update or change the value of global_discount_type and global_order_discount.How can I achieve this as both variables are from different class. I am unable to do using general python approach. Please guide me. class PurchaseOrder(models.Model): _inherit = "purchase.order" total_discount = fields.Monetary(string='Total Discount', store=True, readonly=True, compute='_amount_all', track_visibility='always') global_discount_type = fields.Selection([ ('fixed', 'Fixed'), ('percent', 'Percent') ], string="Discount Type", ) global_order_discount = fields.Float(string='Global Discount', store=True, track_visibility='always') class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" discount = fields.Float(string='Discount', digits=dp.get_precision('Discount'), default=0.0) discount_type = fields.Selection([ ('fixed', 'Fixed'), ('percent', 'Percent') ], string="Discount Type", default='percent') Do I need to made changes in xml file also? I want to achieve this using onchange.
has comment: http://stackoverflow.com/comment/90051201
downvote count: 0
has answer: http://stackoverflow.com/a/51520178
has title: odoo how to update the value of one field by updating the value of other, both field is in different class
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/90051671
has answer: http://stackoverflow.com/a/51523332
has comment: http://stackoverflow.com/comment/90051089
upvote count: 1
has comment: http://stackoverflow.com/comment/90050510

http://stackoverflow.com/comment/90048221
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51529324
type: QuestionComment
has text: Thank you! I open Google cloud platform-IAM and management- IAM, and saw my rold is the owner. I think it's more powerful then viewer and editor.

http://stackoverflow.com/comment/90132216
comment on: http://stackoverflow.com/a/51568199
type: Comment
score: 0
type: AnswerComment
has text: @jezrael sorry haven't tested it yet, just opened your answer. it seems resample is a pandas bug.. i think your solution will work well though. thanks for answering!

http://stackoverflow.com/comment/90116051
comment on: http://stackoverflow.com/a/51574196
type: Comment
score: 0
has text: I've followed step by step the post but it's still not working. I can successfully upload the files in local and in production but can't access them. This problem goes away when DEBUG is turned to False
type: AnswerComment

http://stackoverflow.com/comment/136365251
type: AnswerComment
has text: In python _ is throwaway variable not __
type: Comment
comment on: http://stackoverflow.com/a/75385331
score: 2

http://stackoverflow.com/comment/90026125
has text: It still just downloads the HTML file instead of the PDF. I am looking into the urrlib, as you sugested in the comments.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51528781

http://stackoverflow.com/comment/90262868
comment on: http://stackoverflow.com/q/51634576
score: 0
has text: `received_date = x.senton.date()`....this is working perfectly fine for me. I have updated the question too.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/105268328
comment on: http://stackoverflow.com/a/51610341
score: 0
type: AnswerComment
type: Comment
has text: Why is it necessary to create the web runner in the main thread? I tested and it works fine when created in the new thread. (I suppose it's to [handle the requests in the main thread](https://stackoverflow.com/questions/55133510/aiohttp-slowness-with-threading). Why is that useful?)

http://stackoverflow.com/q/51594182
has title: python2.7 pip install EnvironmentError Illega byte sequence
favorite count: 0
has body: I have an error at pip install pyinstaller Cmd quote: Microsoft Windows Version 6.3.9600 20 13 Microsoft Corporation. All rights reserved. C:\WINDOWS\system32>pip install pyinstaller Collecting pyinstaller Downloading https://files.pythonhosted.org/packages/3c/86/909a8c35c5471919b3854c01f43843d9b5aed0e9948b63e560010f7f3429/PyInstaller-3.3.1.tar.gz (3.5MB) 1% |Could not install packages due to an EnvironmentError: [Errno 42] Illega l byte sequence I use python2.7 and Windows8: Python 2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v. 1500 64 bit (AMD64)] on win32 I tried to check what cause the problem all across the internet without success. it happend to me also at pip install py2exe command it doesn't happand at simple package like pip install clock (simple clock package from githab;just to check pip working) I wanted to make a virtual enviroment but pip install virtualenv gave me the same problem. I think that finally I succeed to install virtualenv by the command: pip install https://github.com/pypa/virtualenv/tarball/master (but I not sure because all of my tries) I created new environment but still I couldn't install pyinstaller pack and I got the same error on the new env. I get the same EnvironmentError at pip install clock command (the simple pack, just to check pip). So maybe something in communication from pip to my computer isn't correct.. maybe my programs need update? I updated pip to last version. What do you recommend?
type: UnansweredQuestion
tagged with: pip
upvote count: 1
tagged with: python
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51595776
score: 1

http://stackoverflow.com/comment/90018666
type: Comment
type: QuestionComment
has text: Also, can you provide some sample data and your expected output (See [mcve]). It's hard to imagine what counts as a date and what doesn't without any data.
score: 2
comment on: http://stackoverflow.com/q/51524929

http://stackoverflow.com/q/51588186
answer count: 1
downvote count: 0
tagged with: keras
has answer: http://stackoverflow.com/a/53381309
favorite count: 0
has comment: http://stackoverflow.com/comment/90145400
type: UnansweredQuestion
tagged with: python
upvote count: 6
has title: Keras, TensorFlow : "TypeError: Cannot interpret feed_dict key as Tensor"
linked to: http://stackoverflow.com/q/40850089
score: 6
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90141717
has body: I am trying to use keras fune-tuning to develop image classify applications. I deployed that application to a web server and the image classification is succeeded. However, when the application is used from two or more computers at the same time, the following error message appears and the application doesn't work. TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(3, 3, 3, 64), dtype=float32) is not an element of this graph. Here is my code for image classification. img_height, img_width = 224, 224 channels = 3 input_tensor = Input(shape=(img_height, img_width, channels)) vgg19 = VGG19(include_top=False, weights='imagenet', input_tensor=input_tensor) fc = Sequential() fc.add(Flatten(input_shape=vgg19.output_shape[1:])) fc.add(Dense(256, activation='relu')) fc.add(Dropout(0.5)) fc.add(Dense(3, activation='softmax')) model = Model(inputs=vgg19.input, outputs=fc(vgg19.output)) model.load_weights({h5_file_path}) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) img = image.load_img({image_file_path}, target_size=(img_height, img_width)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = x / 255.0 pred = model.predict(x)[0] How can I run this application in multiple computers at the same time? Thank you for reading this post.

http://stackoverflow.com/comment/90210383
type: Comment
type: QuestionComment
score: 0
has text: Interesting question but you might get better responses if you try on [DS SE](https://datascience.stackexchange.com/)
comment on: http://stackoverflow.com/q/51622522

http://stackoverflow.com/comment/89975345
comment on: http://stackoverflow.com/q/51502959
score: 0
type: Comment
type: QuestionComment
has text: Have you read this [answer](https://stackoverflow.com/a/37644056/4819376)?

http://stackoverflow.com/comment/90174957
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51604541
has text: Can you provide a single item from your url_list, so people can try to run your code to see what list is returned by pd.read_html?
score: 0

http://stackoverflow.com/q/51525261
has answer: http://stackoverflow.com/a/51620862
tagged with: python
type: AnsweredQuestion
tagged with: socket.io
type: Question
accepted answer: http://stackoverflow.com/a/51620862
tagged with: flask-socketio
score: 4
upvote count: 4
has title: Python Flask-socketio working, not receiving data from JS client
downvote count: 0
answer count: 1
tagged with: websocket
tagged with: javascript
favorite count: 0
has body: I am trying to setup a basic web socket using flask-socketio and the javascript socket-io library on the front end. The frontend successful registers the connection. However, in the python console, my log messages are not working and there is no indication that the server is responding to my requests. All I get in the console on connect is: "GET /socket.io/?EIO=3&amp;transport=polling&amp;t=MJHl5WD HTTP/1.1" 200 - 127.0.0.1 - - [25/Jul/2018 09:58:58] "POST /socket.io/?EIO=3&amp;transport=polling&amp;t=MJHl5WQ&amp;sid=b2a1f92c18e349c5a11df25e5001766c HTTP/1.1" 200 - So the connection is working, however, nothing else on the back end is outputting as it should. Here is the JS: var socket=io('http://127.0.0.1:5000'); socket.on('connect',function(){ console.log("connected"); socket.emit('client_connected',{data:"testsend"}); }); socket.on('update',function(data){ console.log(data) }); And the python: import json import urllib3 from bs4 import BeautifulSoup from flask import Flask, jsonify, render_template, request from flask_socketio import SocketIO, send, emit app=Flask(__name__) socketio= SocketIO(app) if __name__ == '__main__': socketio.run(app) socketio.emit('update',{'data':"test"}); @socketio.on('client_connected') def handle_client_connect_event(data): print("connected") print(str(data)) @socketio.on('disconnect') def disconnected(): print('disconnected') @socketio.on('connect') def connected(): print('connected') None of the @socketio.on lines work, and the 'update' event isn't working either. Help would be greatly appreciated.

http://stackoverflow.com/a/51526954
has comment: http://stackoverflow.com/comment/90022472
upvote count: 5
has body: This has nothing to do with your line continuation, it's with using \, as an escape sequence in your string. The warning explicitly includes \,: DeprecationWarning: invalid escape sequence \, And that's why your later example doesn't warn: because the string doesn't have a \, or other unrecognized escape sequence in it. As explained in the docs for String and Byte literals: Changed in version 3.6: Unrecognized escape sequences produce a DeprecationWarning. In some future version of Python they will be a SyntaxError. This change is mentioned in What's New in Python 3.6, with a link to issue #27364, which links to an earlier discussion on the -dev mailing list. Traditionally, Python allowed unrecognized escape sequences in string literals and just processed them as if they weren't escapes, so \, literally means a backslash and a comma, because this makes it easier to see what's going wrong when you print out the string in the debugger. But this leads to all kinds of confusion, especially for Windows users (who get away with 'C:\Spam', 'C:\spam', and 'C:\Vikings', but get errors with 'C:\vikings'), and for people coming from any of the huge number of languages that follow C-style escape rules (where \, would mean just a comma—although most C compilers will generate a warning for that), which is presumably why you now get a warning.
type: Answer
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/90022609
accepted answer of: http://stackoverflow.com/q/51526849
answers question: http://stackoverflow.com/q/51526849
has comment: http://stackoverflow.com/comment/90022863
has comment: http://stackoverflow.com/comment/90022605
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90022727

http://stackoverflow.com/comment/90028555
type: Comment
has text: You can make it infinite if you want (but your model must be good enough to always reach an `end_of_sentence`). So be careful and define a safety maximum. It doesn't seem to make sense having it as 1.
comment on: http://stackoverflow.com/a/51503886
type: AnswerComment
score: 0

http://stackoverflow.com/a/51539534
has body: You are not opening files... for filename in os.listdir(path): with open(path + filename, 'r') as vt_result_file: vt_data = json.load(vt_result_file) listdir - lists all dirs and files in the path.
score: 0
has comment: http://stackoverflow.com/comment/90050243
type: Answer
has comment: http://stackoverflow.com/comment/90093547
has comment: http://stackoverflow.com/comment/90046730
answers question: http://stackoverflow.com/q/51539344
has comment: http://stackoverflow.com/comment/90050041
has comment: http://stackoverflow.com/comment/90053968

http://stackoverflow.com/comment/89964067
comment on: http://stackoverflow.com/q/51495939
has text: What is the error? What was the code with PyTorch? We cannot really help here.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/90163587
comment on: http://stackoverflow.com/a/51527182
has text: I tried Raffel et al. [https://arxiv.org/abs/1512.08756]'s attention.py, but I got a value error: ValueError: ('Could not interpret regularizer identifier:', 15). Did you use the same attention.py and have you had the same error?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51587935
has comment: http://stackoverflow.com/comment/90142864
has comment: http://stackoverflow.com/comment/90141686
tagged with: data-structures
linked to: http://stackoverflow.com/q/449560
tagged with: python-2.7
tagged with: python
has comment: http://stackoverflow.com/comment/90142348
tagged with: python-3.x
has title: Which data-structure is best considering insertion/accessing for storing timestamps for different units?(data very large)
answer count: 0
has comment: http://stackoverflow.com/comment/90141242
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90141708
has comment: http://stackoverflow.com/comment/90141564
type: Question
has body: I have 6000 log files(so very large data) in the form: u1 1234 u3 231 u5 3456 u1 2367 u7 68968 u8 2112 u6 32423 u7 12345 Where ui is the ith unit and second column is timestamp.Now i need to store all the data in an efficient data structure. Language:Python What i was doing was a dictionary of list.Where key will be the unit number and value will be a list containing values of all the timestamps related to that unit.If there is a better option please suggest.
tagged with: algorithm
has comment: http://stackoverflow.com/comment/90142291
has comment: http://stackoverflow.com/comment/90143084
score: 0

http://stackoverflow.com/q/51595334
accepted answer: http://stackoverflow.com/a/51595414
tagged with: odoo-9
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: python-2.7
type: Question
has answer: http://stackoverflow.com/a/51595414
score: 1
has title: UserError triggered on value 0
upvote count: 1
tagged with: python
answer count: 1
has body: I have this kinda usererror advance_payment_percent = fields.Integer(string='Advance Payment', default=50) if not self.advance_payment_percent: raise UserError(_("Please enter advance payment percent under client form!")) the problem is that when I enter 0 in advance_payment_percent this UserError is still triggered because 0 = False in python, so how can I work around this that I could use 0 and this error wouldn't be triggered. It only should be triggered when field is empty.
tagged with: odoo
tagged with: odoo-8

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/51620484
tags question: http://stackoverflow.com/q/51499085
tags question: http://stackoverflow.com/q/51515471
tags question: http://stackoverflow.com/q/51528045
tags question: http://stackoverflow.com/q/51490891
tags question: http://stackoverflow.com/q/51541494
tag name: kivy-language
tags question: http://stackoverflow.com/q/51579029
tags question: http://stackoverflow.com/q/51496685
tags question: http://stackoverflow.com/q/51494886
tags question: http://stackoverflow.com/q/51552017

http://stackoverflow.com/q/51490553
score: -1
has comment: http://stackoverflow.com/comment/89950615
has title: Python3- How should I create a function that can disable a nested function?
has comment: http://stackoverflow.com/comment/89950099
answer count: 1
has comment: http://stackoverflow.com/comment/89949771
favorite count: 0
has body: Python newb here. I'm trying to create a function that can keep track of other functions. It needs to also disable a nested function silence() and continue to run the rest: import dis import inspect import sys def foo(): global print print('Entering foo()...') #unsilence (disable) this function def silence(*args): pass print = silence print('silence() has been disabled, congratulations!') def solution(): #you can only code here #use sys.settrace and inspect pass def main(): print('Start!') solution() foo() if __name__ == '__main__': main() it should output: Start! Entering foo()... silence() has been disabled, congratulations! I have no idea what to put inside the solution() function to disable silence(). Any help would be greatly appreciated!
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89949724
has comment: http://stackoverflow.com/comment/89949656
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51491312
upvote count: 0
has comment: http://stackoverflow.com/comment/89949670

http://stackoverflow.com/comment/90200122
type: QuestionComment
has text: @pault: not exactly a duplicate: mode text is required for a csv writer, but `endline=''` must be provided too.
score: 0
comment on: http://stackoverflow.com/q/51615916
type: Comment

http://stackoverflow.com/q/51632623
has comment: http://stackoverflow.com/comment/90239067
type: Question
tagged with: opencv
tagged with: opencv3.0
has comment: http://stackoverflow.com/comment/90238790
score: 0
has body: I'm using opencv to extract text from images like this. Right now my goal is in trying to delete the most of the walls/windows/doors I can while leaving the text intact. This is what I came up with: def process_image(path, out_path): image = Image.open(path) gray_image = cv2.cvtColor(np.asarray(image), cv2.COLOR_BGR2GRAY) ret,th = cv2.threshold(gray_image,127,255,cv2.THRESH_OTSU) kernel = np.ones((4,4),np.uint8) edges = cv2.dilate(th,kernel,iterations = 1) edges = cv2.erode(edges, kernel, iterations = 1) edges = cv2.bitwise_and(cv2.bitwise_not(th), edges) ret, labels = cv2.connectedComponents(edges, connectivity = 8) for label in range(ret): if : #if connComp is adjacent to a wall edges[labels == label] = 0 cv2.imwrite(out_path,edges) I basically dilate the image so that all is left are the tickest walls, then I use this image as a filter to actually delete those walls. In the end I look for connected components and now I'd like to cycle on those and check wheter they "touch" the filter I just used (meaning a white pixel is next to a white pixel) and if they do I'd like to recolor the component black. This way I should be able to filter the image even more leaving the text untouched since it never touches a wall, problem is this is my first time using opencv and I'm not really sure how to implement the last bit of my idea. Any tip on how to do it?
has comment: http://stackoverflow.com/comment/90706133
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90238488
tagged with: connected-components
tagged with: python
tagged with: computer-vision
has title: Check the neighbour pixels of a connected component
answer count: 0
has comment: http://stackoverflow.com/comment/90236703

http://stackoverflow.com/a/51499441
has comment: http://stackoverflow.com/comment/90002900
type: Answer
answers question: http://stackoverflow.com/q/51498202
has body: You'll have to create a custom class that inherits the VectorAssembler to automatically set the inputCols: from pyspark import keyword_only class CustomVecssembler(VectorAssembler): @keyword_only def __init__(self, outputCol='features'): super(CustomVecssembler, self).__init__() self.transformer = VectorAssembler(outputCol=outputCol) if spark.version.startswith('2.1'): kwargs = self.__init__._input_kwargs else: kwargs = self._input_kwargs self.setParams(**kwargs) @keyword_only def setParams(self, outputCol='features'): if spark.version.startswith('2.1'): kwargs = self.__init__._input_kwargs else: kwargs = self._input_kwargs return self._set(**kwargs) def _transform(self, df): ready = [col for col in df.columns if col != 'target'] self.setInputCols(ready) self.transformer.setInputCols(ready) df = self.transformer.transform(df) return df Validating whether it works: # prep dataset data = pd.DataFrame({ 'ball_column': [0, 1, 2, 3], 'keep_column': [7, 8, 9, 10], 'hall_column': [14, 15, 16, 17], 'banned_me': [14, 15, 16, 17], 'target': [21, 31, 41, 51] }) df = spark.createDataFrame(data) # ORIGINAL IMPLEMENTATION column_dropper = ColumnDropper_test(banned_list=['banned_me']) model = Pipeline(stages=[column_dropper]).fit(df).transform(df) ready = [col for col in model.columns if col != 'target'] assembler = VectorAssembler(inputCols=ready, outputCol='features') dtc = DecisionTreeClassifier(featuresCol='features', labelCol='target') model_2 = Pipeline(stages=[assembler, dtc]) train_data, test_data = model.randomSplit([0.5, 0.5]) fit_model = model_2.fit(train_data) results = fit_model.transform(test_data) results.select('features','Prediction').show() # +--------------+----------+ # | features|Prediction| # +--------------+----------+ # |[1.0,15.0,8.0]| 51.0| # |[2.0,16.0,9.0]| 51.0| # +--------------+----------+ # USING CUSTOM VEC ASSEMBLER new_assembler = CustomVecssembler(outputCol='features') new_pipeline = Pipeline(stages=[column_dropper, new_assembler, dtc]).fit(train…
upvote count: 3
has comment: http://stackoverflow.com/comment/90004924
has comment: http://stackoverflow.com/comment/89968109
score: 3
has comment: http://stackoverflow.com/comment/90007170
has comment: http://stackoverflow.com/comment/90007321
has comment: http://stackoverflow.com/comment/90002562
has comment: http://stackoverflow.com/comment/89972442
has comment: http://stackoverflow.com/comment/89971740
accepted answer of: http://stackoverflow.com/q/51498202
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90008354

http://stackoverflow.com/comment/90237581
score: 1
has text: You should use tf.saved_model.simple_save():
type: AnswerComment
comment on: http://stackoverflow.com/a/51636392
type: Comment

http://stackoverflow.com/comment/90243828
type: AnswerComment
has text: Thanks. How do you suggest i prevent the number rounding. I need the number as it is given.
type: Comment
comment on: http://stackoverflow.com/a/51639571
score: 0

http://stackoverflow.com/q/51624449
tagged with: winapi
score: 161
answer count: 5
has body: I recently installed Python 3.7 and at the end of the setup, there is the option to "Disable path length limit". I don't know whether or not I should do this. What are the pros and cons of doing this? Just from the sound of it you should always disable it.
linked to: http://stackoverflow.com/q/1880321
has answer: http://stackoverflow.com/a/74909988
downvote count: 0
type: UnansweredQuestion
has title: Python Setup Disabling Path Length Limit Pros and Cons?
has answer: http://stackoverflow.com/a/52824569
type: Question
upvote count: 161
tagged with: windows
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/78912700
has answer: http://stackoverflow.com/a/74789871
tagged with: python
tagged with: max-path
has answer: http://stackoverflow.com/a/74797017

audacity
type: Tag
tags question: http://stackoverflow.com/q/51486615
tag name: audacity

http://stackoverflow.com/comment/90136870
comment on: http://stackoverflow.com/a/51584479
score: 0
type: Comment
has text: @karthikeayan `list` is not a keyword. It is merely the name of a built-in function. It is a normal variable in that respect, you can assign whatever you want to it: `list = "you shouldn't do this"`
type: AnswerComment

http://stackoverflow.com/q/51600414
linked to: http://stackoverflow.com/q/38743064
linked to: http://stackoverflow.com/q/51602248
type: Question
has answer: http://stackoverflow.com/a/51600921
answer count: 1
has body: Aim: To speed up applying a function row wise across a large data frame (1.9 million ~ rows) Attempt: Using dask map_partitions where partitions == number of cores. I've written a function which is applied to each row, creates a dict containing a variable number of new values (between 1 and 55). This function works fine standalone. Problem: I need a way to combine the output of each function into a final dataframe. I tried using df.append, where I'd append each dict to a new dataframe and return this dataframe. If I understand the Dask Docs, Dask should then combine them to one big DF. Unfortunately this line is tripping an error (ValueError: could not broadcast input array from shape (56) into shape (1)). Which leads me to believe it's something to do with the combine feature in Dask? #Function to applied row wise down the dataframe. Takes a column (post) and new empty df. def func(post,New_DF): post = str(post) scores = OtherFUNC.countWords(post) scores['post'] = post New_DF = New_DF.append(scores, ignore_index=True) return(New_DF) #Dask dd.from_pandas(dataset,npartitions=nCores).\ map_partitions( lambda df : df.apply( lambda x : func(x.post,New_DF),axis=1)).\ compute(get=get)
score: 0
tagged with: pandas
tagged with: python
has title: Returning a dataframe in Dask
accepted answer: http://stackoverflow.com/a/51600921
tagged with: dask
type: AnsweredQuestion

http://stackoverflow.com/comment/136544305
type: AnswerComment
has text: With Pandas 2.1.2, the `sum(level=0)` spits `TypeError: sum() got an unexpected keyword argument 'level'`. This is consistent with the official documentation: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.sum.html.
type: Comment
comment on: http://stackoverflow.com/a/51540521
score: 0

http://stackoverflow.com/a/51497219
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Yes that is possible, but that is only now that register_class actually returns the cls. This return of cls was introduced 2018-07-12 with the resolution of issue #186. If you do: import sys from ruamel.yaml import YAML, yaml_object yaml = YAML() def yaml_object(yml): return yml.register_class @yaml_object(yaml) class Asdf: def __init__(self, foo, bar): self.foo = foo self.bar = bar yaml.dump(Asdf(1,2), sys.stdout) it gives: !Asdf foo: 1 bar: 2
accepted answer of: http://stackoverflow.com/q/51496677
upvote count: 2
answers question: http://stackoverflow.com/q/51496677

http://stackoverflow.com/comment/90098067
type: Comment
comment on: http://stackoverflow.com/q/51565619
score: 0
type: QuestionComment
has text: replace to what ?

http://stackoverflow.com/comment/121204042
type: QuestionComment
comment on: http://stackoverflow.com/q/51621799
has text: I hit a similar error `OverflowError: BLOB longer than INT_MAX bytes`
score: 0
type: Comment

http://stackoverflow.com/a/51583106
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51582856
has body: Regex will work for this. I didn't capture everything because you didn't detail what's what but here's an example of capturing the name: import re data = "%B8954756016548963^LAST/FIRST INITIAL^180912345678912345678901234?;8954756016548963=180912345678912345678901234?" matches = re.search(r"\^(?P&lt;name&gt;.+)\^", data) print(matches.group('name')) # LAST/FIRST INITIAL If you aren't familiar with regex, here's a way of testing pattern matching: https://regex101.com/r/lAARCP/1 and an intro tutorial: https://regexone.com/ But basically, I'm searching for (one or more of anything with .+ between two carrots, ^). Actually, since you mentioned having first and last separate, you'd use this regex: \^(?P&lt;last&gt;.+)/(?P&lt;first&gt;.+)\^ This question may also interest you regarding finding something twice: Finding multiple occurrences of a string within a string in Python
has comment: http://stackoverflow.com/comment/90154072
answers question: http://stackoverflow.com/q/51582856
has comment: http://stackoverflow.com/comment/90161954
type: Answer
has comment: http://stackoverflow.com/comment/90154713
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/90153707
has comment: http://stackoverflow.com/comment/90154622
has comment: http://stackoverflow.com/comment/90161068
has comment: http://stackoverflow.com/comment/90160841

http://stackoverflow.com/a/51564911
answers question: http://stackoverflow.com/q/51564332
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: Selenium is not natively included with the python installation. pip install selenium should solve your issue.

http://stackoverflow.com/q/51573449
answer count: 1
has answer: http://stackoverflow.com/a/59667558
has comment: http://stackoverflow.com/comment/90139090
has title: Python selenium proxy authentication
favorite count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: geckodriver
tagged with: python
score: 2
has body: I am currently trying to use user:pass proxies in selenium in firefox, but the solution in the docs is not working from selenium import webdriver from selenium.webdriver.common.proxy import Proxy, ProxyType myProxy = "host:port" Proxy({ 'proxyType': ProxyType.MANUAL, 'httpProxy': myProxy, 'ftpProxy': myProxy, 'sslProxy': myProxy, 'noProxy': '' # set this value as desired }) driver = webdriver.Firefox(r'''C:\Users\ben_s\Desktop\geckodriver''',proxy=proxy) driver.get("https://www.ipchicken.com/") Is there a way this code could be tweaked to make the proxy work? Or is there an entierly different method? Thanks
linked to: http://stackoverflow.com/q/38304253
tagged with: selenium
type: Question
upvote count: 2

http://stackoverflow.com/comment/89974132
has text: Whilst this looks like C++, it really isn't. The language *explicitly* chooses not to assign a meaning to that snippet.
type: QuestionComment
comment on: http://stackoverflow.com/q/51502600
type: Comment
score: 0

http://stackoverflow.com/q/51626343
tagged with: text-processing
downvote count: 0
possible better answer: http://stackoverflow.com/a/51651798
has answer: http://stackoverflow.com/a/51651798
favorite count: 0
has title: Remove quotes holding 2 words and remove comma between them
tagged with: python
tagged with: delimiter
tagged with: data-processing
has answer: http://stackoverflow.com/a/51626833
type: AnsweredQuestion
score: 1
tagged with: process
upvote count: 1
linked to: http://stackoverflow.com/q/51609461
type: Question
answer count: 2
has body: Following up on Python to replace a symbol between between 2 words in a quote Extended input and expected output: trying to replace comma between 2 words Durango and PC in the second line by &amp; and then remove the quotes " as well. Same for third line with Orbis and PC and 4th line has 2 word combos in quotes that I would like to process "AAA - Character Tech, SOF - UPIs","Durango, Orbis, PC" I would like to retain the rest of the lines using Python. INPUT 2,SIN-Rendering,Core Tech - Rendering,PC,147,Reopened 2,Kenny Chong,Core Tech - Rendering,"Durango, PC",55,Reopened 3,SIN-Audio,AAA - Audio,"Orbis, PC",13,Open LTY-168499,[PC][PS4][XB1] Missing textures from Fort Capture NPC face,3,CTU-CharacterTechBacklog,"AAA - Character Tech, SOF - UPIs","Durango, Orbis, PC",29,Waiting For ... ... ... Like these, there can be 100 lines in my sample. So the expected output is: 2,SIN-Rendering,Core Tech - Rendering,PC,147,Reopened 2,Kenny Chong,Core Tech - Rendering, Durango &amp; PC,55,Reopened 3,SIN-Audio,AAA - Audio, Orbis &amp; PC,13,Open LTY-168499,[PC][PS4][XB1] Missing textures from Fort Capture NPC face,3,CTU-CharacterTechBacklog,AAA - Character Tech &amp; SOF - UPIs,Durango, Orbis &amp; PC,29,Waiting For ... ... ... So far, I could think of reading line by line and then if the line contains quote replace it with no character but then replacement of symbol inside is something I am stuck with. Here is what I have right now: for line in lines: expr2 = re.findall('"(.*?)"', line) if len(expr2)!=0: expr3 = re.split('"',line) expr4 = expr3[0]+expr3[1].replace(","," &amp;")+expr3[2] print &gt;&gt;k, expr4 else: print &gt;&gt;k, line but it does not consider the case in 4th line? There can be more than 3 combos as well. For eg. 3,SIN-Audio,"AAA - Audio, xxxx, yyyy","Orbis, PC","13, 22",Open and wish to make this 3,SIN-Audio,AAA - Audio &amp; xxxx &amp; yyyy, Orbis &amp; PC, 13 &amp; 22,Open How to achieve this, any suggestion? Learning Python.
accepted answer: http://stackoverflow.com/a/51626833

http://stackoverflow.com/comment/90072523
type: Comment
comment on: http://stackoverflow.com/q/51552684
has text: @SamuelChen I have edited my answer to include the traceback, and scrape is a function in news.py
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90182396
score: 0
type: AnswerComment
has text: Output is not odd. It just can't be accomodated horizontally. so extra part is laid below.
type: Comment
comment on: http://stackoverflow.com/a/51608339

http://stackoverflow.com/comment/90122099
comment on: http://stackoverflow.com/a/51559696
has text: Not on my machine. If I wrap the above code in def my_function(im3d): ....... return sl_start.val,sl_end.val The function returns before I close the figure.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51530507
type: Question
tagged with: odoo
score: -1
has comment: http://stackoverflow.com/comment/90035676
answer count: 1
has comment: http://stackoverflow.com/comment/90035719
favorite count: 0
has title: Get day name based on a given date
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51818573
downvote count: 2
tagged with: python
has body: I want to get the day name based on the date selected from the fields. I have the code as below: from datetime import datetime, date from odoo import api, fields, models, _ from odoo.exceptions import ValidationError import calendar class HrPublicHolidayHolidays(models.Model): _name = 'hr.public.holiday.holidays' _description = 'Public Holidays Dates' name = fields.Char('Holiday Name', required=True) date = fields.Date('Holiday Date', required=True) date_day = fields.Char('Day') year_id = fields.Many2one('hr.public.holiday', 'Calendar Year', required=True) variable = fields.Boolean('Date may change') @api.onchange('date') def _get_day_of_date(self): for r in self: selected = fields.Datetime.from_string(r.date) r.date_day = calendar.day_name[selected.weekday()] Then when I run the code, when I click on the add an item After I clicked the button it shows me the error result: But if I try to select the date, it will show the day of the date that I've selected like: So basically the code will run, but the error just keeps on showing and I have no idea why.
tagged with: odoo-11
upvote count: 1

directed-acyclic-graphs
type: Tag
tag name: directed-acyclic-graphs
tags question: http://stackoverflow.com/q/51554263

http://stackoverflow.com/comment/90166742
has text: Nice to note that numpy is also generally going to be faster than a raw python solution, since it's offloading most of the work to pre-compiled libraries written in C++
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51599824

http://stackoverflow.com/comment/90098008
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51565064
has text: What are the files in `/database/backend`? Also what code are you using to import the module?

http://stackoverflow.com/comment/90111261
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51567633
score: 0
has text: Thanks. And I got NameError: name 'groupby' is not defined. Do you have any idea what is wrong with it?

http://stackoverflow.com/comment/89950445
comment on: http://stackoverflow.com/a/51490867
type: Comment
score: 1
type: AnswerComment
has text: I can only tell that for some reason `ax.bar()` adds another tick at the location -1 (call `ax.get_xticks()` to see for yourself!)) The label "a" is assigned to that tick and is off the chart.

http://stackoverflow.com/comment/90076642
type: AnswerComment
has text: now that works, thanks , sorry i didn't understand your answer fully at the first. you rock !!!
type: Comment
comment on: http://stackoverflow.com/a/51553921
score: 0

http://stackoverflow.com/q/51529255
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51529654
tagged with: python
has comment: http://stackoverflow.com/comment/90026915
upvote count: 1
answer count: 1
has title: Merging dataframes based on lists of row numbers
type: UnansweredQuestion
tagged with: dataframe
tagged with: pandas
downvote count: 0
score: 1
has body: I need to compare every row with every row in large dataframes (> 50000) leading to over 1 billion comparisons which is too computationally expensive on Pandas dataframes. Therefore I load my values into arrays and compare it using generators: start = df['StartPos'].values.tolist() end = df['EndPos'].values.tolist() index = df.index.values.tolist() a = [(y-x, (i,j)) for i,x in enumerate(start) for j,y in enumerate(end) if (y-x) &gt; 0 and (y-x) &lt;= 2000 and i != j] if len(a) == 0: continue prod_sizes, rows = zip(*a) row1,row2 = zip(*rows) Now, for every dataframe df I end up with a list like &gt;&gt;&gt; row1 (0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4) &gt;&gt;&gt; row2 (1, 2, 3, 4, 5, 2, 3, 5, 3, 5, 2, 5, 1, 2, 3, 5) Now I want to merge my original dataframe df based on the values of row1 and row2. The output dataframe should look like: 0: columns of row0 | columns of row1 1: columns of row0 | columns of row2 2: columns of row0 | columns of row3 3: columns of row0 | columns of row4 4: columns of row0 | columns of row5 5: columns of row1 | columns of row2 6: columns of row1 | columns of row3 ... 15: columns of row4 | columns of row5 Is there a Pandas-way to do this merge operation based on lists of row numbers, or should I simply use loops and access rows via .iloc and append them to a new dataframe?

http://stackoverflow.com/comment/90166471
score: 0
has text: Not sure it is related to functional programming, but `0*NaN=NaN`, `0*Infinity=NaN`, `0*-1=-0`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51600034

http://stackoverflow.com/comment/124511534
type: AnswerComment
comment on: http://stackoverflow.com/a/51635608
type: Comment
score: 1
has text: I followed the second method and it worked. Thank you.

http://stackoverflow.com/comment/90128134
type: Comment
comment on: http://stackoverflow.com/a/51581026
has text: sorry but this still doesnt fix the problem
type: AnswerComment
score: 0

http://stackoverflow.com/comment/89993803
comment on: http://stackoverflow.com/q/51509710
type: Comment
type: QuestionComment
has text: I don't understand what you're asking. Can't you just follow the relationship from one to the other in the template?
score: 0

http://stackoverflow.com/q/51574859
score: 1
favorite count: 0
type: Question
has body: I have the following code where variables "close", "closeLow" and "closeHigh" are Numpy 1D arrays of the same size. I want to compute the array "showData", as shown in the code below, using some function as "np.where" or any other vectorized/efficient way. showData = np.full(len(close), True) for i in range(len(close)): if close[i] &lt; closeLow[i]: showData[i] = True elif close[i] &gt; closeHigh[i]: showData[i] = False else: showData[i] = showData[i-1] The problem here is that I cannot find any simple way to reproduce the effect of the last line, where we keep the result of the last iteration if the 2 conditions (if and elif) are not met. Thanks in advance!
tagged with: python
tagged with: vectorization
has answer: http://stackoverflow.com/a/51575097
has title: Numpy equivalent of if/elif/else that keeps the last value if the condition is not met
upvote count: 1
tagged with: loops
answer count: 1
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51575097
tagged with: pandas
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/51621365
tagged with: matplotlib
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90208562
tagged with: axis-labels
has title: Matplotlib- getting axis numbers to show correctly on log-log plot
type: Question
has answer: http://stackoverflow.com/a/51621675
tagged with: python
has body: I have a plot that is a little complex, where I have two X-axes (one on top, one on bottom) and one Y-axis, all in log-log space. And while I'm not saying this is the most efficient way to do it, this is how it's working right now: Jy = (.15E-5) D = [11.4,2.7,3.,9.,8.,8.,13.6,10.,16.6,4.3,14.7,2.7,13.5,18.,9.9] years = [1994,1972,1937,1989,1981,1937,1971,1960,1965,1974,1960,1895,1939,1983,1998] names= ['SN1994D','SN1972E','SN1937C','SN1989B','SN1981B','SN1937D','SN1971I','SN1960F','SN1965I','SN1974G','SN1960R','SN1895B','SN1939A','SN1983U','SN1998bu'] Sv = Jy*10E-23 Lv = [4*np.pi*((i*3.086e+24)**2)*Sv for i in D] def two_scales(ax1, data1, data2,lum, c1, c2): ax2 = ax1.twiny() ax1.loglog(data1, lum, color=c1) ax1.set_xlabel('Time (years)') ax1.set_ylabel('Luminosity (erg/s/Hz)') ax2.loglog(data2, lum, color=c2) ax2.set_xlabel('Radius (cm)') return ax1, ax2 # Create axes fig, ax = plt.subplots() ax1, ax2 = two_scales(ax, tim, rad*3.086e+18, lum, 'g', 'w') ax1.loglog(tim3, lum3, 'g', label= "n=.1 cm^-3") ax1.loglog(tim, lum, 'b', label= "n=1 cm^-3") ax1.loglog(tim10, lum10, 'r', label="n= 10 cm^-3") ax1.legend(loc=3) ax1.set_xlim(20,1.5E2) ax1.set_ylim(1E23, 5E25) ax1.scatter(time, Lv) ax1.get_xaxis().set_major_formatter(ScalarFormatter()) ax1.set_xticks([20, 30, 40, 60, 100]) for i, txt in enumerate(names): ax1.annotate(txt, (time[i],Lv[i])) plt.savefig('lumin-rad.png',dpi=600, bbox_inches='tight') The issue I get is I would ideally like the lower axis for time to not be in log space, but to just say "20, 30, 40, 60, 100" instead of "2x10^1" etc. So I have found two examples online on how to do this, either setting the xticks myself for that axis, or setting the major formatter to scalar. However, if I do the ScalarFormatter only, I get 100 instead of 1x10^2, but the rest of the numbers will still show the exponent. If I do the code without that line, it doesn't work at all. But if I do both, I will get the correct numbers, but on top I'll get the exponents showing t…
score: 0

http://stackoverflow.com/comment/90193802
has text: Well, creating `Lock` is cheaper but is also much more frequent. In my environment, creating `WeakValueDictionary` is just 20 times more expensive than creating `Lock`. But since you have said that... whatever. About memory leaks, I don't think it is a problem as all locks will be distoried with `Cache` itself.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51613365

http://stackoverflow.com/comment/90073955
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51552790
type: AnswerComment
has text: I mainly just don’t know how to use the python libraries. How do I tell it to treat it as categorical. In R I can just use the factor function.

http://stackoverflow.com/comment/90055591
type: Comment
score: 1
type: QuestionComment
has text: Does "everywhere" include [this example](https://matplotlib.org/gallery/color/color_demo.html)? Or maybe you want to go more in detail about what exact problem you face.
comment on: http://stackoverflow.com/q/51543810

http://stackoverflow.com/a/51522997
has comment: http://stackoverflow.com/comment/90014921
has comment: http://stackoverflow.com/comment/90015185
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90015365
has comment: http://stackoverflow.com/comment/90015530
has comment: http://stackoverflow.com/comment/90015170
answers question: http://stackoverflow.com/q/51521626
type: Answer
has comment: http://stackoverflow.com/comment/90015413
has comment: http://stackoverflow.com/comment/90015340
accepted answer of: http://stackoverflow.com/q/51521626
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/90016040
has body: Alright, this should do it: import pandas as pd df = pd.DataFrame([['BBC News','something','Test1'], ['The Wall Street Journal','something else','Test2'], ['BBC News','something else entirely','Test3']], columns=['newsSource','description','title']) html = df.style.apply(lambda x: ["background: red" if 'BBC' in x['newsSource'] and idx==0 else "" for idx, v in enumerate(x)], axis = 1).set_table_attributes('border="1" class="dataframe table table-hover table-bordered"').render() with open('test.html', 'w') as f: f.write(html) Explanation: The lambda operator allows you to apply the following ["background: red" if 'BBC' in x['newsSource'] and idx==0 else "" for idx, v in enumerate(x)]to every row of your df (specified by axis=1), where x is each individual row of your df. In English, this means change to "background: red" if the string 'BBC' is contained in x['newsSource'], i.e. the 'newsSource' column of the row x of df. The extra logic specifying idx==0 means only the first cell of that row x, for which we have to enumerate(x) in order to track the current column index idx. Otherwise, do not change the background color, using else "". Hope that's clear!

http://stackoverflow.com/q/51537946
accepted answer: http://stackoverflow.com/a/51541308
tagged with: collatz
has comment: http://stackoverflow.com/comment/90044767
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90047498
has comment: http://stackoverflow.com/comment/90045410
has comment: http://stackoverflow.com/comment/90044530
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51541308
has comment: http://stackoverflow.com/comment/90044461
has comment: http://stackoverflow.com/comment/90049377
has title: python Reverse Collatz Conjecture
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90049848
upvote count: 3
type: Question
has body: What the program should do is take steps and a number and than output you how many unique sequences there are with exactly x steps to create number. Does someone know how I can save some memory - as I should make this work for pretty huge numbers within a 4 second limit. def IsaacRule(steps, number): if number in IsaacRule.numbers: return 0 else: IsaacRule.numbers.add(number) if steps == 0: return 1 counter = 0 if ((number - 1) / 3) % 2 == 1: counter += IsaacRule(steps-1, (number - 1) / 3) if (number * 2) % 2 == 0: counter += IsaacRule(steps-1, number*2) return counter IsaacRule.numbers = set() print(IsaacRule(6, 2)) If someone knows a version with memoization I would be thankful, right now it works, but there is still room for improvement.
score: 3

http://stackoverflow.com/comment/90070923
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51551884
type: AnswerComment
has text: Thanks for the concise explanation. Is remove(self) a method I'd have to create myself, like family.add(self), or is it built-in, like list.remove(item)?

http://stackoverflow.com/q/51591456
score: 15
tagged with: colors
has answer: http://stackoverflow.com/a/51592104
has comment: http://stackoverflow.com/comment/90161359
answer count: 4
favorite count: 0
tagged with: tkinter
has body: Can I use rbg instead of hex in tkinter? If so, how can I do it? I am planning to use this feature to make sort of a gradient from one color to another and I plan to make a for loop to change it from 1 to 255 in a few seconds. from tkinter import * root = Tk() root.configure(background="can i use rgb instead of hex here?") root.mainloop()
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/65983607
tagged with: python
downvote count: 3
has answer: http://stackoverflow.com/a/70735165
upvote count: 18
has answer: http://stackoverflow.com/a/51631427
type: Question
has title: Can I use rgb in tkinter?

machine-learning
tags question: http://stackoverflow.com/q/51596088
tags question: http://stackoverflow.com/q/51503939
tags question: http://stackoverflow.com/q/51511074
tags question: http://stackoverflow.com/q/51625702
tags question: http://stackoverflow.com/q/51515165
tags question: http://stackoverflow.com/q/51485084
tags question: http://stackoverflow.com/q/51518585
tags question: http://stackoverflow.com/q/51546585
tags question: http://stackoverflow.com/q/51526515
tags question: http://stackoverflow.com/q/51586582
tags question: http://stackoverflow.com/q/51570785
tags question: http://stackoverflow.com/q/51503889
tags question: http://stackoverflow.com/q/51578328
tags question: http://stackoverflow.com/q/51606544
tags question: http://stackoverflow.com/q/51581240
tags question: http://stackoverflow.com/q/51573068
tags question: http://stackoverflow.com/q/51541359
tags question: http://stackoverflow.com/q/51607239
tags question: http://stackoverflow.com/q/51636620
tags question: http://stackoverflow.com/q/51575306
tags question: http://stackoverflow.com/q/51622490
tags question: http://stackoverflow.com/q/51586563
tags question: http://stackoverflow.com/q/51599510
tags question: http://stackoverflow.com/q/51581521
tags question: http://stackoverflow.com/q/51595618
tags question: http://stackoverflow.com/q/51545026
tags question: http://stackoverflow.com/q/51522743
tags question: http://stackoverflow.com/q/51639415
tags question: http://stackoverflow.com/q/51548765
tags question: http://stackoverflow.com/q/51604912
tags question: http://stackoverflow.com/q/51617856
tags question: http://stackoverflow.com/q/51524005
tags question: http://stackoverflow.com/q/51549878
tags question: http://stackoverflow.com/q/51531255
tags question: http://stackoverflow.com/q/51489171
tags question: http://stackoverflow.com/q/51571488
tags question: http://stackoverflow.com/q/51482918
tags question: http://stackoverflow.com/q/51546019
tags question: http://stackoverflow.com/q/51516544
tags question: http://stackoverflow.com/q/51625591
tags question: http://stackoverflow.com/q/51605893
tag name: machine-learning
tags question: http://stackoverflow.com/q/51500010
tags question: http://stackoverflow.com/q/51521351
tags question: http://stackoverflow.com/q/51618762
tags question: http://stackoverflow.com/q/51576796
tags question: http://stackoverflow.com/q/51625794
tags question: http://stackoverflow.com/q/51541610
tags question: http://stackoverflow.com/q/51617857
tags question: http://stackoverflow.com/q/51528579
tags question: http://stackoverflow.com/q/51549641
tags question: http://stackoverflow.com/q/51488223
tags question: http://stackoverflow.com/q/51613863
tags question: http://stackoverflow.com/q/51499231
tags question: http://stackoverflow.com/q/51622522
type: Tag
tags question: http://stackoverflow.com/q/51518631
tags question: http://stackoverflow.com/q/51502888
tags question: http://stackoverflow.com/q/51572745
tags question: http://stackoverflow.com/q/51482686
tags question: http://stackoverflow.com/q/51591216
tags question: http://stackoverflow.com/q/51500509
tags question: http://stackoverflow.com/q/51506191
tags question: http://stackoverflow.com/q/51501828
tags question: http://stackoverflow.com/q/51549056
tags question: http://stackoverflow.com/q/51618103
tags question: http://stackoverflow.com/q/51530901
tags question: http://stackoverflow.com/q/51622144
tags question: http://stackoverflow.com/q/51505295
tags question: http://stackoverflow.com/q/51582726
tags question: http://stackoverflow.com/q/51559118
tags question: http://stackoverflow.com/q/51637854
tags question: http://stackoverflow.com/q/51504535
tags question: http://stackoverflow.com/q/51557796
tags question: http://stackoverflow.com/q/51585409
tags question: http://stackoverflow.com/q/51523248
tags question: http://stackoverflow.com/q/51587279
tags question: http://stackoverflow.com/q/51602859
tags question: http://stackoverflow.com/q/51507598
tags question: http://stackoverflow.com/q/51619180

http://stackoverflow.com/comment/90214895
type: Comment
type: QuestionComment
has text: You also have to take into consideration what is Day and Night? In some places, it gets dark much earlier than others, so their night begins sooner than you may think. If you set up a generic value to be night time and a generic value to be day time, you could say that night time in your code is 8pm but in some places it is already dark by 7pm.
score: 0
comment on: http://stackoverflow.com/q/51625018

http://stackoverflow.com/comment/90082211
has text: @melpomene I tried it but it didn't work, I edited my question and added a screenshot
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51557543
type: Comment

http://stackoverflow.com/comment/90203853
type: QuestionComment
has text: It means if the url of the GET request has `page` parameter, get it. If it does not, return 1 by default. So if the url has `?page=9` the `page` variable will be equal to 9. If it does not, the `page` variable will be equal to 1.
score: 0
comment on: http://stackoverflow.com/q/51618819
type: Comment

http://stackoverflow.com/a/51536246
accepted answer of: http://stackoverflow.com/q/51536159
answers question: http://stackoverflow.com/q/51536159
has body: May be this: print(df.replace(0,np.nan).ffill()) Output: A B C 2018-07-16 1.0 2.0 2.0 2018-07-17 3.0 2.0 5.0 2018-07-18 3.0 4.0 5.0 2018-07-19 3.0 4.0 5.0
type: Answer
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51489632
has comment: http://stackoverflow.com/comment/89988779
type: Question
tagged with: qodbc
upvote count: 1
tagged with: python
tagged with: pyodbc
answer count: 1
has title: How to parameterize datestamp in pyODBC query?
has answer: http://stackoverflow.com/a/51523829
has comment: http://stackoverflow.com/comment/89966638
downvote count: 0
type: AnsweredQuestion
has body: I'm using pyodbc together with QODBC to construct an ODBC query. I'm having trouble inserting datestamp parameters. Here you can see the escalation starting from the literal version (1) to string-format version (2) to error-state versions. (Note DateFrom &amp; DateTo): sql = "sp_report ProfitAndLossStandard show Amount_Title, Text, Label, Amount parameters DateFrom = {d'2018-02-12'}, DateTo = {d'2018-02-18'}, SummarizeColumnsBy='TotalOnly', ReturnRows='All'" sql = "sp_report ProfitAndLossStandard show Amount_Title, Text, Label, Amount parameters DateFrom = %s, DateTo = %s, SummarizeColumnsBy='TotalOnly', ReturnRows='All'" % (q_startdate, q_enddate) Subsequent attempts with the insertion syntax ?, cursor.execute(sql, (q_startdate), (q_enddate)) and the variables: q_startdate = ("{d'%s'}" % dates[0]) q_enddate = ("{d'%s'}" % dates[1]) sql = "sp_report ProfitAndLossStandard show Amount_Title, Text, Label, Amount parameters DateFrom = ?, DateTo = ?, SummarizeColumnsBy='TotalOnly', ReturnRows='All'" &gt;&gt;&gt; ('HY004', '[HY004] [Microsoft][ODBC Driver Manager] SQL data type out of range (0) (SQLBindParameter)') q_startdate = (dates[0]) q_enddate = (dates[1]) sql = "sp_report ProfitAndLossStandard show Amount_Title, Text, Label, Amount parameters DateFrom = {d'?'}, DateTo = {d'?'}, SummarizeColumnsBy='TotalOnly', ReturnRows='All'" &gt;&gt;&gt; ('42000', "[42000] [QODBC] [sql syntax error] Expected lexical element not found: = {d'?'} (11015) (SQLPrepare)") Reading the pyodbc Wiki page on inserting data, I don't read about any speed bumps with insertion strings. This must have something to do with how pyodbc processes (escapes) the datestamp. How do you parameterize datestamp--Especially with the qodbc flavor of datestamp.
score: 1
accepted answer: http://stackoverflow.com/a/51523829
favorite count: 0

http://stackoverflow.com/q/51572986
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/49059681
has comment: http://stackoverflow.com/comment/90111829
type: Question
tagged with: recursion
has body: kk is the number of lists present. l1 ,l2,l3 are the lists. In the following code, I have used 3 for loops to add elements in the 3 lists. Value of variable k could vary and so the lists. I want to know how do I use recursion to achieve this. kk = 3 l1 = [8,5,4] l2 = [3,11,9] l3 = [5,9,15,8] maxi = [] for i in l1: for j in l2: for k in l3: maxi.append(i+j+k)
has title: N number of for loops for n number of lists to add each element in 1 list to rest of the lists
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51573025
has comment: http://stackoverflow.com/comment/90112346

http://stackoverflow.com/comment/90134278
score: 0
type: Comment
type: QuestionComment
has text: Is your indentation off? (e.g. the last 3 lines?). What's the purpose of the `reshape` line? Did you check `self.inputTotalData` before that?
comment on: http://stackoverflow.com/q/51583761

http://stackoverflow.com/comment/90164599
comment on: http://stackoverflow.com/a/51599316
has text: See the "Answer Well-Asked Questions" section of [How to Answer](https://stackoverflow.com/help/how-to-answer), particularly the bullet point regarding questions which "*have already been asked and answered many times before*".
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51544765
type: Question
has title: Having some challenges parsing XML with Python and xml.etree.ElementTree
score: 1
has body: <?xml version="1.0" encoding="utf-8" standalone="yes"?> Tbl_Projects_Tableau https://share.corp.com/sites/CPIBudget/_vti_bin/ListData.svc/Tbl_Projects_Tableau/ 2018-07-25T21:27:59Z https://share.corp.com/sites/CPIBudget/_vti_bin/ListData.svc/Tbl_Projects_Tableau(1) 2018-06-14T17:15:27Z <name /> <category term="Microsoft.SharePoint.DataService.Tbl_Projects_TableauItem" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /> <d:FBN_IDId m:type="Edm.Int32">6</d:FBN_IDId> <d:Title m:null="true" /> <d:PROJECT_NAME>Project Swoop</d:PROJECT_NAME> <d:Cluster>ABC</d:Cluster> <d:PROJECT_SITE>ABC9</d:PROJECT_SITE> <d:PROJECT_ORIGINALAMT m:type="Edm.Double">500000</d:PROJECT_ORIGINALAMT> <d:PROJECT_ORG>Nookie</d:PROJECT_ORG> <d:PROJECT_GROUP>Smooth</d:PROJECT_GROUP> <d:c__OldID m:type="Edm.Double">1</d:c__OldID> <d:ContentTypeID>0x0100FD279BEBCF3C4F45BB75D6147D315C09</d:ContentTypeID> <d:Id m:type="Edm.Int32">1</d:Id> <d:ContentType>Item</d:ContentType> <d:Modified m:type="Edm.DateTime">2018-06-14T17:15:27</d:Modified> <d:Created m:type="Edm.DateTime">2018-06-14T16:58:50</d:Created> <d:CreatedById m:type="Edm.Int32">2</d:CreatedById> <d:ModifiedById m:type="Edm.Int32">2</d:ModifiedById> <d:Owshiddenversion m:type="Edm.Int32">8</d:Owshiddenversion> <d:Version>1.0</d:Version> <d:Path>/sites/SmoothBudget/Lists/Projects_Tableau1</d:Path> here is a sample of the XML I am trying to parse to CSV. here is my code so far: import config import csv import pymysql import requests import xml.etree.ElementTree as ET from requests_ntlm import HttpNtlmAuth ssoUsername = config.username ssoPassword = config.password f = open(path+csvFile,'w',newline='') csvwriter = csv.writer(f) column_headers = ['FBN','Project_Name','Cluster','Site','OP2_USD','Type','Group'] csvwriter.writerow(column_headers) rows = [] r2 = requests.get(project_url, auth=HttpNtlmAuth('ANT\\'+ssoUsername,ssoPassword), verify=False) projectData = r2.content etree2 = ET.fromstring(projectData) #print(etree2.finda…
has answer: http://stackoverflow.com/a/51547025
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
possible better answer: http://stackoverflow.com/a/51546804
accepted answer: http://stackoverflow.com/a/51547025
tagged with: elementtree
has answer: http://stackoverflow.com/a/51546804
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
upvote count: 1

http://stackoverflow.com/comment/89999837
type: QuestionComment
comment on: http://stackoverflow.com/q/51515677
score: 0
has text: In not insist, you can install whl for pandas.
type: Comment

http://stackoverflow.com/q/51503591
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89975906
has comment: http://stackoverflow.com/comment/89976726
has answer: http://stackoverflow.com/a/51505656
has comment: http://stackoverflow.com/comment/89976878
has comment: http://stackoverflow.com/comment/89976050
has comment: http://stackoverflow.com/comment/89976013
has comment: http://stackoverflow.com/comment/89975965
type: Question
has comment: http://stackoverflow.com/comment/89976312
score: 1
has comment: http://stackoverflow.com/comment/89975934
has comment: http://stackoverflow.com/comment/89976554
has comment: http://stackoverflow.com/comment/89975956
upvote count: 2
accepted answer: http://stackoverflow.com/a/51503803
has comment: http://stackoverflow.com/comment/89975883
answer count: 2
has comment: http://stackoverflow.com/comment/89975910
has comment: http://stackoverflow.com/comment/89976905
has comment: http://stackoverflow.com/comment/89975875
possible better answer: http://stackoverflow.com/a/51505656
has comment: http://stackoverflow.com/comment/89975891
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89975985
has answer: http://stackoverflow.com/a/51503803
has comment: http://stackoverflow.com/comment/89977159
has comment: http://stackoverflow.com/comment/89976447
has comment: http://stackoverflow.com/comment/89976649
has body: Question How to uniquely identify a class in Python over the lifetime of the whole program? I'm interested in both built-in types and user-defined ones. id is not suitable because: [id] returns the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. Is it possible? Concrete use-case I have a dictionary with strings as keys and Python's types/classes as values. For example: {'tid': int, 'name': str, 'color': str} The problem is to uniquely identify a combination of strings and types and use it as basis for comparison. Therefore, dictionary {'tid': int, 'name': str, 'color': str} and dictionary {'tid': float, 'name': str, 'color': str} should be ruled unequal. Similarly, {'tid': int, 'name': str, 'color': str} and {'tid': int, 'name': str, 'colour': str}. The catch Additionally, the comparison should work if names and types are hashed and result is stored (because comparing integers is faster then comparing dicts). For example: def hash_heading(dct): s = '' for k, v in OrderedDict(dct).items(): s += k + str(id(v)) return hash(s) This introduces the risk that two classes A and B, with disjoint lifetimes, are assigned the same id (in case A was destroyed before B was declared) and, therefore, the check passes. [1] https://docs.python.org/3/library/functions.html#id
tagged with: python
has comment: http://stackoverflow.com/comment/89976977
has title: How to uniquely identify a class in Python over the lifetime of the whole program
has comment: http://stackoverflow.com/comment/89975846
has comment: http://stackoverflow.com/comment/89977292

http://stackoverflow.com/comment/90176521
type: QuestionComment
type: Comment
score: 1
has text: There are two year 1963, how do you know which one to choose?
comment on: http://stackoverflow.com/q/51605581

http://stackoverflow.com/comment/90024275
type: QuestionComment
has text: Is seems as if I have to go from this 3NF dataframe to some sort of object that gives me an object with BLIP.value_counts by month and then I somehow need to map them to the plot properly,
comment on: http://stackoverflow.com/q/51527495
score: 0
type: Comment

http://stackoverflow.com/q/51553545
has body: When use sharex or sharey in subplots, the tick labels would disappeared, how to turn them back? Here is an example just copied from the official website: fig, axs = plt.subplots(2, 2, sharex=True, sharey=True) axs[0, 0].plot(x) plt.show() And we will see: As we can see, the top-right plot doesn't have any tick labels, and others also lack some labels because of the axis was shared. I think I should use something like plt.setp(ax.get_xticklabels(), visible=True), but it doesn't work.
type: AnsweredQuestion
upvote count: 9
tagged with: matplotlib
linked to: http://stackoverflow.com/q/29266966
type: Question
score: 9
has title: matplotlib: Tick labels disappeared after set sharex in subplots
duplicate of: http://stackoverflow.com/q/29266966
has answer: http://stackoverflow.com/a/51553849
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51553849
favorite count: 0
tagged with: visible
has comment: http://stackoverflow.com/comment/90074410
has comment: http://stackoverflow.com/comment/124058687
tagged with: python

http://stackoverflow.com/comment/90038356
score: 0
comment on: http://stackoverflow.com/q/51533163
type: Comment
type: QuestionComment
has text: i.e. states clearly what you have, what you want. A simple I/O describing every possible I/O is enough.

http://stackoverflow.com/q/51633293
has comment: http://stackoverflow.com/comment/90232093
answer count: 1
has comment: http://stackoverflow.com/comment/90232445
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90231512
has title: Django : migration error
has comment: http://stackoverflow.com/comment/90232670
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/90231277
has body: I have a Django project. Everything worked , until suddenly I got some strange errors like "unknown argument 'pk'". Now I can't run admin, I am getting this error get() got an unexpected keyword argument 'session_key' I can't migrate , python can't understand my models.py changes and when I run the makemigrations command I am getting this error : Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 227, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\sql.py", line 53, in emit_post_migrate_signal **kwargs File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\dispatch\dispatcher.py", line 193, in send for receiver in self._live_receivers(sender) File "C:\Users\kostas\AppData\Local\Programs\Python\Python36\lib\site-packages\django\dispatch\dispatcher.py", line 193, in &lt;listcomp…
has answer: http://stackoverflow.com/a/51647230
score: 0

http://stackoverflow.com/q/51484410
has comment: http://stackoverflow.com/comment/89938409
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89938413
downvote count: 2
has comment: http://stackoverflow.com/comment/89938369
has answer: http://stackoverflow.com/a/51502497
linked to: http://stackoverflow.com/q/47019047
has comment: http://stackoverflow.com/comment/89973787
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89938240
score: 3
tagged with: algorithm
has comment: http://stackoverflow.com/comment/89973166
has title: Most efficient algorithm in Python to generate all 6x6 (0,1) matrices with sum in columns and rows lower than 2?
upvote count: 5
has comment: http://stackoverflow.com/comment/90052492
has comment: http://stackoverflow.com/comment/90060020
has comment: http://stackoverflow.com/comment/90054651
tagged with: matrix
has comment: http://stackoverflow.com/comment/89937971
has comment: http://stackoverflow.com/comment/89974098
has comment: http://stackoverflow.com/comment/90051875
answer count: 1
has body: I am working on a problem which requires me to find all 6x6 (0,1) matrices with some given properties: The sum of a row/column must be lower than 2. The matrices are not symmetrical. I am using this code: import numpy as np import itertools as it n=6 li=[] for i in it.product([0, 1], repeat = n**2): if (np.reshape(np.array(i), (n, n)).sum(axis=1) &lt; 2).all() and (np.reshape(np.array(i), (n, n)).sum(axis=0)&lt; 2).all() : if (np.transpose(np.reshape(np.array(i), (n, n))) != np.reshape(np.array(i), (n, n))).any(): li.append(np.reshape(np.array(i), (n, n))) The problem is that this method has to go through all 68719476736 (0,1) matrices. After this piece of code I still have to impose extra conditions. Is there a faster algorithm to find this list of matrices? Edit: The problem I am working on is one to find unique adjacency matrices (graph theory) up to a certain equivalence class. For instance, in the 4x4 version of the problem I wanted to find all (0,1) matrices such that: The sum in a row/column is lower than 2; Are not symmetrical, i.e. A^T != A; Also A^T != P^T A P, where P is a matrix representation of the dihedral group D8 (order 8) which is a subgroup of S4. After this last step I get a certain number of matrices. If A relates to B through the relation B = P^T A P, then it represents the same matrix. I follow to choose only one representative of this equivalence class. In the 4x4 problem I go from 65536 to 3. My estimate of the result after sorting through the first condition (sums) is 46080. In the 6x6 problem, the group of transformations P is of order 48.
has comment: http://stackoverflow.com/comment/90016364
favorite count: 0

http://stackoverflow.com/q/51570681
has body: I need to get raw objects using Django .objects.raw functions like : SELECT * FROM TEST_APP_DOCUMENT WHERE DATE BETWEEN to_date('0000-02-07','YYYY-MM-DD') AND to_date('2027-02-15', 'YYYY-MM-DD') in pgAdmin select return good result, but when i put it to django there is an error: File "C:\Users\User\Desktop\test_task\test_app\views.py", line 110 queryset = Document.objects.raw('SELECT * FROM TEST_APP_DOCUMENT WHERE DATE BETWEEN to_date('0000 - 02 - 07','YYYY - MM - DD') AND to_date('2027 - 02 - 15', 'YYYY - MM - DD')') ^ SyntaxError: invalid syntax what is the syntax problem?
accepted answer: http://stackoverflow.com/a/51570798
tagged with: postgresql
tagged with: python
type: AnsweredQuestion
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/51570798
has title: Django - get the query by date using postgresql "to_date"
score: 0
tagged with: to-date
answer count: 1

http://stackoverflow.com/a/51980431
downvote count: 0
score: 15
type: Answer
has body: Let's say you want to add 3 rows at the top of your table, you'll first have to shift down the merged cells and then insert the rows; For this we are going to use the shift(col_shift=0, row_shift=0) method; Help on method shift in module openpyxl.worksheet.cell_range: shift(col_shift=0, row_shift=0) method of openpyxl.worksheet.cell_range.CellRange instance Shift the range according to the shift values (*col_shift*, *row_shift*). :type col_shift: int :param col_shift: number of columns to be moved by, can be negative :type row_shift: int :param row_shift: number of rows to be moved by, can be negative :raise: :class:`ValueError` if any row or column index &lt; 1 The number of rows you want to insert must coincide with the numbers of rows you shift; So for your example you'll just have to: merged_cells_range = ws.merged_cells.ranges for merged_cell in merged_cells_range: merged_cell.shift(0,3) ws.insert_rows(1,3) So in the end the merged cells are preserved
accepted answer of: http://stackoverflow.com/q/51620536
has comment: http://stackoverflow.com/comment/90924602
answers question: http://stackoverflow.com/q/51620536
has comment: http://stackoverflow.com/comment/90924323
upvote count: 15
type: AcceptedAnswer

http://stackoverflow.com/comment/89984847
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51503779
has text: You don't define yaml_tag in your source. Is it really `u'!ClassifyTransform'`, or maybe something else? It is often best to make the tag a class variable on `ClassifyTransform` named `yaml_tag` and then do `yaml.add_constructor(ClassifyTransform.yaml_tag, transform_constructor)`
score: 1

http://stackoverflow.com/comment/90230483
has text: @AliÖztürk Correct, the reason Idle isn't going as fast as cmd is because of the string handling.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51632540

http://stackoverflow.com/q/51539424
type: Question
tagged with: pyspark
tagged with: spark-structured-streaming
has comment: http://stackoverflow.com/comment/90048741
score: 0
answer count: 2
tagged with: apache-spark
upvote count: 1
has title: How to get DataFrame in Structured Streaming?
has answer: http://stackoverflow.com/a/51581680
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/43297973
has body: I want to receive JSON strings from MQTT and parse them to DataFrames df. How can I do it? This is an example of Json message that I send to MQTT queue in order to process in Spark: { "id": 1, "timestamp": 1532609003, "distances": [2,5,7,8] } This is my code: from pyspark.sql import SparkSession spark = SparkSession \ .builder \ .appName("Test") \ .master("local[4]") \ .getOrCreate() # Custom Structured Streaming receiver reader = spark\ .readStream\ .format("org.apache.bahir.sql.streaming.mqtt.MQTTStreamSourceProvider")\ .option("topic","uwb/distances")\ .option('brokerUrl', 'tcp://127.0.0.1:1883')\ .load()\ .selectExpr("CAST(value AS STRING)", "CAST(timestamp AS STRING)") df = spark.read.json(reader.select("value").rdd) # Start running the query that prints the running counts to the console query = df \ .writeStream \ .format('console') \ .start() query.awaitTermination() But this code fails: py4j.protocol.Py4JJavaError: An error occurred while calling o45.javaToPython. : org.apache.spark.sql.AnalysisException: Queries with streaming sources must be executed with writeStream.start();; mqtt I tried to add start as follows: df = spark.read.json(reader.select("value").rdd) \ .writeStream \ .format('console') \ .start() But got the same error. My goal is to get a DataFrame df that I can further pass through ETL processes. UPDATE: The thread marked as an answer has not helped me solving the problem. First of all it gives the solution for Scala, while I am using PySpark. Secondly, I tested the solution proposed in the answer and it returned me the empty column json: reader = spark\ .readStream\ .schema(spark.read.json("mqtt_schema.json").schema) \ .format("org.apache.bahir.sql.streaming.mqtt.MQTTStreamSourceProvider")\ .option("topic","uwb/distances")\ .option('brokerUrl', 'tcp://127.0.0.1:1883')\ .load()\ .selectExpr("CAST(value AS STRING)", "CAST(timestamp AS STRING)") json_schema = spark.read.json("mqtt_schema.json").schema df = reader.withColumn('json', from_json(co…
has answer: http://stackoverflow.com/a/55701769
downvote count: 1

http://stackoverflow.com/q/51536411
has answer: http://stackoverflow.com/a/77746686
has answer: http://stackoverflow.com/a/59476594
answer count: 6
score: 42
favorite count: 0
has body: I am using cProfile try to profile my codes: pr = cProfile.Profile() pr.enable() my_func() # the code I want to profile pr.disable() pr.print_stats() However, the results are too long and cannot be fully displayed in the Spyder terminal (the function calls which take the longest time to run cannot be seen...). I also tried saving the results using cProfile.run('my_func()','profile_results') but the output file is not in human readable format (tried with and without .txt suffix). So my question is how can I save the profiling results to an external file which is human readable (like in a .txt format with all the words properly displayed)?
tagged with: profiling
has title: saving cProfile results to readable external file
tagged with: python-3.x
has answer: http://stackoverflow.com/a/53978443
has answer: http://stackoverflow.com/a/51541290
accepted answer: http://stackoverflow.com/a/51541290
downvote count: 0
has answer: http://stackoverflow.com/a/63190934
tagged with: python
upvote count: 42
tagged with: text
type: AnsweredQuestion
tagged with: cprofile
has answer: http://stackoverflow.com/a/52304147
type: Question
possible better answer: http://stackoverflow.com/a/53978443

http://stackoverflow.com/comment/90246024
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51639635
has text: Thanks for the article, will definitely be reading that
type: AnswerComment

http://stackoverflow.com/comment/90237555
type: QuestionComment
has text: Try the yahoo finance library
comment on: http://stackoverflow.com/q/51636537
score: 0
type: Comment

http://stackoverflow.com/a/52335091
has body: so your data looks like below code 8 time steps and 1 sample arr=array([[[1],[2],[3],[4],[5],[6],[7],[8]]]) but instead you have 100 time steps instead of 8 time steps like above example so if I want to reshape above array to make it 4 samples and each sample is 2 time steps the code will be: reshaped_arr=arr.reshape(4,2,1) use above example as guide
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51484969

http://stackoverflow.com/a/51502071
has body: you should replace: mensaje = file_name.read() with: mensaje = open(file_name).read()
answers question: http://stackoverflow.com/q/51501974
score: 0
type: Answer

http://stackoverflow.com/comment/90002915
has text: `writer.writerow(data)` will write all the data in single row
comment on: http://stackoverflow.com/q/51517209
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51540926
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/51540451
has comment: http://stackoverflow.com/comment/90050354
has comment: http://stackoverflow.com/comment/90242536
type: Answer
has body: Take a look at the Netmiko package ktbyers made, here. The package allows you create ssh connections and send commands/configurations/etc.

http://stackoverflow.com/q/51626281
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51628130
accepted answer: http://stackoverflow.com/a/51628130
has comment: http://stackoverflow.com/comment/90219524
score: 6
has comment: http://stackoverflow.com/comment/90217215
upvote count: 6
has answer: http://stackoverflow.com/a/51628959
has body: I'd like to convert to below Df1 to Df2. The empty values would be filled with Nan. Below Dfs are examples. My data has weeks from 1 to 8. IDs are 100,000. Only week 8 has all IDs, so total rows will be 100,000. I have Df3 which has 100,000 of id, and I want to merge df1 on Df3 formatted as df2. ex) pd.merge(df3, df1, on="id", how="left") -> but, formatted as df2 Df1&gt; wk, id, col1, col2 ... 1 1 0.5 15 2 2 0.5 15 3 3 0.5 15 1 2 0.5 15 3 2 0.5 15 ------ Df2&gt; wk1, id, col1, col2, wk2, id, col1, col2, wk3, id, col1, col2,... 1 1 0.5 15 2 1 Nan Nan 3 1 Nan Nan 1 2 0.5 15 2 2 0.5 15 3 2 0.5 15 1 3 Nan Nan 2 3 Nan Nan 3 3 0.5 15
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90218775
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/90218127
has comment: http://stackoverflow.com/comment/90217509
answer count: 2
has comment: http://stackoverflow.com/comment/90218338
downvote count: 0
has comment: http://stackoverflow.com/comment/90218263
possible better answer: http://stackoverflow.com/a/51628959
has comment: http://stackoverflow.com/comment/90217643
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/90217365
has comment: http://stackoverflow.com/comment/90218361
has title: convert rows to columns in pandas dataframe

http://stackoverflow.com/q/51574191
answer count: 0
linked to: http://stackoverflow.com/q/40660088
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90117375
has body: i'm abstracting a lot of pandas functionality for an application i'm building. I have a scenario where I need to get the value from the target column where the first occurrence of an unknown number conditions evaluates to true. So something like this: import pandas as pd #lets say this dataframe already has data in it with column names and number index rows. df = pd.Dataframe() targetCols:list = [targetColName1, targetColName2] compCols:list = [compColName1, compColName2] compVals:list = [compVals1, compVals2] #Some function that concatenates the compCols and compValues in to stirngs # look like: # (f"(df[['{compCols[0]}']=={compVals[0]}]) &amp; " # f"(df[['{compCols[1]}'] == {compVals[1]})") strExeString = ConcatenateExecutonString(compCols, compVals) dfView = pd.eval(strExeString) dfView = dfView[targetCols] return dfview.loc[0:] However the above causes me to scan through the data set a lot, I want to simply scan the DataFrame once until my conditions are met and then extract the target columns. Can we do this with pandas? I can do this with native list objects but if I can use pandas I'd like to since it can handle large sets more efficiently.
has comment: http://stackoverflow.com/comment/90117477
has title: Pandas Get first Occurance of values in dataframe
duplicate of: http://stackoverflow.com/q/40660088
score: 1
has comment: http://stackoverflow.com/comment/90117398
has comment: http://stackoverflow.com/comment/90114852
has comment: http://stackoverflow.com/comment/90114752
has comment: http://stackoverflow.com/comment/90116346
tagged with: pandas
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90116378
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90117195
has comment: http://stackoverflow.com/comment/90114225

http://stackoverflow.com/q/51493116
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/51494235
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51493182
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/51493182
has title: Blank quotes usage in dataframe
possible better answer: http://stackoverflow.com/a/51494235
has body: I am trying to combine OR | with df.loc to extract data. The code I have written extracts everything in the csv file. Here is the original csv file: https://drive.google.com/open?id=16eo29mF0pn_qNw-BGpZyVM9PBxv2aN1G import pandas as pd df = pd.read_csv("yelp_business.csv") df = df.loc[(df['categories'].str.contains('chinese', case = False)) | (df['name'].str.contains('subway', case = False)) | (df['categories'].str.contains('', case = False)) | (df['address'].str.contains('', case = False))] print df It looks like the blank quotes '' are not working in str.contains or the OR | doesn't work in df.loc. Instead of just returning rows with chinese restaurants (which are 4171 in number) and the row with the restaurant name subway, it returns all the 174,568 rows. EDITED The output I want should be all the rows of category chinese and all the rows of name subway while taking into consideration that the address might not have any assigned value or is null. import pandas as pd df = pd.read_csv("yelp_business.csv") cusine = 'chinese' name = 'subway' address #address has no assigned value or is NULL df = df.loc[(df['categories'].str.contains(cusine, case = False)) | (df['name'].str.contains(name, case = False)) | (df['address'].str.contains(address, case = False))] print df This code gives me an error NameError: name 'address' is not defined.
score: 0
answer count: 2

http://stackoverflow.com/q/51574834
has body: I have a json file that looks like this:: { "1": { "name": "item1" "symbol": "symbol1" "quotes": { "Amount": "45345" "other": "value" } } "734": { "name": "item1" "symbol": "symbol1" "quotes": { "Amount": "45345" "other": "value" } } "378": { "name": "item1" "symbol": "symbol1" "quotes": { "Amount": "45345" "other": "value" } } "2": { "name": "item1" "symbol": "symbol1" "quotes": { "Amount": "45345" "other": "value" } } } The "type" where the number is placed is a string value. if that helps. Normally someone is not trying to make extra work and label the "key" with the value of an integer... I am trying to place this file and some other json into a mysql data base. My research has taught me that this process will look ab bit like this:: # !!!!!!!!!!This is a copy paste from another solution::::::!!!!!!! json_obj = json.loads(response.decode('utf-8')) #print(json_obj["products"][0]["upc"]) for product in json_obj["products"]: print("upc:", product["upc"]) print("sku:", product["sku"]) print("salePrice:", product["salePrice"]) print('---') cursor.execute("INSERT INTO bestb (sku, upc, salePrice) VALUES (%s,%s,%s)", (product["sku"], product["upc"], product["salePrice"])) The above states that we will load the json file and read it, while writing the keys to cols. -- Makes sense... how do I perfrom this process with a loop of my integers.... I started with a while loop i = 1 while 1 &lt; 400: print(data - to mysql) I am using python to pull form the API, then "normalizing" the data to insert into mysql, there php will pull the data to some charts and graphs. Thank you for your help in advance!
tagged with: mysql
type: Question
has answer: http://stackoverflow.com/a/51575865
tagged with: database
score: 0
has title: Sort a json array in python that starts with an integer
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: php

http://stackoverflow.com/a/67088725
downvote count: 1
upvote count: 0
has body: I would use the CNN to predict the model of the car and then using a list of all the car prices it's easy enough to get the price, or if you dont care about the car model just use the prices as lables
answers question: http://stackoverflow.com/q/51484727
type: Answer
score: -1

http://stackoverflow.com/q/51587266
tagged with: python
tagged with: pip
tagged with: dockerfile
type: Question
has comment: http://stackoverflow.com/comment/90141360
has title: error: invalid command 'bdist_wheel' inside dockerfile
has comment: http://stackoverflow.com/comment/90143098
has comment: http://stackoverflow.com/comment/90144887
score: 0
has answer: http://stackoverflow.com/a/64859028
has comment: http://stackoverflow.com/comment/90146520
answer count: 1
has body: I am getting the following error: Building wheels for collected packages: fisher, goatools, wget ... Running setup.py bdist_wheel for fisher: finished with status 'error' ... error: invalid command 'bdist_wheel' ---------------------------------------- Failed building wheel for fisher Running setup.py clean for fisher Inside the this Dockerfile: FROM debian:stretch-backports RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends \ build-essential \ apache2 \ python-dev \ python-setuptools \ python-numpy \ python-mysqldb \ python-pip \ git wget \ ncbi-blast+ &amp;&amp; \ apt-get autoremove -y &amp;&amp; apt-get clean &amp;&amp; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* RUN pip install wheel fisher goatools What did I miss? Thank you in advance
type: UnansweredQuestion
tagged with: python-wheel

http://stackoverflow.com/comment/89943882
score: 0
has text: Not sure I understand the question, but if I open the file "500.bin", first 77 points belong to "400.bin" (and yaw=400) while the remainder is as it should be. This happens for every file except the first one, which is completely ok. You might say things go wrong exactly after the first file (1000 points).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51487104

http://stackoverflow.com/comment/90107770
type: Comment
type: QuestionComment
has text: Thank you so much guys! It helped a lot. It was a silly mistake! :)
comment on: http://stackoverflow.com/q/51569298
score: 0

http://stackoverflow.com/comment/90174700
comment on: http://stackoverflow.com/a/51603877
has text: Thank you a lot, that fixed it my issue.
type: AnswerComment
score: 0
type: Comment

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/51601915
tags question: http://stackoverflow.com/q/51574359
tags question: http://stackoverflow.com/q/51499034
tags question: http://stackoverflow.com/q/51603629
tag name: google-oauth

http://stackoverflow.com/q/51522281
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51625359
has body: I am getting below error. Can anyone help me solve the issue? 2018-07-25 20:31:19 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: tutorial) 2018-07-25 20:31:19 [scrapy.utils.log] INFO: Versions: lxml 4.2.3.0, libxml2 2.9.4, cssselect 1.0.3, parsel 1.5.0, w3lib 1.19.0, Twisted 18.7.0, Python 3.7.0 (default, Jul 23 2018, 20:22:55) - [Clang 9.1.0 (clang-902.0.39.2)], pyOpenSSL 18.0.0 (OpenSSL 1.1.0h 27 Mar 2018), cryptography 2.3, Platform Darwin-17.5.0-x86_64-i386-64bit 2018-07-25 20:31:19 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'tutorial', 'NEWSPIDER_MODULE': 'tutorial.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['tutorial.spiders']} 2018-07-25 20:31:19 [scrapy.middleware] WARNING: Disabled TelnetConsole: TELNETCONSOLE_ENABLED setting is True but required twisted modules failed to import: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/scrapy/extensions/telnet.py", line 13, in &lt;module&gt; from twisted.conch import manhole, telnet File "/usr/local/lib/python3.7/site-packages/twisted/conch/manhole.py", line 154 def write(self, data, async=False): ^ SyntaxError: invalid syntax
type: UnansweredQuestion
has title: TELNETCONSOLE_ENABLED setting is True but required twisted modules failed to import
tagged with: python
score: 3
upvote count: 3
tagged with: web-scraping
tagged with: scrapy
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/54458333

http://stackoverflow.com/comment/90064272
has text: Thankyou for reply, I've tried that but i am getting the same error
type: AnswerComment
comment on: http://stackoverflow.com/a/51548229
score: 0
type: Comment

http://stackoverflow.com/q/51616145
score: 1
has body: I am trying to create a simple widget using Orange. It calculates the mean of a given data input but I am unsure of how to iterate through the gui widget label to show each instance inside the widget box when it is uploaded to Orange. import Orange import Orange.data from Orange.widgets.widget import OWWidget, Input, Output from Orange.widgets import gui class OWtest(OWWidget): name = "Mean Data" description = "Mean of data attributes" #icon = ".svg" priority = 20 class Inputs: data = Input("Data", Orange.data.Table) class Outputs: infoData = Output("Info Data", Orange.data.Table) want_main_area = False def __init__(self): super().__init__() box = gui.widgetBox(self.controlArea, "Info") self.line_a = gui.widgetLabel(box, 'No data present') @Inputs.data def set_data(self, dataset): if dataset is not None: for d in dataset: print(d) average = lambda x: sum(x)/len(x) for x in dataset.domain.attributes: self.line_a.setText("%s %.2f" % (x.name, average([d[x] for d in dataset]))) print("%s %.2f" % (x.name, average([d[x] for d in dataset]))) At the moment it is only showing one line within the widget box, where i have only defined self.line_a. How would I loop through to create and display multiple widget labels to fit with the output produced by the average calculation? I am unsure on where the loop would fit or is there a simple step that i am missing? I have been looking through documentation and trying to fix the problem but can't seem to make it work.
has title: Orange widget development: How to iterate through gui widget label to display output of calculation
tagged with: loops
has answer: http://stackoverflow.com/a/51623561
type: Question
tagged with: orange
accepted answer: http://stackoverflow.com/a/51623561
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90169656
score: 0
type: AnswerComment
has text: @Orchard'sStory See the new function at the end.
type: Comment
comment on: http://stackoverflow.com/a/51601135

http://stackoverflow.com/comment/89939124
type: Comment
score: 1
has text: Good observation.
type: AnswerComment
comment on: http://stackoverflow.com/a/51485053

http://stackoverflow.com/comment/90198373
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51613845
has text: Yes, the right solution is the one proposed by the comment above.
score: 0

http://stackoverflow.com/comment/90252733
type: Comment
type: QuestionComment
has text: @Gowthaman I have tried it but the result didn't look good.
score: 0
comment on: http://stackoverflow.com/q/51624496

http://stackoverflow.com/q/51609299
tagged with: statistics
has title: Python np.lognormal gives infinite results for big average and St Dev
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/48014712
upvote count: 5
tagged with: python
type: AnsweredQuestion
has body: I am trying to draw the lognormal distribution for my data. using the following code: mu, sigma = 136519., 50405. # mean and standard deviation hs = np.random.lognormal(mu, sigma, 1000) #mean, s dev , Size count, bins, ignored = plt.hist(hs, 100, normed=True) x = np.linspace(min(bins), max(bins), 10000) pdf = (math.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))) #plt.axis('tight') plt.plot(x, pdf, linewidth=2, color='r') As you can see, my mean and sigma are big values, it creates the problem that hs goes to infinity that gives an error. While if I put something like mu =3 and sigma =1, it works, any suggestions for big numbers? Update 1 : I corrected my code with the first answer, but now I only get a straight line : mu, sigma = 136519 , 50405 # mean and standard deviation normal_std = np.sqrt(np.log(1 + (sigma/mu)**2)) normal_mean = np.log(mu) - normal_std**2 / 2 hs = np.random.lognormal(normal_mean, normal_std, 1000) print(hs.max()) # some finite number print(hs.mean()) # about 136519 print(hs.std()) # about 50405 # hs = np.random.lognormal(mu, sigma, 1000) #mean, s dev , Size # count, bins, ignored = plt.hist(hs, 100, normed=True) x = np.linspace(min(bins), max(bins), 10000) pdfT = []; for el in range (len(x)): pdfTmp = (math.exp(-(np.log(x[el]) - mu)**2 / (2 * sigma**2))) pdfT += [pdfTmp] #plt.axis('tight') pdf = np.asarray(pdfT) plt.plot(x, pdf, linewidth=2, color='r')
has answer: http://stackoverflow.com/a/51617073
downvote count: 0
accepted answer: http://stackoverflow.com/a/51617073
tagged with: standard-deviation
type: Question
tagged with: numpy
score: 5
tagged with: mean

http://stackoverflow.com/q/51561242
has answer: http://stackoverflow.com/a/51561603
has answer: http://stackoverflow.com/a/51561788
has comment: http://stackoverflow.com/comment/90090076
type: Question
score: 0
has body: I am trying to write a program to find a missing letter in an array of letters of alphabetical order. ex. [a,b,c,d,f] missing => 'e'. Right now I have this: def find_missing_letter(chars): # Creates variables of complete alphabet. alphabetLower = list(string.ascii_lowercase) enumeratedLower = [] alphabetUpper = list(string.ascii_uppercase) enumeratedUpper = [] # Checks if the function has to enumerate the upper- or lowercase alphabet. if(chars[0].islower()): for c, value in enumerate(alphabetLower, 1): enumeratedLower.append([c, value]) else: for c, value in enumerate(alphabetUpper, 1): enumeratedUpper.append([c, value]) # Checks at what letter the characters begin. # After that it checks if the following letters are equal to eachother. if(chars[0].isupper()): for x in range(1, 26): print enumeratedUpper[x][1] print 'char:' + chars[0] if(chars[0] == enumeratedUpper[x][1]): for i in range(enumeratedUpper[x][0], len(chars)): if(chars[i] != alphabetUpper[i]): return alphabetUpper[i] else: for x in range(1, 26): print enumeratedLower[x][1] print 'char:' + chars[0] if(chars[0] == enumeratedLower[x][1]): for i in range(enumeratedLower[x][0], len(chars)): if(chars[i] != alphabetLower[i]): return alphabetLower[i] However, the if statements if(chars[0] == enumeratedUpper[x][1]): and if(chars[0] == enumeratedLower[x][1]): are not working for some reason. The reason for this statement is because a given array of characters (chars), can start at a random letter (doesn't have to start at 'a' or 'A'). I put the print statement there to see what was wrong and the output is this: b char:o c char:o d char:o e char:o f char:o g char:o h char:o i char:o j char:o k char:o l char:o m char:o n char:o o char:o p char:o q char:o r char:o s char:o t char:o u char:o v char:o w char:o x char:o y char:o z char:o
answer count: 3
has title: Checking if two characters are equal to each other in python
has answer: http://stackoverflow.com/a/51561844
has comment: http://stackoverflow.com/comment/90090018
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90092064
tagged with: python

http://stackoverflow.com/comment/89940994
type: QuestionComment
has text: Checkout [applymap](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html)
score: 0
comment on: http://stackoverflow.com/q/51485955
type: Comment

http://stackoverflow.com/q/51486281
favorite count: 0
has comment: http://stackoverflow.com/comment/89941866
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/95299461
has comment: http://stackoverflow.com/comment/90015432
tagged with: python
has answer: http://stackoverflow.com/a/63578199
has comment: http://stackoverflow.com/comment/89941745
score: 2
has comment: http://stackoverflow.com/comment/89985388
tagged with: tkinter
has comment: http://stackoverflow.com/comment/112424328
type: Question
has comment: http://stackoverflow.com/comment/129833717
has comment: http://stackoverflow.com/comment/89941697
has comment: http://stackoverflow.com/comment/112458984
has answer: http://stackoverflow.com/a/65823399
has comment: http://stackoverflow.com/comment/89941735
answer count: 2
downvote count: 0
has title: Tkinter maximum number of widgets
has body: I've got quite a complicated GUI interface built by Tkinter library. It has several tabs and a lot of controls with possibility of dynamic adding and deleting them. And it seems that Tkinter has an internal maximum number of widgets, something about 10000 (including Frames). When it is exceeded new widgets are not created and even some strange graphical effects can appear outside the window (without any exceptions or messages). Did anyone face such problems? I wonder if there is a way to overcome this limitation.

http://stackoverflow.com/a/51618649
has comment: http://stackoverflow.com/comment/90204791
answers question: http://stackoverflow.com/q/51618575
has body: You aren't using expressions from the list of expressions, just string r'expr' Use expr directly, without quotes, e.g. re.search(expr, key, re.I): import re data = {r'\windows\temp\zzz.rar': 'xxx'} expressions = [r'(temp|tmp)\\[a-z]+\.rar'] for key, value in data.items(): for expr in expressions: matchStr = re.search(expr, key, re.I) if matchStr: print('Match found') break Prints: Match found
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51618575

http://stackoverflow.com/comment/89944066
comment on: http://stackoverflow.com/a/51487470
type: Comment
has text: Depends on what is `y`. If it's a column in your df, you can even write y.cummin().plot()
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90188802
score: 0
type: Comment
has text: Thanks <3 Finally... Understood.
type: AnswerComment
comment on: http://stackoverflow.com/a/51611970

http://stackoverflow.com/comment/130183925
has text: I have built a library which does a very similar thing with one exception that, from my perspective, is a deal breaker. You don't have to extend anything in order for it to work. It covers almost everything which you can find in the typing package: https://github.com/kodemore/chili
comment on: http://stackoverflow.com/a/70283539
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/a/51577768
type: Answer
has body: May not be the most efficient but works: Using shell command to move the types to separate folders (ran for both txt and doc extensions to create 2 folders): find /path-to-files-root/ -type f -name '*.txt' -exec mv -i {} /new-path-to-files/txt/ \; Then I ran: def get_all_files(path, pattern): #see https://stackoverflow.com/questions/17282887/getting-files-with-same-name-irrespective-of-their-extension datafiles = [] for root,dirs,files in os.walk(path): for file in fnmatch.filter(files, pattern): datafiles.append(file) return datafiles txt_files = [f for f in os.listdir(txt_path) if isfile(join(txt_path, f))] doc_files = [f for f in os.listdir(doc_path) if isfile(join(doc_path, f))] for i, txt_file in enumerate(txt_files): filename = (os.path.splitext(txt_file)[0]) doc_files = get_all_files(doc_path, '{0}.doc'.format(filename)) if len(doc_files)== 1: doc_file = doc_files[0] #do something with txt_file and doc_file
answers question: http://stackoverflow.com/q/51571270
score: 0

http://stackoverflow.com/comment/90067600
type: Comment
score: 1
has text: The Wikipedia page you link to already gives you a non-recursive solution.
comment on: http://stackoverflow.com/q/51550083
type: QuestionComment

http://stackoverflow.com/comment/90018011
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51524591
type: Comment
has text: https://docs.djangoproject.com/en/2.0/topics/email/

http://stackoverflow.com/q/51575704
has answer: http://stackoverflow.com/a/52438819
answer count: 1
tagged with: hp-alm
tagged with: rest
tagged with: python
has title: HP ALM Python rest api - How to properly pass cookie for API calls
type: AnsweredQuestion
has body: How to pass the HP ALM authentication session object for rest api calls. I am following some examples to connect to HP ALM via REST API to run basic CRUD operations. One of the example - https://github.com/vkosuri/py-hpalm/blob/master/hpalm/hpalm.py Below is the code snippet to establish the connection which is working perfectly fine. I am getting 200 OK response for login. headers = {'Cookie' : lwssocookie} headers["Accept"] = 'application/xml' login_url = self.base_url + '/qcbin/authentication-point/authenticate' resp = requests.get(login_url, headers=headers, auth=HTTPBasicAuth(self.username, self.password), verify=self.verify) alm_session = resp.headers['Set-Cookie'] logger.debug("Is QC session launched: %s" %alm_session) cookie = ";".join((lwssocookie, alm_session)) But all the subsequent operations are failing with unauthorized error even though I added the cookies to header self.headers['cookie'] = cookie url = self.base_url + '/qcbin/rest/domains/' + self.domain + '/projects/' + self.project + '/test-instances' response = requests.get(url, params=params, headers=self.getheaders()) Can anyone please suggest how to hold the session to run operations and what am I missing here. I also tried to pass cookies in get call as below and even that didn't work. response = requests.get(url, params=params, headers=self.getheaders(), cookies=cookie) Thank you in advance
type: Question
accepted answer: http://stackoverflow.com/a/52438819
score: 0

http://stackoverflow.com/a/51498251
downvote count: 0
has comment: http://stackoverflow.com/comment/89965146
type: Answer
has comment: http://stackoverflow.com/comment/89965209
has comment: http://stackoverflow.com/comment/89967177
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89965511
has body: One method you could try is assertRaises and call the assertLessEqual method from within the with block: import unittest class Test1(unittest.TestCase): def test_between(self): with self.assertRaises(AssertionError) as e: self.assertLessEqual(999, 998, "Not less") with self.assertRaises(AssertionError) as e: self.assertLessEqual(999, 500, "Not less") if __name__ == '__main__': unittest.main() You should find that the behaviour is the same with assertTrue or assertFalse as with assertLessEqual which has the following description: Just like self.assertTrue(a &lt;= b), but with a nicer default message. You should find that many of the unit test methods are simply nice wrappers for an assertTrue or assertFalse call. Of course, a simplistic approach to solving your problem would be to either rearrange a and b in your assertLessEqual call or user assertGreaterEqual instead. If you have a large number of similar tests to run, you could also look at subTest. This allows you to run the same test code for a number of variables: import unittest class Test1(unittest.TestCase): def test_between(self): for i in range(10): with self.subTest(i=i): self.assertLessEqual(i, 5) if __name__ == '__main__': unittest.main() The above test results in 4 failures, an example of one: FAIL: test_between (__main__.Test1) (i=9) ---------------------------------------------------------------------- Traceback (most recent call last): File "scratchpad.py", line 7, in test_between self.assertLessEqual(i, 5) AssertionError: 9 not less than or equal to 5
accepted answer of: http://stackoverflow.com/q/51497968
answers question: http://stackoverflow.com/q/51497968
type: AcceptedAnswer

http://stackoverflow.com/comment/89993885
score: 0
has text: Does the file exist? ave you tried to manually install CapnProto?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51512763

http://stackoverflow.com/comment/90190053
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51612107
has text: I just tested in 2.0.2 and its working normal as in 2.3.0. so i guess you have to see where the error is generating at
type: AnswerComment

http://stackoverflow.com/comment/90097092
score: 0
comment on: http://stackoverflow.com/q/51562341
type: Comment
type: QuestionComment
has text: Oh, wait. Is the `ValueError` is getting thrown from the `unsupervised_wiener` line, not the `convolve2d` line? I think that function also takes a 2D input (http://scikit-image.org/docs/dev/api/skimage.restoration.html#skimage.restoration.unsupervised_wiener) so you'll need to use a similar for loop there as well.

http://stackoverflow.com/comment/90070838
score: 0
comment on: http://stackoverflow.com/q/51551814
type: Comment
type: QuestionComment
has text: Where I add the array people?

http://stackoverflow.com/comment/90151845
comment on: http://stackoverflow.com/a/51591405
score: 3
type: AnswerComment
has text: You should explain how this solves the question. It works for examples 1 and 2, not for 3 and 4.
type: Comment

http://stackoverflow.com/comment/90058975
has text: I'm not familiar with the intricacies of the different scipy window functions, but using df.rolling() with one of the non-evenly-weighted windowing functions from https://docs.scipy.org/doc/scipy/reference/signal.html#window-functions may be a place to start.
comment on: http://stackoverflow.com/q/51545419
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51548633
type: AnsweredQuestion
upvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90065592
tagged with: python
has body: Can anyone convert the below function into a list compressions please! def something(x,y): result = [] for i in x: for j in y: if i['username'] == j['username']: result.append(j) if i['username'] != result[len(result)-1]['username']: result.append(i) return result This is best I could come up with but it is not correct. result = [user for user in users for contact in contacts if contact['username'] == user['username']] Thank you for any help.
has answer: http://stackoverflow.com/a/51548782
downvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/90064998
tagged with: nested-loops
accepted answer: http://stackoverflow.com/a/51548782
tagged with: list-comprehension
score: -3
has title: Convert function into a nested list comprehension (Python)

http://stackoverflow.com/comment/91610709
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51619205
has text: Can you raise a new ticket for the same ?

http://stackoverflow.com/comment/90136516
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51581962
has text: Have you installed the `requests-toolbelt`, and followed the additional set up instructions for App Engine? https://google-auth.readthedocs.io/en/latest/user-guide.html#the-app-engine-standard-environment
score: 0

http://stackoverflow.com/q/51567645
downvote count: 0
answer count: 1
has body: I have some stock data, downloaded and made into a pandas series via import quandl as qd api = '1uRGReHyAEgwYbzkPyG3' qd.ApiConfig.api_key = api data = qd.get_table('WIKI/PRICES', qopts={'columns': ['ticker', 'date', 'high', 'low', 'open', 'close']}, ticker=['AMZN'], date={'gte': '2000-01-01', 'lte': '2014-03-10'}) data.reset_index(inplace=True, drop=True) price = pd.Series(data.iloc[:,2].values,index=pd.to_datetime(data.iloc[:,1])) And with statsmodels, I want to graph an ARIMA model showing the following: the original data, the fitted values overlapping some original data, and the future forecast + confidence interval up to specified distance. The picture above comes from the statsmodels documentation here, but following their code throws me weird errors. fig, ax = plt.subplots() ax = price.loc['2012-01-03':].plot(ax=ax, label='observed') fig = model_fit.plot_predict('2014-01-03','2015-01-03', dynamic=False, ax=ax, plot_insample=False) plt.show() Error below, KeyError Traceback (most recent call last) pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() KeyError: 1420243200000000000 During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) ~/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 2524 try: -&gt; 2525 return self._engine.get_loc(key) 2526 except KeyError: pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc() pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc() KeyError: Timestamp('2015-01-03 00:00:00') During handling of the above exception, another exception occurred: KeyError Traceback (most recent call last) pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc() pandas/_libs/hashtable_class_helper.p…
favorite count: 0
tagged with: arima
tagged with: python
score: 2
has title: Statsmodels: difficulty overlaying ARIMA forecast with confidence bounds on original data
upvote count: 2
type: UnansweredQuestion
type: Question
tagged with: statsmodels
tagged with: matplotlib
tagged with: graph
has answer: http://stackoverflow.com/a/51585908

relative-path
type: Tag
tags question: http://stackoverflow.com/q/51589612
tag name: relative-path

automation
tags question: http://stackoverflow.com/q/51530240
tag name: automation
tags question: http://stackoverflow.com/q/51502558
type: Tag
tags question: http://stackoverflow.com/q/51554027
tags question: http://stackoverflow.com/q/51572872

http://stackoverflow.com/comment/90156612
type: Comment
comment on: http://stackoverflow.com/a/51592924
type: AnswerComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177029/discussion-between-cegprakash-and-stephen-mallette).
score: 0

http://stackoverflow.com/a/51580011
has comment: http://stackoverflow.com/comment/90125217
type: Answer
accepted answer of: http://stackoverflow.com/q/51579852
has comment: http://stackoverflow.com/comment/90125279
answers question: http://stackoverflow.com/q/51579852
has body: Your code is not properly indented. class Employee: def __init__(self, first, last): self.first = first self.last = last @property def email(self): #same level indentation as __init__() or it'll have scope under __init__() method only return '{}.{}@email.com'.format(self.first, self.last) @property def fullname(self): return '{} {}'.format(self.first, self.last) emp1 = Employee('Aquib', 'Javed') emp1.email # Since you've mentioned `email` as property and returning as string, you should just use its property's name emp1.fullname # same goes here too print(emp1.fullname)
has comment: http://stackoverflow.com/comment/90125252
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/90365618
comment on: http://stackoverflow.com/a/51635698
score: 1
type: AnswerComment
type: Comment
has text: Python comes with the `pydoc` command to list documentation that is part of any Python class, so you can type `pydoc pexpect` and `pydoc pexpect.pxssh` for the documentation. `original_prompt` is used in `expect()` so it is a regex.

http://stackoverflow.com/a/51555938
type: Answer
has body: After carefully examining your implementations, I observed that all the hyperparameters match except for the batch size. I don't agree with the answer from @Ultraviolet, because the default kernel_initializer of tf.layers.conv2d is also Xavier (see the TF implementation of conv2d). The learning curves don't match for the following two reasons: The parameters from the Keras implementation (version 2) are receiving many more updates than those of the TF implementation (version 1). In version 1, you're feeding the full dataset simultaneously into the network at each epoch. This results in only 30 adam updates. In contrast, version 2 is performing 30 * ceil(len(training_label_data)/batch_size) adam updates, with batch_size=4. The updates of version 2 are noisier than those of version 1, because the gradients are averaged over less samples.
score: 3
has comment: http://stackoverflow.com/comment/90080560
downvote count: 0
has comment: http://stackoverflow.com/comment/90080085
has comment: http://stackoverflow.com/comment/90080002
accepted answer of: http://stackoverflow.com/q/51546176
answers question: http://stackoverflow.com/q/51546176
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90080393
has comment: http://stackoverflow.com/comment/90080484
has comment: http://stackoverflow.com/comment/90080145

http://stackoverflow.com/comment/90037826
has text: Although it doesn't solve my problem completely, it could still be a solution for most scenario, I'd like to accept this answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51533902
type: Comment

http://stackoverflow.com/a/51620347
has body: This is not a bug and is the expected behavior. Scikit will not make assumptions after the model has been trained about what features should have been included or not. Instead, when you call fit for a model there is an implicit assumption being made that you have already performed feature selection to remove features that will not be important to the model. Once fit the expectation is that you will provide a dataset of the same size that was used to fit the model regardless of whether the features are important or not.
answers question: http://stackoverflow.com/q/51619180
accepted answer of: http://stackoverflow.com/q/51619180
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/comment/90071423
comment on: http://stackoverflow.com/q/51534890
score: 0
type: QuestionComment
type: Comment
has text: K-means can't use this data type. This will be a rather challenging task, you'll need to read several books and tutorials. This too broad to be answered here.

http://stackoverflow.com/comment/90249790
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51641581
has text: Yeah, I came up with about the same solution, just a bit too late. Since there are still some minor differences, I though it to be useful to post anyways. @Fiver If in doubt, this is probably the solution to accept, because mine just came later and only brings marginal improvement.

http://stackoverflow.com/q/51577441
favorite count: 0
has answer: http://stackoverflow.com/a/63382509
has comment: http://stackoverflow.com/comment/100156988
score: 48
answer count: 5
has title: How to seed Django project ? - insert a bunch of data into the project for initialization
has answer: http://stackoverflow.com/a/51577650
upvote count: 48
has answer: http://stackoverflow.com/a/55223981
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90121325
has answer: http://stackoverflow.com/a/57116699
type: Question
has answer: http://stackoverflow.com/a/51577456
tagged with: django-queryset
downvote count: 0
has body: I'ved been developing in Django and was wondering if there is a way to seed data into the database in Django. In ruby on rails, I use seed.rb and then run "rake db:seed" in command line. Main reason I want to seed some data on statuses, types, etc for the project initialization. Is there something similar ?
tagged with: seed

http://stackoverflow.com/comment/90052091
type: QuestionComment
score: 0
has text: As @Aran-Fey points out, though, that means that you cannot assume that any given instance of `abc` has a `b` attribute, because it depends how it was created. This violates the Liskov substitution principle and will lead to bugs and/or complexity.
comment on: http://stackoverflow.com/q/51541712
type: Comment

http://stackoverflow.com/comment/90042604
type: QuestionComment
comment on: http://stackoverflow.com/q/51536478
has text: can you provide the code that you can replicate? you are missing the imports, hard to guess what is `chi2.rvs`?
score: 0
type: Comment

http://stackoverflow.com/comment/90246293
type: AnswerComment
score: 0
has text: I get that the non default argument must come before the default one but how can it when the parent arguments initialise before adding the child arguments?
type: Comment
comment on: http://stackoverflow.com/a/51595616

http://stackoverflow.com/comment/90183587
has text: If color of the font is different to the hexagon, you might try to filter text out before pattern matching.
comment on: http://stackoverflow.com/q/51582034
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90058888
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51523332
type: Comment
has text: Thanks WaKo, This is what I needed.\n Please look into my comment on @CZoellner answer. I want to achieve some other things. Please look into this.

http://stackoverflow.com/q/51620933
upvote count: 2
has body: I'm new to plotly for python, and ran into a problem today: when I do scatter plots, hover display only works if the points have different x values. Please see the attached example. I've tried formatting hoverinfo as "x+y", but it didn't make a difference. Is there a workaround for this, so I can display entries with different y values but same x value? Many thanks in advance for the help! x=np.zeros(10) y=np.arange(0,10,1) trace1=go.Scatter(x=x, y=y) data1=[trace1] `enter code here`plotly.offline.iplot(data1) only one hover label shows up:
has title: Plotly in python: hover display doesn't differentiate along x axis?
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51627877
tagged with: plotly
type: Question
has comment: http://stackoverflow.com/comment/90219743
accepted answer: http://stackoverflow.com/a/51627877
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/45101562

http://stackoverflow.com/comment/90069859
has text: Works on my machine too, no errors. Looks like a Pandas installation issue.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51551267

http://stackoverflow.com/comment/90180282
comment on: http://stackoverflow.com/q/51607406
score: 0
has text: What kind of exception is raised in <your logic>? This might have to do with https://bugs.python.org/issue9400
type: Comment
type: QuestionComment

http://stackoverflow.com/a/66711754
upvote count: 2
answers question: http://stackoverflow.com/q/51603459
has comment: http://stackoverflow.com/comment/122496487
type: Answer
score: 2
downvote count: 0
has body: The exact same thing happened with me today, turns out i was missing the comma after 'pages.apps.PageConfig'. Super silly mistake

http://stackoverflow.com/q/51574119
tagged with: python
has title: Array / Dataframe manipulation in python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51577060
has answer: http://stackoverflow.com/a/51574589
possible better answer: http://stackoverflow.com/a/51577060
type: Question
tagged with: indexing
tagged with: dataframe
has body: Is there an efficient way to create an array or dataframe that outputs the following (don't need the Price column in the far left and top rows): 18.00 18.50 17.25 12.50 14.50 Price Date 12/18/1992 12/21/1992 12/22/1992 12/23/1992 12/24/1992 18.00 12/18/1992 0% 3% -4% -31% -19% 18.50 12/21/1992 0% -7% -32% -22% 17.25 12/22/1992 0% -28% -16% The input would be a csv file with 1 column, indexed by a list of dates. So for the example above it would be: Date Price 12/18/1992 18.00 12/21/1992 18.50 12/22/1992 17.25 I'm trying to calculate the price change for every date pair that's chronological. So date_1 / date_0, date_2 / date_0, and so forth. I want to leave blanks in the date pairs that aren't chronological. So far i just have this...: import pandas as pd import numpy as np import datetime import matplotlib.pyplot as plt file_loc = "C:\\Users\\Price Data\\CL1.csv" df = pd.read_csv(file_loc, parse_dates = True) df.set_index('Date', inplace = True)
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51574589
score: 0
answer count: 2
tagged with: arrays

http://stackoverflow.com/comment/90223722
type: AnswerComment
score: 0
type: Comment
has text: >>> import tensorflow as tf Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named tensorflow
comment on: http://stackoverflow.com/a/51629636

http://stackoverflow.com/comment/89939262
comment on: http://stackoverflow.com/q/51485008
score: 0
type: QuestionComment
type: Comment
has text: oops I meant to put a % in that, thanks for the catch. I am running it through Visual Studio Code and I have python 3.7. Also can you explain why my if max%x == 0 works the way it works? Shouldn't it be max//x %0?

http://stackoverflow.com/a/51552635
answers question: http://stackoverflow.com/q/51552554
downvote count: 0
score: 1
upvote count: 1
has body: Looks like you need list comprehension Ex: s_headers=[] headers=['DRIVER’S NAME', 'LICENSE', 'PH NUMBER', 'DOB', 'HIRE DAY'] s_headers = [str(int(head)) if isinstance(head, float) else head for head in headers] print(s_headers)
type: Answer

http://stackoverflow.com/q/51584556
tagged with: django-celery
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90134960
has comment: http://stackoverflow.com/comment/90135711
has answer: http://stackoverflow.com/a/51585048
has body: I want to check basic Celery functionality inside official demo Celery project for django with code available here. My modification is the demoapp/views.py (and of course urls.py to point to this view): from __future__ import absolute_import, unicode_literals from django.http import HttpResponse from demoapp.tasks import add, mul, xsum def home(request): return HttpResponse("Your output is: %s" % mul.delay(22,4).get(timeout=1) ) which always gives timeout error, though the terminal of running Celery worker shows that task was received and displays correct return value. However, if I start python shell python ./manage.py shell and then run from demoapp.tasks import add, mul, xsum mul.delay(22,4).get(timeout=1) I immediately get the expected result. What may be the problem? Rabbitmq server is running, I use Celery 4.2.1, django 2.0.6. demoapp/tasks.py: from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def add(x, y): return x + y @shared_task def mul(x, y): return x * y @shared_task def xsum(numbers): return sum(numbers) proj/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) proj/settings.py ... CELERY_BROKER_URL = 'amqp://guest:guest@localhost//' CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_BACKEND = 'db+sqlite:///results.sqlite' CELERY_TASK_SERIALIZER = 'json' ...
favorite count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
tagged with: celery
has title: Celery get() works in python shell but not in Django view
score: 1

http://stackoverflow.com/comment/90015922
has text: Which widget is the master is only used in `pack`, `grid` and `place`. Adding a tab does not care which widget is master.
comment on: http://stackoverflow.com/q/51522174
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90210792
has text: yes sir that seems to work. This seems to be something wrong in how I am configuring pycharm.
comment on: http://stackoverflow.com/q/51622423
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51546408
has comment: http://stackoverflow.com/comment/90060744
has body: I am using the following code to try to use the Fpgrowth algorithm but I get '' as items in the basket when I want to remove them. What is the proper way to do this? from pyspark.mllib.fpm import FPGrowth from pyspark import SparkConf from pyspark.context import SparkContext sc = SparkContext.getOrCreate(SparkConf().setMaster("local[*]")) data = sc.textFile("C:\\Users\\marka\\Downloads\\Assig2.txt") data.map(lambda line: line.strip().split()) transactions = data.map(lambda line: line.strip().split('\t')) #notempty = transactions.map(lambda x: x is not '') unique = transactions.map(lambda x: list(set(x))).cache() model = FPGrowth.train(unique, minSupport=0.7, numPartitions=10) result = model.freqItemsets().collect() for fi in result: print(fi) Output: FreqItemset(items=[''], freq=100) FreqItemset(items=['Soap'], freq=99) FreqItemset(items=['Soap', ''], freq=99) FreqItemset(items=['Water'], freq=99) FreqItemset(items=['Water', 'Soap'], freq=99) FreqItemset(items=['Water', 'Soap', ''], freq=99) FreqItemset(items=['Water', ''], freq=99) FreqItemset(items=['Beer'], freq=88) FreqItemset(items=['Beer', 'Water'], freq=88) FreqItemset(items=['Beer', 'Water', 'Soap'], freq=88) FreqItemset(items=['Beer', 'Water', 'Soap', ''], freq=88) FreqItemset(items=['Beer', 'Water', ''], freq=88) FreqItemset(items=['Beer', 'Soap'], freq=88) FreqItemset(items=['Beer', 'Soap', ''], freq=88) FreqItemset(items=['Beer', ''], freq=88) FreqItemset(items=['Rock_Salt'], freq=80) FreqItemset(items=['Rock_Salt', 'Water'], freq=79) FreqItemset(items=['Rock_Salt', 'Water', 'Soap'], freq=79) FreqItemset(items=['Rock_Salt', 'Water', 'Soap', ''], freq=79) FreqItemset(items=['Rock_Salt', 'Water', ''], freq=79) FreqItemset(items=['Rock_Salt', 'Soap'], freq=79) FreqItemset(items=['Rock_Salt', 'Soap', ''], freq=79)
has answer: http://stackoverflow.com/a/51546573
has title: How do I properly remove tabs and split in Python?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90060926
accepted answer: http://stackoverflow.com/a/51546573
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90060817
type: AnsweredQuestion
tagged with: formatting
type: Question

http://stackoverflow.com/comment/90203867
comment on: http://stackoverflow.com/q/51618953
type: QuestionComment
score: 0
has text: The exact same approach as in your first solution for lists works for NumPy arrays; is that not enough?
type: Comment

http://stackoverflow.com/comment/90219535
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51627001
has text: @SubodhJoshi I have found a way to do it in one line - Please read my answer
score: 0

http://stackoverflow.com/a/51630076
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51629294
type: Answer
has body: Well it almost exists: sys.stdout = sys.__stdout__ reset stdout to its original value at the start of program. Simply it but might not do what you want. You might stack sys.stdout redirections, and in that case, it would make sense to revert to previous redirection instead of the original one. A real use case for it in the IDLE interactive interpretor. The original stdout will be None on Windows because it is a GUI program, and will be directed to the terminal from where you started it on Linux. In either case after a redirection, you certainly do not want to use that default original value, but the one that was setup by IDLE. That is the reason why you should always save the original standard output when you redirect it, and restore it when you no longer need the redirection.
upvote count: 1
answers question: http://stackoverflow.com/q/51629294
score: 1

http://stackoverflow.com/q/51588981
possible better answer: http://stackoverflow.com/a/51589089
has body: python 2.7 DJANGO 1.11.14 win7 when I click the link in FWinstance_list_applied_user.html it was supposed to jump to FW_detail.html but nothing happened url.py urlpatterns += [ url(r'^myFWs/', views.LoanedFWsByUserListView.as_view(), name='my-applied'), url(r'^myFWs/(?P<pk>[0-9]+)$', views.FWDetailView.as_view(), name='FW-detail'), views.py: class FWDetailView(LoginRequiredMixin,generic.ListView): model = FW template_name = 'FW_detail.html' models.py class FW(models.Model): ODM_name = models.CharField(max_length=20) project_name = models.CharField(max_length=20) FW_detail.html {% block content %} FW request information: {{ FW.ODM_name}};{{ FW.project_name}} please download using this link: {{ FW.download }} {% endblock %} FWinstance_list_applied_user.html {% block content %} Applied FWs {% if FW_list %} {% for FWinst in FW_list %} {% if FWinst.is_approved %} --> {{FWinst.ODM_name}} ({{ FWinst.project_name }}) {% endif %} {% endfor %} {% else %} Nothing. {% endif %} {% endblock %} the image of FWinstance_list_applied_user.html, when I click the link CSR, nothing happened
type: AnsweredQuestion
tagged with: django
type: Question
accepted answer: http://stackoverflow.com/a/51589093
has answer: http://stackoverflow.com/a/51589089
answer count: 2
has answer: http://stackoverflow.com/a/51589093
has title: link in html do not function
score: 0
tagged with: python

http://stackoverflow.com/comment/90130716
type: Comment
has text: When i use it instead of the for loop, Nothing is displayed (i change book_types instead booktypes).
type: AnswerComment
comment on: http://stackoverflow.com/a/51582612
score: 0

pyspark
tags question: http://stackoverflow.com/q/51599510
tags question: http://stackoverflow.com/q/51550341
tags question: http://stackoverflow.com/q/51608432
tags question: http://stackoverflow.com/q/51528485
tags question: http://stackoverflow.com/q/51607457
tags question: http://stackoverflow.com/q/51498202
tags question: http://stackoverflow.com/q/51598727
tags question: http://stackoverflow.com/q/51575997
tags question: http://stackoverflow.com/q/51501517
type: Tag
tags question: http://stackoverflow.com/q/51534667
tags question: http://stackoverflow.com/q/51521655
tags question: http://stackoverflow.com/q/51610195
tags question: http://stackoverflow.com/q/51495155
tags question: http://stackoverflow.com/q/51634947
tags question: http://stackoverflow.com/q/51601639
tags question: http://stackoverflow.com/q/51537178
tags question: http://stackoverflow.com/q/51560502
tags question: http://stackoverflow.com/q/51546028
tags question: http://stackoverflow.com/q/51614459
tags question: http://stackoverflow.com/q/51633822
tags question: http://stackoverflow.com/q/51527066
tags question: http://stackoverflow.com/q/51539424
tags question: http://stackoverflow.com/q/51623121
tags question: http://stackoverflow.com/q/51609339
tags question: http://stackoverflow.com/q/51624601
tags question: http://stackoverflow.com/q/51528769
tags question: http://stackoverflow.com/q/51522719
tags question: http://stackoverflow.com/q/51500288
tags question: http://stackoverflow.com/q/51602842
tags question: http://stackoverflow.com/q/51622685
tags question: http://stackoverflow.com/q/51540331
tags question: http://stackoverflow.com/q/51520714
tags question: http://stackoverflow.com/q/51491903
tags question: http://stackoverflow.com/q/51610133
tag name: pyspark
tags question: http://stackoverflow.com/q/51504076
tags question: http://stackoverflow.com/q/51539088
tags question: http://stackoverflow.com/q/51528625
tags question: http://stackoverflow.com/q/51506820
tags question: http://stackoverflow.com/q/51607061
tags question: http://stackoverflow.com/q/51503609
tags question: http://stackoverflow.com/q/51486264

http://stackoverflow.com/comment/90152671
score: 0
comment on: http://stackoverflow.com/a/51593245
has text: Is there any way to use your solution in a way that I don't have to write 'prop1 = MyProp("prop1")' but instead something like: 'add_prop("prop1")'
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/90239398
type: Comment
type: QuestionComment
has text: What does not work? I have posted an answer.
score: 0
comment on: http://stackoverflow.com/q/51637301

http://stackoverflow.com/q/51576590
upvote count: 2
has answer: http://stackoverflow.com/a/51576650
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90118762
type: Question
accepted answer: http://stackoverflow.com/a/51576650
downvote count: 0
tagged with: class
answer count: 1
has body: I don't understand why when trying to create an instance of the class 'Deck', PyCharm returns an error that 'Deck is not callable. Main.py if __name__ == '__main__': while play_again is True: player_count: int = int(input("Enter number of players: ")) print(player_count) game_deck: Deck = Deck("game") #error on this line shuffle(game_deck) burn_deck = Deck Deck.py class Deck: card_sequence: Card = [] deck_type = "" def __init__(self, deck_type): card_suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] card_ranks = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', 'Jack', 'Queen', 'King'] self.deck_type = deck_type if self.deck_type == "player": for i in range(2): self.card_sequence = [random.random() for _ in range(2)] elif self.deck_type == "game": for i in card_suits: for j in card_ranks: new_card = Card(i, j) self.card_sequence.push(new_card) for _ in self.card_sequence: self.card_sequence.append(random.random()) elif self.deck_type == "burn": self.size = 0 self.card_sequence = [] Error Traceback (most recent call last): File "C:/Users/Chris/PycharmProjects/BlackJack/Main.py", line 36, in &lt;module&gt; game_deck: Deck = Deck("game") TypeError: 'module' object is not callable
favorite count: 0
has comment: http://stackoverflow.com/comment/90118740
has title: Can't pass parameter when creating an instance of a class

http://stackoverflow.com/q/51513808
has comment: http://stackoverflow.com/comment/89996009
has comment: http://stackoverflow.com/comment/89996142
has comment: http://stackoverflow.com/comment/89996098
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89995928
upvote count: 0
has answer: http://stackoverflow.com/a/51513905
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89996518
tagged with: python
has body: how can i open file and save file to new dir? here is my code from tkinter import * from tkinter import filedialog root = Tk() def browsefunc(): filename = filedialog.askopenfilename(filetypes=(("Pilih PDF", "*.pdf"), ("Semua File", ".*"))) pathlabel.config(text=filename) browsebutton = Button(root, text="Pilih PDF", command=browsefunc) browsebutton.pack() pathlabel = Label(root) def savefunc(): filename = filedialog.asksaveasfile(initaldir="/", filetypes=(("PDF","*.pdf"),("Semua File", ".*"))) pathlabel.config(text=filename) savebutton = Button(root, text="PDF", command=savefunc) savebutton.pack() pathlabel = Label(root) pathlabel.pack() mainloop() i can't save the file
score: -1
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/51513905
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/89996075
has title: How can I open file from dir and save file to new dir?

http://stackoverflow.com/comment/90158584
score: 0
comment on: http://stackoverflow.com/q/51593052
has text: @alexis yes, I definitely exaggerated, but with some luck the defaults "just work" in one's case, and you definitely don't need work-arounds.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51527113
type: Answer
has body: If you want to convert a Python Dictionary to JSON using the json.dumps() method. ` import json from decimal import Decimal d = {} d["date"] = "2017-07-24" d["quantity"] = "149.7619" print json.dumps(d, ensure_ascii=False) `
downvote count: 0
has comment: http://stackoverflow.com/comment/90024241
answers question: http://stackoverflow.com/q/51526076
has comment: http://stackoverflow.com/comment/90023342
score: 1
has comment: http://stackoverflow.com/comment/90023007
has comment: http://stackoverflow.com/comment/90023211
upvote count: 1
has comment: http://stackoverflow.com/comment/90024073

http://stackoverflow.com/a/51861258
has body: Preprocess your string with a simple double replace - first escape all the quotation marks, then replace all the escaped apostrophes with a quotation mark - which will simply invert the escapes, e.g.: # we'll define it as an object to keep the validity src = "{\\'text\\' : \\'This is the first time I've tried really \"fancy food\" at a...\\'}" # The double escapes are just so we can type it properly in Python. # It's still the same underneath: # {\'text\' : \'This is the first time I've tried really "fancy food" at a...\'} preprocessed = src.replace("\"", "\\\"").replace("\\'", "\"") # Now it looks like: # {"text" : "This is the first time I've tried really \"fancy food\" at a..."} Which is now a valid JSON (and a Python dictionary, incidentally) so you can go ahead and parse it: import json parsed = json.loads(preprocessed) # {'text': 'This is the first time I\'ve tried really "fancy food" at a...'} Or: import ast parsed = ast.literal_eval(preprocessed) # {'text': 'This is the first time I\'ve tried really "fancy food" at a...'} UPDATE: Based on the posted line, you actually have a (valid) representation of a 7-element tuple containing a string representation of a dictionary as its third element, you don't need to preprocess the string at all. What you need is to first evaluate the tuple, then post-process the inner dict with another level of evaluation, i.e.: import ast # lets first read the data from a 'input.txt' file so we don't have to manually escape it with open("input.txt", "r") as f: data = f.read() data = ast.literal_eval(data) # first evaluate the main structure data = data[:2] + (ast.literal_eval(data[2]), ) + data[3:] # .. and then the inner dict # this gives you `data` containing your 'serialized' tuple, i.e.: print(data[4]) # 31.328237,-85.811893 # and you can access the children of the inner dict as well, i.e.: print(data[2]["types"]) # ['restaurant', 'food', 'point_of_interest', 'establishment'] print(data[2]["opening_hours"]["weekday_text"][3]) # …
answers question: http://stackoverflow.com/q/51635184
has comment: http://stackoverflow.com/comment/90704890
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51635184
score: 0
has comment: http://stackoverflow.com/comment/90718408
type: Answer
has comment: http://stackoverflow.com/comment/90705174

http://stackoverflow.com/q/51625942
has title: Improve Performance processing Pandas dataframe (isin)
has body: My Python script is exiting with OOO memory errors when processing a large file. (Works fine for small subset of records ~10K) I'm processing 2 files: companies.csv (File size 19MB) ~43K records competitor_companies.csv (File size 427MB) ~4.5M records In file 1, I have a field called uuid. I need to compare: If company_name is the same in file1 and file2, copy uuid field from file 1 into competitor_companies dataframe. If website is the same in file1 and file2 , copy uuid field from file 1 into competitor_companies dataframe. When I process the files in my server (~30 GB RAM), script gets stuck in this line: logging.info('Matching TLD.') match_tld = competitor_companies.tld.isin(companies.tld) Then script stops and I see this line in /var/log/syslog: Out of memory: Kill process 177106 (company_generat) score 923 or sacrifice child Python code: def MatchCompanies( companies: pandas.Dataframe, competitor_companies: pandas.Dataframe) -&gt; Optional[Sequence[str]]: """Find Competitor companies in companies dataframe and generate a new list. Args: companies: A dataframe with company information from CSV file. competitor_companies: A dataframe with Competitor information from CSV file. Returns: A sequence of matched companies and their UUID. Raises: ValueError: No companies found. """ if _IsEmpty(companies): raise ValueError('No companies found') # Clean up empty fields. companies = companies.fillna('') logging.info('Found: %d records.', len(competitor_companies)) competitor_companies = competitor_companies.fillna('') # Create a column to define if we found a match or not. competitor_companies['match'] = False # Add Top Level Domain (tld) column to compare matching companies. companies.rename(columns={'website': 'tld'}, inplace=True) logging.info('Cleaning up company name.') companies.company_name = companies.company_name.apply(_NormalizeText) competitor_companies.company_name = competitor_companies.company_name.apply( _NormalizeText) # Create a new column since AppAnnie …
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/51635764
has comment: http://stackoverflow.com/comment/90217436
has comment: http://stackoverflow.com/comment/90217497
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: performance

http://stackoverflow.com/comment/90124333
has text: my ip address is whitelisted, the client-side firewall might be it i will check on it, thanks for you response.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51526142

http://stackoverflow.com/q/51596522
answer count: 6
score: 4
upvote count: 4
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/90158976
has answer: http://stackoverflow.com/a/51596674
has comment: http://stackoverflow.com/comment/90159134
favorite count: 0
has answer: http://stackoverflow.com/a/51596657
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1894269
has comment: http://stackoverflow.com/comment/90159008
has comment: http://stackoverflow.com/comment/90158960
tagged with: python
has answer: http://stackoverflow.com/a/51596695
tagged with: list
has answer: http://stackoverflow.com/a/51596552
has title: Converting a list into comma separated and add quotes in python
has body: I have : val = '[12 13 14 16 17 18]' I want to have: ['12','13','14','16','17','18'] I have done x = val.split(' ') y = (" , ").join(x) The result is '[12 , 13 , 14 , 16 , 17 , 18 ]' But not the exact one also the quotes What's the best way to do this in Python?
has comment: http://stackoverflow.com/comment/90159143
has answer: http://stackoverflow.com/a/51596720
type: Question
has answer: http://stackoverflow.com/a/51596609

http://stackoverflow.com/comment/89948550
comment on: http://stackoverflow.com/q/51489901
type: QuestionComment
type: Comment
has text: Note that your code is the (rather ugly) one-liner: `lambda lst: next((x for x in lst if x%4==0), 0) if len(lst) > 0 else -999`. That will even pass all your test cases. It is not, however, correct.
score: 0

http://stackoverflow.com/q/51578659
type: Question
has comment: http://stackoverflow.com/comment/90123164
downvote count: 0
has comment: http://stackoverflow.com/comment/90122876
favorite count: 0
has body: I want to draw SIFT feature matches across two different pictures but when the image resolution is too high then the lines become barely visible (of course this is usually desired, and it is the expected behavior, and one can always zoom, but...). Is there a way to change default line width (or pass is as a flag) or is the only way to implement a custom drawing function? Sample code for drawing: img1 = np.array(Image.open("im1.jpg")) img2 = np.array(Image.open("im2.jpg")) sift = cv2.xfeatures2d.SIFT_create() kp1, desc1 = sift.detectAndCompute(img1, None) kp2, desc2 = sift.detectAndCompute(img2, None) bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True) # Match descriptors. matches = bf.match(desc1,desc2) # Sort them in the order of their distance. matches = sorted(matches, key = lambda x: x.distance) out = np.concatenate([img1, img2], axis=1) # Draw first 10 matches. cv2.drawMatches(img1, kp1, img2, kp2, matches[:20], flags=2, outImg=out) plt.figure(figsize=(18,14)) plt.imshow(out) plt.show()
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Set line width for default drawing functions in Python/OpenCV
tagged with: opencv
has comment: http://stackoverflow.com/comment/90130646
answer count: 0
score: 1

http://stackoverflow.com/comment/90149703
has text: It won't make much of a difference, but I would say that in general `generators` are preferred over `lists`. Just to get used to them for when it does matter :)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51589891

http://stackoverflow.com/q/51544257
has answer: http://stackoverflow.com/a/51546493
tagged with: amazon-web-services
score: 0
tagged with: python
has body: and having some Problems. I am trying to parse thee path with dom.minidom. Example: from __future__ import print_function import sys import time import logging import rds_config import pymysql import os import io import zipfile import gzip import urllib import tempfile import botocore import traceback import datetime import boto3 import uuid import xml.dom.minidom from concurrent import futures from io import BytesIO from datetime import timedelta,datetime def readingXML(self,ruta): try: print('readingXML...') #self.s3 = boto3.client('s3') #ruta = xmls/(xmlname.xml) full_path = "s3://"+self.bucket+"/"+ruta print(full_path) doc = minidom.parse(full_path) #variables de xml - Comprobante And got this Error message: [Errno 2] No such file or directory: u's3://mi-bucket/xmls/A91C7BE1-015A-4A1A-9A85-3B065122E1EB.xml'
tagged with: http://stackoverflow.com/tag/xml
accepted answer: http://stackoverflow.com/a/51546493
has title: Python-lambda aws: [Errno 2] No such file or directory: How can i parse real path
type: AnsweredQuestion
tagged with: dom
type: Question
answer count: 1

http://stackoverflow.com/q/51575373
tagged with: flask
accepted answer: http://stackoverflow.com/a/51575397
tagged with: http://stackoverflow.com/tag/html
answer count: 1
score: -1
favorite count: 0
tagged with: python
tagged with: jinja2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51575397
downvote count: 1
type: Question
upvote count: 0
has body: I would like to display a python dataframe into html page using for loop. I do not want to use .to_html function because I want to customize table elements.Is there any way to do this? Here is my python code: @app.route('/table',methods=['GET','POST']) def table(): url = 'https://raw.github.com/pandas-dev/pandas/master/pandas/tests/data/tips.csv' df_Final = pd.read_csv(url) df_Final_header = list(df_Final) df_Final_header_length1 = len(df_Final_header) df_Final_header_length = list(range(0,df_Final_header_length1)) df_Final_Index_length1 =len(df_Final.index) df_Final_Index_length = list(range(0,df_Final_Index_length1)) return render_template('table1.html',data=df_Final,headers=df_Final_header,data_index_len=df_Final_Index_length,data_row_len=df_Final_header_length) #.to_html(classes="table table-striped table-bordered table-hover table-condensed")) if __name__ == '__main__': app.run(debug=True) Here is my templace: {% for header in headers %} {{ header }}&nbsp&nbsp {% endfor %} {% for i in data_index_len %} {% for j in headers %} {{ data.ix[i,j] }}&nbsp&nbsp {% endfor %} {% endfor} I am getting this random error while loading /table jinja2.exceptions.TemplateSyntaxError: unexpected '}'
has title: Rendering table in html from python Flask app using for loop
tagged with: javascript

http://stackoverflow.com/comment/90336776
type: Comment
has text: Yes @Scott Boston. I need something that looks like this https://stackoverflow.com/questions/31845258/pandas-multi-index-plotting/43999896#43999896 with seaborn
comment on: http://stackoverflow.com/q/51532581
score: 0
type: QuestionComment

http://stackoverflow.com/a/51585973
answers question: http://stackoverflow.com/q/51585130
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90141952
has body: The problem is that you are modifying attributes of the return values of recursiveTraversal. This function returns Path objects and you modify their attributes weight and vertices. So for the non-cached version each time you call the function with (x, y, z) arguments a fresh Path(0, []) object will be created and its attributes are modified later on in the for loop. But for each (x, y, z) call you are assured to start from a fresh object. Now for the cached version, instead of providing a fresh object by going all the way down the recursive tree, the cache wrapper just provides you with the instance of a previously created Path object (which already has modified weight and vertices attributes) and these are modified even further (i.e. this modifies the cache). This can be seen from the following example: # Augment `Path` class with `__repr__`. class Path: # Other methods go here. def __repr__(self): return '{}({}, {})'.format(self.__class__.__name__, repr(self.weight), repr(self.vertices)) data = [ {'ID': '2', 'Weight': 1, 'Edges': [1]}, {'ID': '1', 'Weight': 1, 'Edges': []} ] print(recursiveTraversal(0, '1', 1)) # Prints "Path(1, [1])". print(recursiveTraversal(1, '1', 0)) # Prints "Path(1, [1])". Checking the function recursiveTraversal is seems that for steps=0 it should return Path(0, []) in case the target matches. Nevertheless it returns Path(1, [1]). This happens because the previous call to recursiveTraversal already invoked recursiveTraversal(1, '1', 0) and modified the result's weight and vertices attributes. When performing the second explicit call to recursiveTraversal(1, '1', 0) you'll get back the cached reference to that object. Possible solution A possible solution is to create copies of cached objects before modifying them further. This prevents that the cache gets modified. from copy import deepcopy # Within `recursiveTraversal`: # ... nextPath = deepcopy(recursiveTraversal(i, target, steps - 1)) # ...
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/90137539
accepted answer of: http://stackoverflow.com/q/51585130

http://stackoverflow.com/q/51599980
score: -1
linked to: http://stackoverflow.com/q/2709821
has comment: http://stackoverflow.com/comment/90166253
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90166121
favorite count: 0
has comment: http://stackoverflow.com/comment/90166184
has comment: http://stackoverflow.com/comment/90166102
type: UnansweredQuestion
has body: I was using function based views and was getting output correctly. However when I changed it to class based views while invoking function I am getting error Method Not Allowed (POST): views file" class ChatBot(TemplateView): # extend from TemplateView template_name = 'bot/chatbot.html' //**Getting error in calling bot function** class MessagePassing(View): def bot(request): response_data={} response_data['input'] = request.POST['message'] return HttpResponse(json.dumps(response_data), content_type="application/json")
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90166047
has comment: http://stackoverflow.com/comment/90166046
upvote count: 0
has title: How to call custom method in class based views
type: Question
has comment: http://stackoverflow.com/comment/90166064
has answer: http://stackoverflow.com/a/51600085
has comment: http://stackoverflow.com/comment/90166030

http://stackoverflow.com/q/51559118
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51560757
tagged with: tensorflow
type: Question
downvote count: 0
tagged with: keras
tagged with: deep-learning
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51560757
has title: Tensorflow/Keras: Model accuracy during training is always 0.5 with input size different from first official tutorial
has body: I'm beginner with deep learning and keras/tensorflow. I have followed the first tutorial on tensorflow.org: a basic classification with fashion MNIST. In this case the input data are 60000, 28x28 images and the model is this: model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation=tf.nn.relu), keras.layers.Dense(10, activation=tf.nn.softmax) ]) Compiled with: model.compile(optimizer=tf.train.AdamOptimizer(), loss='sparse_categorical_crossentropy', metrics=['accuracy']) At the end of training the model has this accuracy: 10000/10000 [==============================] - 0s 21us/step Test accuracy: 0.8769 It's ok. Now I'm trying to duplicate this model with another set of datas. New input is a dataset downloaded from kaggle. The dataset has images with different sized of dogs and cats, so I have create a simple script that get the images, resize in 28x28 pixel and convert in a numpy array. This is the code to do this: import tensorflow as tf from tensorflow import keras from tensorflow.keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img from tensorflow.keras.models import load_model from PIL import Image import os # Helper libraries import numpy as np # base path dataset base_path = './dataset/' training_path = base_path + "training_set/" test_path = base_path + "test_set/" # size rate of images size = 28, 28 # train_images = [] train_labels = [] test_images = [] test_labels = [] classes = ['dogs', 'cats'] # Scorre sulle cartelle contenute nel path e trasforma le immagini in nparray def from_files_to_nparray(path): images = [] labels = [] for subfolder in os.listdir(path): if subfolder == '.DS_Store': continue for image_name in os.listdir(path + subfolder): if not image_name.endswith('.jpg'): continue img = Image.open(path + subfolder + "/" + image_name).convert("L").resize(size) # convert to grayscale and resize npimage = np.asarray(img) images.append(npimage) labels.append(classes.i…
upvote count: 1
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/comment/90128685
score: 1
comment on: http://stackoverflow.com/q/51580938
type: Comment
type: QuestionComment
has text: The code you've posted runs fine for me. Is it possible you defined a variable named `range` somewhere earlier in your code or in something that you didn't show us?

http://stackoverflow.com/a/51625871
has comment: http://stackoverflow.com/comment/91232652
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91445062
answers question: http://stackoverflow.com/q/51625265
downvote count: 0
has body: Answering my own question, since I resolved it. My bad, I just had to restart the airflow webserver and scheduler after placing the driver jars in spark/jar folder. It worked fine then.
type: Answer

http://stackoverflow.com/q/51510716
type: Question
has title: comparing 2 data field in mysql with python
has comment: http://stackoverflow.com/comment/89990788
has comment: http://stackoverflow.com/comment/89990486
answer count: 2
tagged with: mysql-python
downvote count: 0
has answer: http://stackoverflow.com/a/51513818
has comment: http://stackoverflow.com/comment/89990736
favorite count: 0
tagged with: python-3.x
has body: This is my database i want to comparing 2 date time datatype (datetime_comp &amp; date_time) simple comparison. etc : date1 > date 2 = "On_Time" but my problem is, i need to compare the data 1 by 1 (loop for sure) and this is my code from datetime import datetime import pymysql import time #Declare Connection conn = pymysql.connect(host='localhost', port='', user='root', passwd='', db='tes_coba', use_unicode=True, charset="utf8mb4") cur = conn.cursor() EW = "Tepat Waktu" LW = "Tidak Tepat Waktu" #get data from database cur.execute("SELECT datetime_comp FROM `tweet2`") row1 = cur.fetchall() cur.execute("SELECT date_time FROM `tweet2`") row2 = cur.fetchall() n = 1 for date1 in row1: print(date1) for date2 in row2: print(date2) if date1 &gt; date2: Result=EW elif date1 &lt; date2: Result=LW print(Result) cur.execute("UPDATE tweet2 SET on_time=%s WHERE no=%s AND relevance='Relevan'",(str(Result), str(n))) n = n + 1 conn.commit() cur.close() conn.close() and the result is, the comparison code only work with last data in database, because the comparison code does not looping for sure (confusing) but if i put the comparison code to one if the looping process, for date1 in row1: print(date1) for date2 in row2: print(date2) if date1 &gt; date2: Result=EW elif date1 &lt; date2: Result=LW only the last data compare with all data
has comment: http://stackoverflow.com/comment/89990756
accepted answer: http://stackoverflow.com/a/51513818
possible better answer: http://stackoverflow.com/a/51511595
has comment: http://stackoverflow.com/comment/89990639
tagged with: python
has answer: http://stackoverflow.com/a/51511595
has comment: http://stackoverflow.com/comment/89991607
type: AnsweredQuestion
score: 1
tagged with: mysql
upvote count: 1

http://stackoverflow.com/a/51590127
type: Answer
has comment: http://stackoverflow.com/comment/90161928
has body: In your front end, add an onclick attribute to your save button and call a function to arrange your data in a JSON so they would look like the following: { "employee": "xyz" , "weeks_schedule" :[ {"data_week": "value_1", "data_off_week": "value_2", "shift": "value_3"}, {"data_week": "value_4", "data_off_week": "value_5", "shift": "value_6"}, . . . ] } Of course at the end of the function after arranging the data inside this JSON, post it to the correct URL. In your view you should handle this JSON differently by adding a well written post method: class ShiftCreateView(CreateView): def post(self, request, *args, **kwargs): json_data = json.loads(request.body.decode('utf-8')) employee = json_data["employee"] for week in json_data["weeks_schedule"]: # Code for saving in the database here return _(some_http_response) If you would like to do the process without a json just submit your form and instead of the line: json_data = json.loads(request.body.decode('utf-8')) write form = request.POST remember to clean, validate and save the data in the form manually the same as in json, so if you run print(request.POST) you will notice that your data will look like: &lt;QueryDict: {'employee': 'xyz', 'off_week': 'xyz_2' ......}&gt; Of course your QueryDict will look different but if you know how will it look you should be able to deal with it.
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51589757
downvote count: 0

http://stackoverflow.com/a/51491865
score: 1
has body: You could use values_list() + flat=True to generate a list instead. &gt;&gt;&gt; p_name = OrderLine.objects.filter(order_id=order).values_list('product_name',flat=True) &gt;&gt;&gt; print(p_name) &gt;&gt;&gt; &lt;QuerySet ['doc 1 (1-1000)']&gt; This is meant to generate a list of values from the field passed in value_list(). In case you are sure that this will have only one value and it's the one wanted, you may index the item in the list: &gt;&gt;&gt; p_name[0] &gt;&gt;&gt; 'doc 1 (1-1000)'
accepted answer of: http://stackoverflow.com/q/51491745
answers question: http://stackoverflow.com/q/51491745
type: AcceptedAnswer
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/q/51622702
linked to: http://stackoverflow.com/q/4438020
accepted answer: http://stackoverflow.com/a/51622853
tagged with: windows
has title: Windows 10 run python program in startup
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/51622853
downvote count: 0
has comment: http://stackoverflow.com/comment/130896578
type: Question
tagged with: startup
type: AnsweredQuestion
score: 4
answer count: 1
tagged with: apscheduler
has body: I have written a python program that periodically runs with ApScheduler package. The .pyw file runs in the background, but when I restart the PC the program doesn't continue running. What can I do to run a code automatically in startup a windows 10 pc?
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/90015054
type: Comment
has text: That doesn't highlight anything for me. [Screenshot of my code](https://i.sstatic.net/yeOyr.jpg) (sorry it's a screenshot, but I don't know a better way to show the code)
type: AnswerComment
comment on: http://stackoverflow.com/a/51522497
score: 0

timeit
tag name: timeit
type: Tag
tags question: http://stackoverflow.com/q/51503672

http://stackoverflow.com/comment/90133054
comment on: http://stackoverflow.com/a/51560079
score: 0
type: Comment
has text: If not at all, you can do `fig = plt.figure(figsize=(X,Y)); plot_importance(model, ax=fig.axes)` pyplot.show()`
type: AnswerComment

http://stackoverflow.com/a/51560324
type: Answer
upvote count: 1
score: 1
has body: @murali selenium is correct, you need to extract the text from elements before you write to file. You'll need to do something like this in your try block: try: elm = browser.find_element_by_link_text("next") browser.execute_script("return arguments[0].scrollIntoView();", elm) elm.click() labels = browser.find_elements_by_xpath('.//a[@class="question-hyperlink"]') text = [x.text for x in labels] data.append(text) with open('output.csv', 'w') as data_file: writer = csv.writer(data_file) writer.writerows(data) except NoSuchElementException: print(traceback.format_exc()) break You're using writerows so you don't need for label in labels:, especially since you're not even using label in the loop.
accepted answer of: http://stackoverflow.com/q/51553874
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51553874

http://stackoverflow.com/a/51597772
answers question: http://stackoverflow.com/q/51597181
has body: Your best solution would be ti use the same function for both routes, by making project_id an optional parameter for the home route. This question has more details, as well as links to examples in the Flask documentation to do so. Having the project as an optional parameter would let you display all tasks in the home view when it is not present, and limit them to a given project when it is.
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/51597181
type: Answer

http://stackoverflow.com/comment/90210581
comment on: http://stackoverflow.com/a/51621738
type: AnswerComment
has text: Thanks i tried this, but line in my case is an email address read line by line from a text file. Should i put double or single quotes around the respective emails in the text file for this to work?
type: Comment
score: 0

http://stackoverflow.com/comment/101124517
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51585177
has text: If `l= [1,0]` then how can you index your numpy array with `l`? For example `np.array(m) l` does not work.
score: 0

http://stackoverflow.com/comment/90243234
score: 0
type: Comment
type: QuestionComment
has text: I've used `send_keys` before to select an option in a drop down.
comment on: http://stackoverflow.com/q/51639372

token
tags question: http://stackoverflow.com/q/51505449
tags question: http://stackoverflow.com/q/51602617
type: Tag
tag name: token

http://stackoverflow.com/comment/90015350
has text: @BenjaminPharris try iterating through once and see how it goes
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51505912

http://stackoverflow.com/comment/90062564
comment on: http://stackoverflow.com/a/51542518
score: 0
type: Comment
has text: And if I added icons in href, then in which folder do I put them? Now they are located in templates/ folder
type: AnswerComment

http://stackoverflow.com/q/51623949
has comment: http://stackoverflow.com/comment/90213130
has comment: http://stackoverflow.com/comment/90213152
has comment: http://stackoverflow.com/comment/90213250
has comment: http://stackoverflow.com/comment/90213208
upvote count: 1
possible better answer: http://stackoverflow.com/a/51624114
downvote count: 1
type: Question
tagged with: sublimetext
has title: "if" condition for boolean settings: == 1, == True or just omit?
has comment: http://stackoverflow.com/comment/90213080
has answer: http://stackoverflow.com/a/51624091
has comment: http://stackoverflow.com/comment/90213072
score: 0
has comment: http://stackoverflow.com/comment/90213160
answer count: 3
has answer: http://stackoverflow.com/a/51623991
favorite count: 0
accepted answer: http://stackoverflow.com/a/51624091
tagged with: sublime-text-plugin
has body: Here is simple ST plugin. Is there a difference between commented lines? Personally, I don't see any difference in how they work, just a difference in visual appearance. However, some plugin developers prefer second version (== 1), which looks just useless and ugly for me. Probably there are some reasons to prefer it? import sublime_plugin class ExpandUnexpandTabsCommand(sublime_plugin.EventListener): def on_pre_save(self, view): # if view.settings().get("translate_tabs_to_spaces"): # if view.settings().get("translate_tabs_to_spaces") == 1: # if view.settings().get("translate_tabs_to_spaces") == True: view.run_command("expand_tabs") else: view.run_command("unexpand_tabs")
tagged with: python
has answer: http://stackoverflow.com/a/51624114
type: AnsweredQuestion

http://stackoverflow.com/comment/90111553
type: QuestionComment
comment on: http://stackoverflow.com/q/51570684
has text: @KlausD. Whoops. I see it now. I think I fixed it.
score: 0
type: Comment

http://stackoverflow.com/q/51486456
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51486672
upvote count: 2
tagged with: python
downvote count: 1
type: AnsweredQuestion
has body: I have a program in python, and when I make an alert with win32api.py, the running program pauses, how do I make it continue working even if the alert is up? This is the code example: time.sleep(3) win32api.MessageBox(0,'hello','text') time.sleep(3) os.system("TASKKILL /F /IM program.exe") Now when it comes to the win32api.Mes... part it pauses the program until I click "OK", how to prevent it from pausing? Thank you!
score: 1
tagged with: winapi
accepted answer: http://stackoverflow.com/a/51486672
type: Question
has comment: http://stackoverflow.com/comment/89942011
has title: How to make alert with python without pausing the running program?
answer count: 1

http://stackoverflow.com/comment/90240098
score: 0
type: Comment
has text: Have you tried by CSS selector ?
type: QuestionComment
comment on: http://stackoverflow.com/q/51637794

http://stackoverflow.com/comment/90232730
score: 0
type: Comment
type: QuestionComment
has text: Empty set. But I have created the database and table in phpmyadmin. What's the problem?
comment on: http://stackoverflow.com/q/51620173

http://stackoverflow.com/q/51625105
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51625167
type: Question
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
has body: I'm currently merging the first and last string in a row. These strings are merged when they are to the right of a specific value. I'm hoping to change that to below a specific value. import pandas as pd d = ({ 'A' : ['X','Foo','','X','Big'], 'B' : ['No','','','No',''], 'C' : ['Merge','Bar','','Merge','Cat'], }) df = pd.DataFrame(data = d) m = df.A == 'X' def f(x): s = x[x!= ''] x[s.index[1]] = x[s.index[1]] + ' ' + x[s.index[-1]] x[s.index[-1]] = '' return x df = df.astype(str).mask(m, df[m].apply(f, axis=1)) This code merges the first and last string when followed by X. Output: A B C 0 X No Merge 1 Foo Bar 2 3 X No Merge 4 Big Cat I'm hoping to change it to rows beneath the value X. Intended Output: A B C 0 X No Merge 1 Foo Bar 2 3 X No Merge 4 Big Cat
accepted answer: http://stackoverflow.com/a/51625167
has title: Merge specific values in a pandas df
tagged with: python
tagged with: merge

http://stackoverflow.com/comment/89991417
has text: @jezrael and @ Ashish Acharya , thanks for both responses, also thanks for advising me to do not use list..@jezrael in a hypothetical scenario if I add a date variable would I be able to do combinations with 3 constraints?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51511239
score: 0

http://stackoverflow.com/a/51758008
has body: The problem was permissions problem. While the file ca.pem had the appropriate permissions, it's directory (app/) did not have read access. Hence, the file could not be read.
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51606054
upvote count: 3
answers question: http://stackoverflow.com/q/51606054
score: 3

class
tags question: http://stackoverflow.com/q/51583944
tags question: http://stackoverflow.com/q/51540966
tags question: http://stackoverflow.com/q/51569298
tags question: http://stackoverflow.com/q/51569397
tags question: http://stackoverflow.com/q/51546039
tags question: http://stackoverflow.com/q/51567356
tags question: http://stackoverflow.com/q/51483516
tags question: http://stackoverflow.com/q/51631942
tags question: http://stackoverflow.com/q/51502156
tags question: http://stackoverflow.com/q/51570985
tags question: http://stackoverflow.com/q/51550426
tags question: http://stackoverflow.com/q/51573299
tags question: http://stackoverflow.com/q/51524049
tags question: http://stackoverflow.com/q/51502479
tags question: http://stackoverflow.com/q/51615073
tags question: http://stackoverflow.com/q/51621237
tags question: http://stackoverflow.com/q/51571311
tags question: http://stackoverflow.com/q/51518424
tags question: http://stackoverflow.com/q/51598745
tags question: http://stackoverflow.com/q/51556737
tags question: http://stackoverflow.com/q/51564071
tags question: http://stackoverflow.com/q/51530216
tags question: http://stackoverflow.com/q/51599979
type: Tag
tags question: http://stackoverflow.com/q/51576862
tags question: http://stackoverflow.com/q/51510135
tags question: http://stackoverflow.com/q/51540486
tags question: http://stackoverflow.com/q/51576590
tags question: http://stackoverflow.com/q/51551588
tags question: http://stackoverflow.com/q/51619937
tag name: class
tags question: http://stackoverflow.com/q/51572195
tags question: http://stackoverflow.com/q/51509531
tags question: http://stackoverflow.com/q/51505666
tags question: http://stackoverflow.com/q/51625775
tags question: http://stackoverflow.com/q/51577957
tags question: http://stackoverflow.com/q/51491119
tags question: http://stackoverflow.com/q/51560569
tags question: http://stackoverflow.com/q/51546543
tags question: http://stackoverflow.com/q/51546989
tags question: http://stackoverflow.com/q/51541043
tags question: http://stackoverflow.com/q/51504268

http://stackoverflow.com/a/51619368
has comment: http://stackoverflow.com/comment/90204619
has comment: http://stackoverflow.com/comment/90204516
upvote count: 3
has comment: http://stackoverflow.com/comment/90204319
has comment: http://stackoverflow.com/comment/90204434
type: Answer
has comment: http://stackoverflow.com/comment/90204487
has comment: http://stackoverflow.com/comment/90204425
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51618819
has comment: http://stackoverflow.com/comment/90204441
has body: In simple way... you are using get() method that will check if the element that you want exists if not return None (null), so you are searching for GET (HTTP) Paramter if "page" exists, if not exists it return 1 mypage.com/?page=2 request.GET['page'] # That will force get page param, and you will if not found request.GET.get('page', '1') # Tha will check if param exists, and return 1 if not found Using GET.get() is a bad pratice, since your erros will silent fail, better your GET['page'] and handle the errors using try/except try: page = request.GET['page'] ... except Exception as e: print(e) # handle your errors page = 1 # The Default value when erros comes ...
has comment: http://stackoverflow.com/comment/90204355

http://stackoverflow.com/q/51540800
answer count: 2
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/90050104
favorite count: 0
has body: The favicon is currently not being displayed on pages served by my Flask app. I have the following two routes, how do I ensure the favicon is displayed? @app.route('/') def hello(): return redirect("tg://resolve?domain=sneakersale", code=302) @app.route('/favicon.ico') def fav(): return send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico')
has title: Favicon not seen in Flask app
accepted answer: http://stackoverflow.com/a/51542518
tagged with: python
tagged with: favicon
has comment: http://stackoverflow.com/comment/90049678
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51542518
score: 6
type: Question
has answer: http://stackoverflow.com/a/58700344
tagged with: flask
possible better answer: http://stackoverflow.com/a/58700344

http://stackoverflow.com/q/51565311
tagged with: vader
tagged with: python
has title: positive phrase has negative score in vader function polarity_scores
score: 0
type: Question
has comment: http://stackoverflow.com/comment/90098211
has comment: http://stackoverflow.com/comment/90097525
has body: In python's nltk.sentiment.vader, there is a function called polarity_scores, you can try to use the string no problem to see the result, which is -0.6. How could I improve vader's performance. If not, is there any other package that does a better job?
answer count: 1
has answer: http://stackoverflow.com/a/62727261
type: UnansweredQuestion

http://stackoverflow.com/a/51639533
type: Answer
has comment: http://stackoverflow.com/comment/91556119
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90276870
has body: This is caused by the syntax error at if event.type = pygame.KEYUP:. Opening the file will cause it to close instantly, but running it in the interpreter (IDLE) will show you that error. Just change it to if event.type == pygame.KEYUP: and everything will work fine. UPDATE: Running code from the file rather than the interpreter (IDLE) won't always open. It is best to run it in IDLE. Code: import pygame pygame.init() display_width = 1280 display_height = 720 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption("Racing Game") clock = pygame.time.Clock() black = (0,0,0) white = (255,255,255) carImg = pygame.image.load("racecar.png") def car(x,y): gameDisplay.blit(carImg, (x,y)) x = display_width * 0.45 y = display_height * 0.8 x_change = 0 car_speed = 0 crashed = True while crashed: for event in pygame.event.get(): if event.type == pygame.QUIT: crashed = False ############################# if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 elif event.key == pygame.K_RIGHT: x_change = 5 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 ############################# print(event) x += x_change gameDisplay.fill((255,255,255)) car(x,y) pygame.display.update() clock.tick(60) pygame.display.quit() pygame.quit() quit()
answers question: http://stackoverflow.com/q/51639365
downvote count: 0

http://stackoverflow.com/comment/90018805
type: AnswerComment
has text: I do have the latest pycharm version
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51495186

http://stackoverflow.com/q/51602799
accepted answer: http://stackoverflow.com/a/51603240
has comment: http://stackoverflow.com/comment/90172252
has comment: http://stackoverflow.com/comment/90172285
tagged with: python
has comment: http://stackoverflow.com/comment/90172067
has answer: http://stackoverflow.com/a/51603240
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51602961
has comment: http://stackoverflow.com/comment/90172375
type: Question
tagged with: indexing
has comment: http://stackoverflow.com/comment/90172115
has title: How to use 2 different conditions to filter an array in python
has comment: http://stackoverflow.com/comment/90172442
has body: I am trying to create a new array, which will consist of (data value &lt;=20000) from the first column, along with all other corresponding columns. Mathematically I am doing the following: I am reading data from a text file. I am finding distance to all the points from the last point. Then I will take only those rows with distances less than 20000 and M1 less than 11.5. The data looks as follows: # ID M1 M2 M3 M4 R4 M5 R5 x y z 10217 11.467 11.502 13.428 13.599 432.17 13.266 281.06 34972.8 42985.9 14906 7991 11.529 11.559 13.438 13.520 435.23 13.224 272.23 8538.05 33219.8 43375.1 2100 11.526 11.573 13.478 13.490 448.97 13.356 301.27 9371.75 13734.1 43398.6 9467 11.557 11.621 13.481 13.537 449.99 13.367 303.67 33200.3 36008.9 12735.8 my code looks the following: import numpy as np import matplotlib.pyplot as plt halo = 'nntest.txt' ID, m,r,x,y,z= np.loadtxt(halo, usecols=(0,6,7,8,9,10), unpack =True) # selet the last point m_mass = m[-1:] ID_2 = ID[-1:] r_2 = r[-1:] x_2 = x[-1:] y_2 = y[-1:] z_2 = z[-1:] ####################################### #Find distance to all points from our targeted point nearest_neighbors = [] def neighbors(ID_2, cx,cy,cz, ID, m, r, x, y, z): dist = np.sqrt((cx-x)**2 + (cy-y)**2 + (cz-z)**2) return dist, ID, m, r, x, y, z for i in range(len(ID_2)): hist = neighbors(ID_2[i], m_2[i], r_2[i], x_2[i], y_2[i], z_2[i], ID, m , r, x, y, z) #print all the IDs and all other data which are less than 20000 and M less than 11.5 of that targeted value print ID[hist[0]&lt;20000] and m[hist[1]&lt;11.5] But I am having problem with setting the 2 conditions. It returns me this error: File "overlaping_halos_finder.py", line 53, in &lt;module&gt; combined = zip(ID[hist[0]&lt;r_2[i] and m[hist[1]&gt;1.e12]]) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() if instead of print ID[hist[0]&lt;20000] and m[hist[1]&lt;11.5] I do only: print ID[hist[0]&lt;20000] I have following sample output: # ID M R X Y Z 6737.…
has comment: http://stackoverflow.com/comment/90172223
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/90172275
answer count: 2
possible better answer: http://stackoverflow.com/a/51602961
tagged with: arrays
has comment: http://stackoverflow.com/comment/90172251

http://stackoverflow.com/q/51572872
downvote count: 0
has comment: http://stackoverflow.com/comment/90111995
tagged with: selenium
type: AnsweredQuestion
tagged with: automation
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51572934
has comment: http://stackoverflow.com/comment/90111907
accepted answer: http://stackoverflow.com/a/51572934
has body: What I am trying to do: Quite simply, use Selenium to select a specific day in a calendar, via the attribute of the day element. The structure of the web page: The days of a month exist in a calendar table, which should also be fairly standard. Snapshot of the calendar table: dayTable Snapshot of the HTML source code:dayTableHTML What has worked: I have no problem locating/selecting a certain day element via direct path, either via XPath or CSS selector. For example, if I want to select day "6", I will just use the following code. Both work fine. driver.find_element_by_xpath('//table/tbody/tr[2]/td[4]') driver.find_element_by_css_selector('table &gt; tbody &gt; tr:nth-child(2) &gt; td:nth-child(4)') What is not working: I'd like to select a day just by its identifiers. As you can see in the source code picture embedded above, there is no class or id names that's unique for each day. The attribute of "data-title" seems to be the perfect solution, since its value is the position of the day within the calendar table. Day "6", for example, has a data-title of "r1c3". So I try to select the element again via the attribute value. And this is where I have been stuck. I have been given SyntaxError of invalid syntax. The code is as followed: driver.find_element_by_css_selector('table &gt; tbody td[data-title='r1c3']') The pointing arrow points to the 3 within 'r1c3', but I really don't know what's wrong with this line of code. Is it because the attribute of 'data-title' has a hyphen in its name, and that is difficult for Python/Selenium to handle? Then how do I properly escape the hyphen? It's confusing as many related articles use attributes with hyphenated names, and there didn't seem to be any issue or escaping involved. Is it because there are multiple tr nodes under the table node, and multiple td nodes under a tr node, and my code does not lead me to the specific td I want? But isn't that what the attribute specification there is for? Please help solve the mystery. I w…
tagged with: css-selectors
answer count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Python Selenium - Can't locate element by attribute of data-title
score: 2

http://stackoverflow.com/a/51566574
has body: Solution Please refer to the example for details. DropDown is a special widget just like Popup. Don't try to add it as a child to any other widget. If you do, DropDown will be handled like an ordinary widget and dropdown list will be opened i.e. won't be closed in the background. In kv file, create a dynamic class &lt;CustomDropDown@DropDown&gt;: and add widgets to it. Buttons in the ScrollView are bigger than the ScrollView because size_hint_y: None was not specified. Set the height to minimum height such that there is something to scroll. ScrollView » Managing the Content Size and Position layout = GridLayout(cols=1, spacing=10, size_hint_y=None) # Make sure the height is such that there is something to scroll. layout.bind(minimum_height=layout.setter('height')) for i in range(100): btn = Button(text=str(i), size_hint_y=None, height=40) layout.add_widget(btn) root = ScrollView(size_hint=(1, None), size=(Window.width, Window.height)) ScrollView » bar_width bar_width Width of the horizontal / vertical scroll bar. The width is interpreted as a height for the horizontal bar. bar_width is a NumericProperty and defaults to 2. Example main.py from kivy.app import App from kivy.core.window import Window from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.uix.scrollview import ScrollView from kivy.properties import ListProperty, NumericProperty, ObjectProperty class ScrollButton(Button): pass class DropperScrollView(ScrollView): layout = ObjectProperty(None) class MainWindow(FloatLayout): mainbutton = ObjectProperty(None) scroll_list = ObjectProperty(None) def btn_1(self): if not self.scroll_list.layout.children: # empty list btn_1 = ScrollButton(text='Button 1') btn_2 = ScrollButton(text='Button 2') self.scroll_list.layout.add_widget(btn_1) self.scroll_list.layout.add_widget(btn_2) class BioWikiaApp(App): ratio = 1/7 window_width = 360 window_height = 640 squared_ratio = NumericProperty(ratio) squared_dropper_size_hint = ListProperty(…
answers question: http://stackoverflow.com/q/51552017
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51552017
score: 0
type: Answer

http://stackoverflow.com/q/51622364
upvote count: 1
downvote count: 1
answer count: 1
tagged with: tensorflow
has body: ValueError: Layer concatenate_1 was called with an input that isn't a symbolic tensor. Received type: . Full input: [9]. All inputs to the layer should be tensors. Problem on line paired_encoders_merger = concatenate(paired_encoder_size) def __init__(self, input_size=18, paired_encoder_size=9, common_encoder_size=126, size_class=10): inputs = [] [inputs.append(Input(shape=(input_size,1), name=('input_'+str(i)))) for i in range(7)] paired_encoders = [] for i in range(7): paired_encoders.append(Dense(paired_encoder_size, activation='relu')(inputs[i])) paired_encoders_merger = concatenate(paired_encoder_size) common_encoder = Dense(common_encoder_size, activation='relu')(paired_encoders_merger) classes = Dense(size_class, activation='relu')(common_encoder) common_decoded = Dense(common_encoder_size, activation='relu')(classes) paired_decoded = [] for i in range(7): paired_decoded.append(Dense(paired_encoder_size, activation='relu')(common_decoded)) out_pair = [] for i in range(7): out_pair.append(Dense(input_size, activation='relu', name=('out_'+str(i)))(paired_decoded[i])) out_merger = concatenate(out_pair) self.model = Model(inputs=inputs, outputs=out_merger) self.model.compile(optimizer='ADAM', loss='binary_crossentropy')
has title: All inputs to the layer should be tensors
has answer: http://stackoverflow.com/a/51622684
type: AnsweredQuestion
tagged with: keras
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/51622684
score: 0

http://stackoverflow.com/q/51531007
accepted answer: http://stackoverflow.com/a/51550949
favorite count: 0
has title: Is "input" a keyword that causes errors when used as a parameter name (in PyTorch)?
tagged with: python
has body: So I have a line of code: packed_embeddings = pack_padded_sequence(input=embeddings, lengths=lengths, batch_first=True) That throws me this error: File "/Users/kwj/anaconda3/lib/python3.6/site-packages/torch/onnx/__init__.py", line 130, in might_trace first_arg = args[0] IndexError: tuple index out of range But magically fixes itself if I take out the "input": packed_embeddings = pack_padded_sequence(embeddings, lengths=lengths, batch_first=True) Here is the function specification in the PyTorch docs: https://pytorch.org/docs/stable/_modules/torch/nn/utils/rnn.html#pack_padded_sequence I'm using Python3 and PyTorch 0.4. Am I missing something really basic? Not sure if this is my issue, or a PyTorch specific issue...pretty confused here. Thanks
tagged with: pytorch
upvote count: 7
type: Question
type: AnsweredQuestion
score: 7
has answer: http://stackoverflow.com/a/51550949
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51564733
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has body: the program I'm making sends emails to our customers and the API I'm working with allows me to write in HTML and insert variables, I'm trying to make one of those variables an image. Basically what I'm doing is opening an image in python, encoding it to base 64 and then concatenating it to a variable with the HTML IMG tag. When I execute my code I get TypeError: Object of type 'bytes' is not JSON serializable I'm using Python 3.6 This is my code: with open("TA203_2.jpg", "rb") as imageFile: equipment_image = base64.b64encode(imageFile.read()) logger.debug(str(equipment_image)) Is there any way to work around this?
tagged with: base64
type: Question
has title: how to encode image to base64 in python and insert to HTML?
tagged with: encoding
answer count: 1
has answer: http://stackoverflow.com/a/51564750
score: 0

http://stackoverflow.com/a/51575445
answers question: http://stackoverflow.com/q/51575362
upvote count: 1
score: 1
downvote count: 0
has body: Here you go. I lumped both answers in one example: # create figure and ax objects, it is a good practice to always start with this fig, ax = plt.subplots() # then plot histogram using axis # note that you can change orientation using keyword ax.hist(np.random.rand(100), bins=10, orientation="horizontal") # get_xticklabels() actually gets you an iterable, so you need to rotate each label for tick in ax.get_xticklabels(): tick.set_rotation(45) It produces the graph with rotated x-ticks and horizontal histogram.
type: Answer

http://stackoverflow.com/a/51632208
downvote count: 0
answers question: http://stackoverflow.com/q/51631866
has comment: http://stackoverflow.com/comment/90228846
has comment: http://stackoverflow.com/comment/90229278
has comment: http://stackoverflow.com/comment/90228724
type: Answer
has comment: http://stackoverflow.com/comment/90228996
score: 2
has comment: http://stackoverflow.com/comment/90228954
has comment: http://stackoverflow.com/comment/90228781
has body: from html.parser import HTMLParser str = "I am happy with This is a Heading This is a paragraph. 3333 > This is a Heading This is a paragraph. your code" class MyHTMLParser(HTMLParser): got_html_in_tags = False html_free_text = [] def handle_starttag(self, tag, attrs): self.got_html_in_tags = True def handle_endtag(self, tag): self.got_html_in_tags = False def handle_data(self, data): if not self.got_html_in_tags: self.html_free_text.append(data) parser = MyHTMLParser() parser.feed(str) print("".join(parser.html_free_text)) This will print I am happy with 3333 your code even with '>' or '<' in text
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51631866
type: AcceptedAnswer

http://stackoverflow.com/comment/90121582
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51578040
has text: This is a very elegant solution ARMAN! Thank you. But I think abarnerts' is more optimal
score: 1

http://stackoverflow.com/comment/124058687
has text: that answer didn't work for me, no idea why.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51553545
score: 0

http://stackoverflow.com/comment/90125761
comment on: http://stackoverflow.com/a/51556659
has text: Thank you very much for your reply. I can confirm `tf.contrib.data.group_by_window` works on cifar10 dataset so far... I'll do more test to see if it is efficient on ImageNet.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90033816
has text: Please note that every time you remove a row you will move all the cells in rows below it which will affect any counting you have.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51510669
score: 0

http://stackoverflow.com/comment/89951027
type: Comment
comment on: http://stackoverflow.com/a/51491257
score: 0
type: AnswerComment
has text: thanks but i'll be go with window._sharedData.entry_data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media

http://stackoverflow.com/comment/90187621
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51610959
has text: `np.nan` probably satisfies the `float` test.
score: 0

http://stackoverflow.com/comment/90001131
type: Comment
comment on: http://stackoverflow.com/a/51514534
has text: And what if i want to know in how many 2*2 matrix the index (1,1) is included. For that answer will be 1 because (1,1) is included in only one 2*2 grid
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90539572
has text: Thank you! That makes a lot of sense now.
type: Comment
comment on: http://stackoverflow.com/a/51769373
score: 0
type: AnswerComment

http://stackoverflow.com/comment/106427098
score: 1
comment on: http://stackoverflow.com/a/51581295
type: AnswerComment
type: Comment
has text: can you please provide us a code sample for working on the underlying XML of the visio files?

http://stackoverflow.com/q/51592114
upvote count: 1
tagged with: web-scraping
tagged with: scrapy
accepted answer: http://stackoverflow.com/a/51595122
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51592261
score: 1
type: Question
possible better answer: http://stackoverflow.com/a/51592261
answer count: 2
has comment: http://stackoverflow.com/comment/90149608
downvote count: 0
has title: How to get XPath value from nested div
has answer: http://stackoverflow.com/a/51595122
has comment: http://stackoverflow.com/comment/90150343
tagged with: python
favorite count: 0
tagged with: xpath
has body: How can I get the value 5000+ by providing key "Installs" to xpath. Installs 5,000+ I tried this response.xpath('//span/div/span/text()').extract() but it's giving all text. Can anyone help me with it?

http://stackoverflow.com/q/51531543
favorite count: 0
has title: DRF ForeignKey value not showing partially
upvote count: 1
has answer: http://stackoverflow.com/a/51531618
type: AnsweredQuestion
has body: I am newbie in python django, just couple weeks. And this is my first question post. I found problems using DRF ForeignKey. The foreign key value (name) do not showing up. I have 3 tables which are related each other (Brand, Country, BrandCountry). After followed some tutorials, in BrandCountry Entity, I succeed print out the name of brand (instead of ID), but it is not working with the same code structure for country relation. country name not showing I wonder what is the problem causing this. There is no error or warning message. I tried to debug, the query run correctly (it selects brand.name and country.name correctly). correct query from debug I wonder is it because of : - I use 'code' for relation key instead of 'ID'? the name of the Country contains Kanji(special character)? or is there something i miss? Models.py class BrandCountry(models.Model): class Meta: db_table = 'brand_countries' brand = models.ForeignKey(to='brand.Brand', on_delete=models.CASCADE, related_name='ref_brand_country_brand') country_code = models.ForeignKey(to='country.Country', on_delete=models.CASCADE, related_name='ref_brand_country_country', max_length=45, db_column='country_code', to_field='code') Serializers.py class BrandCountrySerializer(serializers.ModelSerializer): brand_name = serializers.StringRelatedField(source='brand.name') country_name = serializers.StringRelatedField(source='country.name') class Meta: model = BrandCountry fields = ('id', 'brand_id', 'brand_name', 'country_code', 'country_name') @staticmethod def setup_eager_loading(queryset): queryset = queryset.select_related('brand','country_code') return queryset Views.py class BrandCountryListView(generics.ListAPIView): serializer_class = BrandCountrySerializer brand_id = "brand_id" def get_queryset(self): serializer_class = BrandCountrySerializer.setup_eager_loading(BrandCountry.objects) queryset = serializer_class.all() brand_id = self.kwargs.get(self.brand_id) queryset = queryset.filter(brand_id=brand_id) return qu…
type: Question
answer count: 1
downvote count: 0
score: 1
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/51531618
tagged with: python-3.6
tagged with: python

http://stackoverflow.com/q/51618132
answer count: 1
favorite count: 0
has body: I am trying to install django in windows 10. I have already installed Python 3.7 and running this command to install django. pip install django As only Python 3 is installed on my PC, so I didn't have to use pip3. Error: Proxy Error() Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refuses it. From the error, I can see it is some kind of proxy error and ask me to change or provide a proxy. But I am not using any proxy and my Firewall is all set (it is not blocking it). Tried for solution I have already searched it a lot and most of them recommended me to provide --proxy with pip but I can't, as I am not using any proxy.
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51618250
accepted answer: http://stackoverflow.com/a/51618250
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 2
has title: Proxy error while django installation on python 3.7 in windows
tagged with: windows

http://stackoverflow.com/q/51588514
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51591689
tagged with: pyqt5
type: Question
tagged with: matplotlib-widget
tagged with: matplotlib
has title: How to draw share xaxis subplot with multiple yaxis with Figure(matplotlib FigureCanvasQTAgg)?
upvote count: 2
answer count: 1
linked to: http://stackoverflow.com/q/13128647
favorite count: 0
has body: I want to draw a graph that's share xaxis but different yaxis in vertical layer as image below. I have tried this import sys import matplotlib matplotlib.use("Qt5Agg") from PyQt5 import QtCore from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import num2date, date2num import datetime class GraphCanvas(FigureCanvas): def __init__(self, parent=None, width=1, height=1, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi,facecolor='#041105') #figure options #first subplot self.axes = fig.add_subplot(211,facecolor='#041105') self.axes.tick_params(axis='both',color='#ffffff',labelcolor ='#ffffff') #tick options self.axes.grid(color='lightgray', linewidth=.5, linestyle=':') self.axes.yaxis.tick_right() # show yaxis tick text in right side self.axes.xaxis_date() #second subplot self.axes2 = fig.add_subplot(212,facecolor='#041105') self.axes2.tick_params(axis='both', color='#ffffff', labelcolor='#ffffff') # tick options self.axes2.grid(color='lightgray', linewidth=.5, linestyle=':') self.axes2.yaxis.tick_right() # show yaxis tick text in right side self.axes2.xaxis_date() # ploting all trace self.plot_traces() FigureCanvas.__init__(self, fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) class GraphTraces(GraphCanvas): """Simple canvas with a sine plot.""" def plot_traces(self): dates = ['2017/01/01', '2017/01/02', '2017/01/03', '2017/01/04', '2017/01/05','2017/01/06','2017/01/07'] x = date2num([datetime.datetime.strptime(d, '%Y/%m/%d').date() for d in dates]) #scatter line chart y1 = [2,5,4,7,6,5,4] self.axes.plot(x, y1,color='orange') #bar chart y2 = [2,5,4,7,6,5,4] self.axes2.bar(x, y2,width=.8,color='g') class ApplicationWindow(QMainWindow): def __init__(self): QMainWindow.__init__(s…
accepted answer: http://stackoverflow.com/a/51591689
tagged with: python

http://stackoverflow.com/q/51565847
downvote count: 0
has answer: http://stackoverflow.com/a/51565975
tagged with: ipython
type: Question
tagged with: pdb
has body: I have a file called foo.py. In that file I have a bunch of functions and I would like to debug one of them, called foo.bar by setting a breakpoint but not hardcoding it using set_trace. I am working in an IPython console and I know there is a %debug magic function that can be used for this purpose with the syntax: %debug [--breakpoint FILE:LINE] So I try %debug --breakpoint foo.py:10 to set the breakpoint at line 10. However, how do I actually execute the code then so that IPython recognizes the breakpoint? Doing import foo foo.bar() does not work as the breakpoint is simply skipped.
upvote count: 3
answer count: 1
tagged with: jupyter-console
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51565975
tagged with: python
type: AnsweredQuestion
score: 3
has title: debug magic function in ipython console

http://stackoverflow.com/comment/90118407
type: Comment
comment on: http://stackoverflow.com/a/51571766
type: AnswerComment
score: 0
has text: if module are a file, why `__init__` have no module named?

http://stackoverflow.com/q/51580173
score: 0
has title: How to implement button interaction for Main Menu (Pygame)
answer count: 2
tagged with: program-entry-point
tagged with: button
has body: I've been watching a bunch of tutorials and new to pygame and coding in general. None of the tutorials I watched helped me with this. What i'm aiming for is for the buttons to change the button to a different colour when the user hovers over the button. Below is my entire code for the main menu so far. import pygame import time import random pygame.init() size = (800, 600) screen = pygame.display.set_mode(size) BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) pygame.display.set_caption("Basketball Shootout") clock = pygame.time.Clock() #GAME INTRO def game_intro(): intro = True while intro: for event in pygame.event.get(): #print(event) if event.type == pygame.QUIT: pygame.quit() quit() #Font's and text font = pygame.font.SysFont ("Times New Norman", 60) text = font.render ("", True, WHITE) #Background Image background_images = pygame.image.load("greybackground.jpg").convert() screen.blit(background_images, [0,0]) screen.blit(text, (150, 50)) #Background Music pygame.mixer.music.load('game.ogg') pygame.mixer.music.set_endevent(pygame.constants.USEREVENT) pygame.mixer.music.play() pygame.display.update() clock.tick(15) #BUTTONS screen.blit(text, (150, 50)) pygame.draw.rect(screen,(0,0,0),(300,300,205,80)); pygame.draw.rect(screen,(0,0,0),(300,400,205,80)); pygame.draw.rect(screen,(0,0,0),(300,500,205,80)); font = pygame.font.SysFont ("Times New Norman, Arial", 30) text = font.render ("START", True, WHITE) screen.blit(text, (340, 320)) font = pygame.font.SysFont ("Times New Norman, Arial", 30) text = font.render ("OPTIONS", True, WHITE) screen.blit(text, (340, 420)) font = pygame.font.SysFont ("Times New Norman, Arial", 30) text = font.render ("ABOUT", True, WHITE) screen.blit(text, (340, 520)) pygame.display.flip(); #Quit Pygame game_intro() pygame.quit
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47639826
tagged with: python
tagged with: pygame
tagged with: menu
has answer: http://stackoverflow.com/a/51580556
type: Question
has answer: http://stackoverflow.com/a/63091344

http://stackoverflow.com/comment/89947026
has text: IIRC, this can happen if you had an old Python, from before the `py.exe` launcher existed, and then installed a newer one. Instead of your scripts running with `py`, which knows how to preserve argv, they get run with `python`, which doesn't. Or something like that. But, even if I'm right, I don't remember how to get out of that state if you get into it.
comment on: http://stackoverflow.com/q/51488975
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/51519696
has comment: http://stackoverflow.com/comment/90008390
upvote count: 11
favorite count: 0
has answer: http://stackoverflow.com/a/51519942
has comment: http://stackoverflow.com/comment/90008290
has comment: http://stackoverflow.com/comment/90009042
tagged with: python
score: 11
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/90009108
has title: Idiomatic way to call method on all objects in a list of objects
linked to: http://stackoverflow.com/q/5753597
tagged with: methods
accepted answer: http://stackoverflow.com/a/51519942
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51519964
has comment: http://stackoverflow.com/comment/90008409
downvote count: 0
has comment: http://stackoverflow.com/comment/90008252
has comment: http://stackoverflow.com/comment/90008885
has comment: http://stackoverflow.com/comment/90008408
possible better answer: http://stackoverflow.com/a/51519964
has body: I have a list of objects and they have a method called process. In Python 2 one could do this map(lambda x: x.process, my_object_list) In Python 3 this will not work because map doesn't call the function until the iterable is traversed. One could do this: list(map(lambda x: x.process(), my_object_list)) But then you waste memory with a throwaway list (an issue if the list is big). I could also use a 2-line explicit loop. But this pattern is so common for me that I don't want to, or think I should need to, write a loop every time. Is there a more idiomatic way to do this in Python 3?

http://stackoverflow.com/q/51620378
has answer: http://stackoverflow.com/a/51620576
favorite count: 0
possible better answer: http://stackoverflow.com/a/51620492
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51620539
tagged with: python
has answer: http://stackoverflow.com/a/51620560
has title: Python:update a list by adding a string to all elements
upvote count: 2
has body: Python 2.7, Windows 10 I have a code that finds all the sheet names of an excel file then puts then splits the string and puts it in a list. The next step of my code needs to attach the file path to the sheet names in the list. The file path will be a constant variable. I realize that this code is incorrect, but I basically just need to be able to do something like this: List = ['test1', 'test2', 'test3'] for i in list print("file_Path" + i) 'file_path test1' 'file_path test2' But I need it to update the list or append to a new list instead of print. What is the best method to do this. I've looked pretty hard to find a good answer to this, but I realize I might be searching in the wrong place. Thanks!
has comment: http://stackoverflow.com/comment/90206373
has comment: http://stackoverflow.com/comment/90206298
has comment: http://stackoverflow.com/comment/90206276
downvote count: 1
type: Question
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51620560
has answer: http://stackoverflow.com/a/51621775
answer count: 6
has answer: http://stackoverflow.com/a/51620546
has answer: http://stackoverflow.com/a/51620492
has comment: http://stackoverflow.com/comment/90206852

date
tags question: http://stackoverflow.com/q/51581776
tag name: date
tags question: http://stackoverflow.com/q/51558194
tags question: http://stackoverflow.com/q/51621082
tags question: http://stackoverflow.com/q/51535629
tags question: http://stackoverflow.com/q/51543965
type: Tag
tags question: http://stackoverflow.com/q/51636658
tags question: http://stackoverflow.com/q/51530947
tags question: http://stackoverflow.com/q/51605307
tags question: http://stackoverflow.com/q/51587468

outliers
tags question: http://stackoverflow.com/q/51554983
type: Tag
tag name: outliers
tags question: http://stackoverflow.com/q/51622490

http://stackoverflow.com/a/51600552
score: 1
has comment: http://stackoverflow.com/comment/90167746
accepted answer of: http://stackoverflow.com/q/51600034
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51600034
has comment: http://stackoverflow.com/comment/90167709
has body: You can use np.where to find the non zero indices. For example (m=3 and n=6): x= np.array([1,0,0,2,3,1]) Y = np.array([[1,2,3,4,5,6], [4,5,6,1,2,3], [7,8,9,4,5,1]]) ind = np.where(x != 0)[0] result = sum(x[ind]*np.max(Y[:,ind], axis=0)) print (result) Output 36.0
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51598770
has comment: http://stackoverflow.com/comment/90163563
has title: Expected behavior of Pandas str.isnumeric()
downvote count: 0
tagged with: string
favorite count: 0
possible better answer: http://stackoverflow.com/a/51598902
tagged with: python
has body: I have a multi-dtype series pd.Series like [100, 50, 0, foo, bar, baz] when I run pd.Series.str.isnumeric() I get [NaN, NaN, NaN, False, False, False] Why is this happening? Shouldn't it return True for the first three in this series?
upvote count: 6
has answer: http://stackoverflow.com/a/51598890
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51598890
score: 6
type: Question
has answer: http://stackoverflow.com/a/51598902
answer count: 2
tagged with: pandas

http://stackoverflow.com/q/51489746
has comment: http://stackoverflow.com/comment/89948236
has comment: http://stackoverflow.com/comment/89948157
tagged with: python
score: 14
type: AnsweredQuestion
upvote count: 14
tagged with: selenium
has body: I want to import selenium WebElement since I need to check if a function returns a WebElement or not I have googled but only find how to import selenium, such as from selenium import webdriver, I already have that working. The error part is the type checking line such as: if isinstance(var, WebElement): #do something else: #do nothing so the question is what is the class path for selenium's WebElement? for example from selenium.common import WebElement (already tried this and not working)
type: Question
has answer: http://stackoverflow.com/a/59999387
has title: how to import selenium WebElement in python
accepted answer: http://stackoverflow.com/a/59999387
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/89956101
type: Comment
has text: can you add the data and the full code ?
score: 0
comment on: http://stackoverflow.com/q/51483951
type: QuestionComment

http://stackoverflow.com/q/51512672
type: UnansweredQuestion
has body: I want to calculate the angle using data from a text file. Right now, I have a python code which can calculate the angle. import numpy as np a = np.array([27.090, 26.790, 4.920]) b = np.array([26.790, 26.400, 5.740]) c = np.array([27.490, 26.590, 6.370]) ba = a - b bc = c - b cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc)) angle = np.arccos(cosine_angle) print np.degrees(angle) But i want this python code should take coordinates from a text file (coord.txt). Because I have multiple coordinates in the text file like 27.090 26.790 4.920 26.790 26.400 5.740 27.490 26.590 6.370 Format of text file is x1 y1 z1 x2 y2 z2 x3 y3 z3 for each line and it should give angle corresponding to each line. Code should consider coordinate from text file and write angle in another text file.
has comment: http://stackoverflow.com/comment/89994043
has answer: http://stackoverflow.com/a/51513584
has answer: http://stackoverflow.com/a/51512877
type: Question
score: -1
has title: Read coordinates of points three by three from a text file with Numpy?
upvote count: 2
tagged with: numpy
answer count: 2
favorite count: 0
downvote count: 3
tagged with: python

http://stackoverflow.com/comment/90107065
has text: ...also, `export Path` should be `export PATH`. Environment variables on UNIX-like systems are case sensitive (not on Windows).
comment on: http://stackoverflow.com/q/51570306
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51526613
tagged with: unity-game-engine
type: Question
linked to: http://stackoverflow.com/q/49793560
upvote count: 1
answer count: 1
tagged with: tensorflow
tagged with: c#
has title: Reference a python script through Unity
has answer: http://stackoverflow.com/a/51526918
linked to: http://stackoverflow.com/q/46527470
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51526918
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90021886
type: AnsweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/40106644
favorite count: 0
has body: So I did some research on the subject, and it turns out there is such a thing as a Python interpreter for Unity, but I'm only interested in using Python as a quick calculation step in my project. Long story short, I want to be able to input an array of numbers into a Python script and get an array of numbers back in a coroutine or an Update function. Performance is key, as I'm planning on doing matrix calculations in Python, using TensorFlow and Numpy. Any way to achieve this and retain at least MOST of its efficiency? PS. I will also want to later build to an Android / iOS device. Am I asking for too much? Thanks in advance!

http://stackoverflow.com/comment/90150872
score: 2
type: Comment
has text: ty for your answer, but i did it, i want to make this without creating another photo, is this posible?
comment on: http://stackoverflow.com/a/51592397
type: AnswerComment

http://stackoverflow.com/a/51921373
answers question: http://stackoverflow.com/q/51614092
has body: I simplified your code and was able to get the color of the centroids without using moment. import imutils import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imread("multiplegrains.png") resized = imutils.resize(img, width=900) ratio = img.shape[0] / float(resized.shape[0]) gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) _, cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # if you want cv2.contourArea &gt;1, you can just comment line bellow cnts = np.array(cnts)cv2.contourArea(c)&gt;10 for c in cnts grains = [np.int0(cv2.boxPoints(cv2.minAreaRect(c))) for c in cnts] centroids =[(grain[2][1]-(grain[2][1]-grain[0][1])//2, grain[2][0]-(grain[2][0]-grain[0][0])//2) for grain in grains] colors = [resized[centroid] for centroid in centroids]
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51622865
score: 4
has title: break up a .wav file by timestamp
has body: I am new to the audio processing scene. I have a set of timestamps generated by a speech parsing program. What I want to do now is to break up the full wav file into segments specified by the list of timestamps. Can someone recommend a python library I can use for this job?
linked to: http://stackoverflow.com/q/37999150
has answer: http://stackoverflow.com/a/52264015
answer count: 2
has comment: http://stackoverflow.com/comment/90211116
favorite count: 0
has answer: http://stackoverflow.com/a/51623035
tagged with: python
tagged with: parsing
type: UnansweredQuestion
downvote count: 1
type: Question
tagged with: audio
upvote count: 5
tagged with: wav

http://stackoverflow.com/a/59463739
has body: You should try this configuration = sib_api_v3_sdk.Configuration() configuration.api_key['api-key'] = 'YOUR_API_KEY'
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51617162

http://stackoverflow.com/q/51580218
score: 0
tagged with: file-io
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51613848
has title: Reading BSD500 groundTruth with scipy
tagged with: scipy
type: Question
tagged with: numpy
has body: I am trying to load using scipy loadmat a ground truth file, it return numpy ndarray of type object (dtype='O'). From that object I arrive to access to each element that are also ndarrays but I am struggling from that point to access to either the segmentation or the boundaries image. I would like a to transform this a list of list of ndarray of numerical types how can I do that ? Thanks in advance for any help
has answer: http://stackoverflow.com/a/51613848
answer count: 1

http://stackoverflow.com/a/51582156
answers question: http://stackoverflow.com/q/51582123
has comment: http://stackoverflow.com/comment/90129665
score: 0
type: Answer
has body: This works as follows: "%s %d {N similar elements}" % (a, b, ...N similar values) So, you should just do: print ar % tuple(le_temp_list_val) There's no need to create the string ar_val because it will be treated as the only argument.
has comment: http://stackoverflow.com/comment/90130560
has comment: http://stackoverflow.com/comment/90129537

http://stackoverflow.com/a/51588041
has comment: http://stackoverflow.com/comment/90142036
has comment: http://stackoverflow.com/comment/90145235
has comment: http://stackoverflow.com/comment/90141301
score: 0
has body: Your python interpreter is looking for the cnt variable on the local scope, which happens because of the assignment to it. Consider this example, which shows the same behaviour: c = 0 def foo(): c=c+1 foo() Traceback (most recent call last): File "C:\...\miniconda3\envs\py36\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-4-c19b6d9633cf&gt;", line 1, in &lt;module&gt; foo() File "&lt;ipython-input-3-454c342b701e&gt;", line 2, in foo c=c+1 UnboundLocalError: local variable 'c' referenced before assignment Now if you were to write instead c=0 def foo(): d=c+1 foo() There will be no error. In order to convince your interpreter to use the global variable instead of searching for it on the local scope, use the global keyword: c=0 def foo(): global c c = c+1 foo() print(c) Out[11]: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51587923
type: Answer
answers question: http://stackoverflow.com/q/51587923

http://stackoverflow.com/a/51604520
has comment: http://stackoverflow.com/comment/90203634
type: Answer
score: 6
upvote count: 6
has body: OK If you have the 2.66 GHz version that seems to me to be the the Arrendale architecture released 2010 in which case there is absolutely no chance it's going to work since that thing doesn't have AVX instructions as needed by the latest binaries of tensor flow. Unless your CPU is Sandy Bridge or newer (so AVX instructions) your options are: 1) get a newer CPU 2) install an older version of tensor flow 3) compile tensor flow from source for downgrade version see. Illegal instruction(core dumped) tensorflow Illegal instruction when import tensorflow in Python EDIT It seems that although all Core (i3, i5, i7) and Xeon CPU Sandy Bridge and newer support AVX, this is not true of Celron, nor Pentium CPU's to this day, as of 2018. Check what the machine contains if buying hardware.
accepted answer of: http://stackoverflow.com/q/51599488
has comment: http://stackoverflow.com/comment/90204738
answers question: http://stackoverflow.com/q/51599488
type: AcceptedAnswer
downvote count: 0

python-2.7
tags question: http://stackoverflow.com/q/51494675
tags question: http://stackoverflow.com/q/51610053
tags question: http://stackoverflow.com/q/51595613
tags question: http://stackoverflow.com/q/51564929
tags question: http://stackoverflow.com/q/51508352
tags question: http://stackoverflow.com/q/51608584
tags question: http://stackoverflow.com/q/51622109
tags question: http://stackoverflow.com/q/51632928
tags question: http://stackoverflow.com/q/51628255
tags question: http://stackoverflow.com/q/51552195
tags question: http://stackoverflow.com/q/51588887
tags question: http://stackoverflow.com/q/51630114
tags question: http://stackoverflow.com/q/51618709
tags question: http://stackoverflow.com/q/51594877
tags question: http://stackoverflow.com/q/51626161
tags question: http://stackoverflow.com/q/51542630
tags question: http://stackoverflow.com/q/51513386
tags question: http://stackoverflow.com/q/51568156
tags question: http://stackoverflow.com/q/51516790
tags question: http://stackoverflow.com/q/51531741
tags question: http://stackoverflow.com/q/51579852
tags question: http://stackoverflow.com/q/51559201
tags question: http://stackoverflow.com/q/51572352
tags question: http://stackoverflow.com/q/51613385
tags question: http://stackoverflow.com/q/51614629
tags question: http://stackoverflow.com/q/51637149
tags question: http://stackoverflow.com/q/51551067
tags question: http://stackoverflow.com/q/51620378
tags question: http://stackoverflow.com/q/51513195
tags question: http://stackoverflow.com/q/51552327
tags question: http://stackoverflow.com/q/51556272
tags question: http://stackoverflow.com/q/51591943
tags question: http://stackoverflow.com/q/51526478
tags question: http://stackoverflow.com/q/51639041
tags question: http://stackoverflow.com/q/51490737
tags question: http://stackoverflow.com/q/51505334
tags question: http://stackoverflow.com/q/51635266
tags question: http://stackoverflow.com/q/51639547
tags question: http://stackoverflow.com/q/51591267
tags question: http://stackoverflow.com/q/51537967
tags question: http://stackoverflow.com/q/51507490
tags question: http://stackoverflow.com/q/51597936
tags question: http://stackoverflow.com/q/51571652
tags question: http://stackoverflow.com/q/51571291
tags question: http://stackoverflow.com/q/51630353
tags question: http://stackoverflow.com/q/51490675
tags question: http://stackoverflow.com/q/51553688
tags question: http://stackoverflow.com/q/51572796
tags question: http://stackoverflow.com/q/51491593
tags question: http://stackoverflow.com/q/51566014
tags question: http://stackoverflow.com/q/51529556
tags question: http://stackoverflow.com/q/51503160
tags question: http://stackoverflow.com/q/51561493
tags question: http://stackoverflow.com/q/51489570
tags question: http://stackoverflow.com/q/51499085
tags question: http://stackoverflow.com/q/51625265
tags question: http://stackoverflow.com/q/51612146
tags question: http://stackoverflow.com/q/51607406
tags question: http://stackoverflow.com/q/51499034
tags question: http://stackoverflow.com/q/51482688
tags question: http://stackoverflow.com/q/51566068
tags question: http://stackoverflow.com/q/51506188
tags question: http://stackoverflow.com/q/51619046
tags question: http://stackoverflow.com/q/51600013
tags question: http://stackoverflow.com/q/51486567
tags question: http://stackoverflow.com/q/51634530
tags question: http://stackoverflow.com/q/51499078
tags question: http://stackoverflow.com/q/51544434
tags question: http://stackoverflow.com/q/51587935
tags question: http://stackoverflow.com/q/51506200
tags question: http://stackoverflow.com/q/51561321
tags question: http://stackoverflow.com/q/51551333
tags question: http://stackoverflow.com/q/51619554
tags question: http://stackoverflow.com/q/51633927
tags question: http://stackoverflow.com/q/51638861
tags question: http://stackoverflow.com/q/51492267
tags question: http://stackoverflow.com/q/51613290
tags question: http://stackoverflow.com/q/51542807
tags question: http://stackoverflow.com/q/51495626
tags question: http://stackoverflow.com/q/51577733

http://stackoverflow.com/comment/90036682
type: QuestionComment
score: 0
has text: Well, that's only if you make the image bigger then it will look like pixels but if you don't make it big it looks perfect
comment on: http://stackoverflow.com/q/51533996
type: Comment

http://stackoverflow.com/comment/89980399
type: QuestionComment
comment on: http://stackoverflow.com/q/51505121
type: Comment
has text: Please provide a testable example. There is not enough here to work with accurately. Please provide [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
score: 0

http://stackoverflow.com/comment/90176563
has text: Ah I got it to work, it was because of it being the long dash instead of the short dash. thanks for the help!
score: 0
comment on: http://stackoverflow.com/q/51605307
type: Comment
type: QuestionComment

label
tags question: http://stackoverflow.com/q/51490358
tags question: http://stackoverflow.com/q/51613195
tag name: label
tags question: http://stackoverflow.com/q/51488701
tags question: http://stackoverflow.com/q/51525043
tags question: http://stackoverflow.com/q/51491487
type: Tag
tags question: http://stackoverflow.com/q/51621278

http://stackoverflow.com/q/51515024
tagged with: django
type: Question
has body: I am trying to get it so anytime my function delete_curricula_info is activated it then redirects to CurriculumClasses url class CurriculumClasses(TemplateView): template_name = 'architect/assignclasses.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = AssignClassForm(self.request.GET or None) context['classes'] = Classes.objects.all() context['curricula_infos'] = CurriculaInfo.objects.all() context['course_abbr'] = self.kwargs.get('course_abbr') context['year'] = self.kwargs.get('year') context['semester'] = self.kwargs.get('semester') context['module_abbr'] = self.kwargs.get('module_abbr') context['curricula'] = Curricula.objects.get( course_period__course__course_abbreviation=self.kwargs.get('course_abbr'), module_period__module__module_abbreviation=self.kwargs.get('module_abbr'), course_period__period__academic_year=self.kwargs.get('year'), course_period__period__semester=self.kwargs.get('semester')).pk return context def delete_curricula_info(request, pk): curricula_info = get_object_or_404(CurriculaInfo, pk=pk) curricula_info.delete() return redirect('curriculum_classes') Heres my urls.py path('courses/&lt;str:course_abbr&gt;/&lt;str:module_abbr&gt;/&lt;int:year&gt;/&lt;int:semester&gt;/classes/', views.CurriculumClasses.as_view(), name='curriculum_classes'), path('delete-curricula-info/&lt;int:pk&gt;/', views.delete_curricula_info, name='delete_curricula_info') The url for my CurriculumClasses is using a dynamic one so i could not hardcode the url to the return redirect of my function. So how do i redirect as my current method does not work. Thanks.
has comment: http://stackoverflow.com/comment/89999360
has answer: http://stackoverflow.com/a/51515648
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: Django function redirects back to class
has comment: http://stackoverflow.com/comment/89999173
has comment: http://stackoverflow.com/comment/89999334

plot
tags question: http://stackoverflow.com/q/51556953
tags question: http://stackoverflow.com/q/51545057
tags question: http://stackoverflow.com/q/51486099
tags question: http://stackoverflow.com/q/51558901
tags question: http://stackoverflow.com/q/51637246
tag name: plot
tags question: http://stackoverflow.com/q/51488045
tags question: http://stackoverflow.com/q/51573324
tags question: http://stackoverflow.com/q/51552229
tags question: http://stackoverflow.com/q/51606234
tags question: http://stackoverflow.com/q/51611168
tags question: http://stackoverflow.com/q/51576320
tags question: http://stackoverflow.com/q/51563338
tags question: http://stackoverflow.com/q/51620286
type: Tag
tags question: http://stackoverflow.com/q/51560880
tags question: http://stackoverflow.com/q/51630006
tags question: http://stackoverflow.com/q/51543377
tags question: http://stackoverflow.com/q/51514840
tags question: http://stackoverflow.com/q/51532581
tags question: http://stackoverflow.com/q/51487391
tags question: http://stackoverflow.com/q/51624813
tags question: http://stackoverflow.com/q/51544930
tags question: http://stackoverflow.com/q/51613756
tags question: http://stackoverflow.com/q/51620634
tags question: http://stackoverflow.com/q/51590602
tags question: http://stackoverflow.com/q/51508237
tags question: http://stackoverflow.com/q/51495819

c++
tags question: http://stackoverflow.com/q/51635113
tags question: http://stackoverflow.com/q/51599420
tags question: http://stackoverflow.com/q/51599699
tags question: http://stackoverflow.com/q/51633430
tags question: http://stackoverflow.com/q/51490254
tags question: http://stackoverflow.com/q/51547126
tags question: http://stackoverflow.com/q/51485839
type: Tag
tags question: http://stackoverflow.com/q/51508191
tags question: http://stackoverflow.com/q/51598137
tags question: http://stackoverflow.com/q/51494211
tags question: http://stackoverflow.com/q/51495929
tags question: http://stackoverflow.com/q/51562800
tags question: http://stackoverflow.com/q/51494242
tag name: c++
tags question: http://stackoverflow.com/q/51497357

http://stackoverflow.com/q/51536771
has title: pandas left join on column with list values
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/51537018
type: AnsweredQuestion
has body: Giving this two Data samples, I would like to join by a column that in the left join dataframe the value is a list of one element of several and in the other dataframe is the same colum (primary key) with aditional information without list as format. with this example df1 = pd.DataFrame({'ID':[[1111],[2222,3333],[4444,5555],[6666]],'NAME':['foo','bar','zoo','bahh']}) df2 = pd.DataFrame({'ID':[[1111],[2222],[3333],[4444],[5555],[7777]],'ALT_NAME':['foo_alt','bar_alt','zoo_alt','baoo','razz','foo fi']}) print(df1) print(df2) Output[1]: ID NAME 0 [1111] foo 1 [2222, 3333] bar 2 [4444, 5555] zoo 3 [6666] bahh Output[2]: ALT_NAME ID 0 foo_alt [1111] 1 bar_alt [2222] 2 wis_alt [3333] 3 baoo [4444] 4 razz [5555] 5 foo fi [7777] The result should be: ID NAME ALT NAME 0 [1111] foo [foo_alt] 1 [2222, 3333] bar [bar_alt , wis_alt] 2 [4444, 5555] zoo [baoo, razz] 3 [6666] bahh nan Proposed solution: I could solve it by splitting the ID in several columns and do several left joins, but I expect finding onliner or smarter solution. So, The nature of this question is more python learning oriented.
upvote count: 1
has answer: http://stackoverflow.com/a/51538135
type: Question
score: 1
possible better answer: http://stackoverflow.com/a/51538135
has answer: http://stackoverflow.com/a/51537018
answer count: 2

http://stackoverflow.com/q/51610855
has title: How to find all the color shapes in an image open CV python
score: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90186978
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51611730
upvote count: 1
accepted answer: http://stackoverflow.com/a/51611730
has body: I have this image where I need to find the colored shapes in an image I need the positions of these Colored shapes. And I need to place this monkey on green triangle My code is giving me the error This code can only detect the black colour but it throws an error. # import the necessary packages import numpy as np import argparse import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", help = "path to the image file") args = vars(ap.parse_args()) # load the image image = cv2.imread(args["image"]) # find all the shapes in the image lower = np.array([0, 0, 0]) upper = np.array([15, 15, 15]) shapeMask = cv2.inRange(image, lower, upper) # find the contours in the mask (cnts, _) = cv2.findContours(shapeMask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) print ("I found %d black shapes" % (len(cnts))) cv2.imshow("Mask", shapeMask) # loop over the contours for c in cnts: # draw the contour and show it cv2.drawContours(image, [c], -1, (0, 255, 0), 2) cv2.imshow("Image", image) cv2.waitKey(0)
type: Question
tagged with: numpy
tagged with: opencv
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/90020948
score: 0
type: AnswerComment
has text: extension id in my case is "dkgjopcolgcafhnicdahjemapkniikeh" . when I go to that link, it just says your file was not found. Is there maybe a way to activate the extension instead of using Selenium clicking?
type: Comment
comment on: http://stackoverflow.com/a/51524957

http://stackoverflow.com/comment/90219470
type: Comment
comment on: http://stackoverflow.com/q/51612940
type: QuestionComment
score: 0
has text: I use Ubuntu 16.04. And I install use repository: sudo apt-get install gnuradio https://wiki.gnuradio.org/index.php/InstallingGR My PYTHONPATH is ~$ echo $PYTHONPATH :/usr/local/lib/python2.7/dist-packages:/usr/local/lib/python2.7/dist-packages

http://stackoverflow.com/comment/90075863
has text: @zindarod thank you!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51553928
score: 0

http://stackoverflow.com/a/51581373
accepted answer of: http://stackoverflow.com/q/51576272
has comment: http://stackoverflow.com/comment/90133021
type: Answer
has body: Difference in features You said that originally you have784 features, but you reduce it to 154. That may seem like a lot. However if you look at the documentation: max_features : int, float, string or None, optional (default=”auto”) The number of features to consider when looking for the best split: If “auto”, then max_features=sqrt(n_features). That means that your original problem was sqrt(784) = 28 and you reduced it to sqrt(154) = 12. Yes, it is smaller now, but not as small as you originally thought. Optimization The way that your Random forest is built, is by looking at possible splits and picking the best ones according to a certain criteria. Note the documentation: criterion : string, optional (default=”gini”) The function to measure the quality of a split. Supported criteria are “gini” for the Gini impurity and “entropy” for the information gain. Note: this parameter is tree-specific. [...] Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than max_features features. So, while fitting, the algorithm is iterating over possible splits that optimize the criterion. However, by reducing the number of features you might have made the problem to find this splits more difficult (by having less good splits to find), which makes the algorithm need more iterations to find a good split.
has comment: http://stackoverflow.com/comment/90165805
answers question: http://stackoverflow.com/q/51576272
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90102880
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51568251
has text: Use `dict(b)` here

http://stackoverflow.com/comment/90128006
has text: @shashank allow you to deploy one app for free, for a certain number of hours per month (I think it sleeps after 10 minutes of inactivity, so the free hours usually last much longer than you think - in any case it's a great way to see it in action). Once you have something working on your laptop, it takes about 10 minutes to get it on to the web
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51580854

qt
tags question: http://stackoverflow.com/q/51545428
type: Tag
tags question: http://stackoverflow.com/q/51566884
tags question: http://stackoverflow.com/q/51544077
tags question: http://stackoverflow.com/q/51559628
tags question: http://stackoverflow.com/q/51599374
tags question: http://stackoverflow.com/q/51630968
tags question: http://stackoverflow.com/q/51620072
tag name: qt

docker
tags question: http://stackoverflow.com/q/51628581
tags question: http://stackoverflow.com/q/51536577
type: Tag
tags question: http://stackoverflow.com/q/51484521
tags question: http://stackoverflow.com/q/51499715
tags question: http://stackoverflow.com/q/51629194
tags question: http://stackoverflow.com/q/51484207
tags question: http://stackoverflow.com/q/51577963
tags question: http://stackoverflow.com/q/51578720
tags question: http://stackoverflow.com/q/51544433
tags question: http://stackoverflow.com/q/51564723
tags question: http://stackoverflow.com/q/51633987
tags question: http://stackoverflow.com/q/51504221
tag name: docker
tags question: http://stackoverflow.com/q/51608355
tags question: http://stackoverflow.com/q/51550260
tags question: http://stackoverflow.com/q/51515137
tags question: http://stackoverflow.com/q/51504144
tags question: http://stackoverflow.com/q/51542285
tags question: http://stackoverflow.com/q/51636721
tags question: http://stackoverflow.com/q/51541415
tags question: http://stackoverflow.com/q/51601953
tags question: http://stackoverflow.com/q/51483896
tags question: http://stackoverflow.com/q/51590156
tags question: http://stackoverflow.com/q/51619559
tags question: http://stackoverflow.com/q/51587078
tags question: http://stackoverflow.com/q/51590885
tags question: http://stackoverflow.com/q/51580617
tags question: http://stackoverflow.com/q/51552706
tags question: http://stackoverflow.com/q/51598239

http://stackoverflow.com/comment/90183456
type: AnswerComment
type: Comment
has text: Thanks! It was such a small mistake. :)
score: 0
comment on: http://stackoverflow.com/a/51604629

http://stackoverflow.com/q/51621613
has body: I have this time series data , now I want to calculate the trend seasonality type (multiplicative or additive) for each cluster of APMC and commodities using 'modal_price'. The dataset has around 60,000 such rows with APMC and Cluster being the same but the date as changing . The dataset is as follows : APMC | Commodity | qtl _weight| min_price | max_price | modal_price | district_name | Year | Month date 2014-12-01 Akole bajri 40 1375 1750 1563 Ahmadnagar 2014 12 2014-12-01 Akole paddy-unhusked 346 1400 1800 1625 Ahmadnagar 2014 12 2014-12-01 Akole wheat 55 1500 1900 1675 Ahmadnagar 2014 12 2014-12-01 Akole bhagar/vari 59 2000 2600 2400 Ahmadnagar 2014 12 2014-12-01 Akole gram 9 3200 3300 3235 Ahmadnagar 2014 12 2014-12-01 Jamkhed cotton 44199 3950 4033 3991 Ahmadnagar 2014 12 2014-12-01 Jamkhed bajri 846 1300 1488 1394 Ahmadnagar 2014 12 2014-12-01 Jamkhed wheat(husked) 155 1879 2231 2055 Ahmadnagar 2014 12 2014-12-01 Kopar gram 421 1983 2698 2463 Ahmadnagar 2014 12 2014-12-01 Kopar greengram 18 6734 7259 6759 Ahmadnagar 2014 12 2014-12-01 Kopar soybean 1507 2945 3247 3199 Ahmadnagar 2014 12 2016-11-01 Sanga wheat(husked) 222 1730 2173 1994 Ahmadnagar 2016 11 Now I tried pivot table for this using (APMC,Commodity and date as index) but that doesn't help in calculating the mean(to calculate trend) for each cluster(APMC,Commodity). I just need to know how do i calculate mean for each cluster(APMC,Commodity) using 'modal_price' and ADD that as a COLUMN in the dataframe/pivot-table .
score: 0
tagged with: pivot-table
has answer: http://stackoverflow.com/a/51622010
type: Question
tagged with: group-by
tagged with: time-series
answer count: 1
accepted answer: http://stackoverflow.com/a/51622010
tagged with: pandas
tagged with: python
has title: Calculate seasonality and trend of time series data for each cluster
type: AnsweredQuestion

http://stackoverflow.com/q/51599532
has answer: http://stackoverflow.com/a/51599635
tagged with: django-templates
has body: I am new to json and not familiar with it. In my Django view file, I want to pass only certain json values: school, address, each student's name (Andy, Tom, Jack) and id (Andy.id, Tom.id, Jack.id) to the html from Django view. How can I achieve the above case? my json content is: { "school": "xxx", "address": "xxx", "number": "xxx, "students": { "Andy": { "id": "xxx", "add": "xxx" }, "Tom": { "id": "xxx", "add": "xxx" }, "Jack": { "id": "xxx", "add": "xxx" }, }, } In my view.py, I have got these codes. jresult is the json string and I used json.dumps() to generated JSON, but it will populate all the json data to the html. How can I achieve the above case? Any helps will be appreciated. def model_form_upload(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'].read() jresult = execution(file) json_string = json.dumps(jresult, indent=4) return render(request, 'virus/home.html', {'json_string': json_string}) else: form = FileForm() return render(request, 'virus/upload.html', { 'form': form }) my home.html template: &lt;body&gt; &lt;pre&gt;&lt;/pre&gt; &lt;/body&gt;
tagged with: django
has comment: http://stackoverflow.com/comment/90165217
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51599609
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90165153
accepted answer: http://stackoverflow.com/a/51599635
score: 0
has title: Populate specific json value to html with django template
possible better answer: http://stackoverflow.com/a/51599609
tagged with: python

iteration
tags question: http://stackoverflow.com/q/51484601
tags question: http://stackoverflow.com/q/51507698
tags question: http://stackoverflow.com/q/51548364
tags question: http://stackoverflow.com/q/51489398
tags question: http://stackoverflow.com/q/51601249
type: Tag
tags question: http://stackoverflow.com/q/51513419
tags question: http://stackoverflow.com/q/51584415
tags question: http://stackoverflow.com/q/51611143
tag name: iteration
tags question: http://stackoverflow.com/q/51531488

http://stackoverflow.com/comment/90169380
score: 0
type: Comment
type: QuestionComment
has text: The number to multiply it, will it be same for each element, like 3 or 5 etc.. ?
comment on: http://stackoverflow.com/q/51601633

http://stackoverflow.com/q/51636028
has comment: http://stackoverflow.com/comment/90236595
downvote count: 0
has comment: http://stackoverflow.com/comment/90236888
has comment: http://stackoverflow.com/comment/90236645
has answer: http://stackoverflow.com/a/51636529
has comment: http://stackoverflow.com/comment/90236493
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/51636519
score: 4
has comment: http://stackoverflow.com/comment/90237275
linked to: http://stackoverflow.com/q/728972
has comment: http://stackoverflow.com/comment/90236690
possible better answer: http://stackoverflow.com/a/51648211
has answer: http://stackoverflow.com/a/51648211
has answer: http://stackoverflow.com/a/51637127
has title: quick find all sets that are subset
has body: I have big dictionary with frozenset keys. I need to find all keys which are subset of given one. I see obvious way to do it: dictionary = { frozenset([1]): 1, frozenset([2]): 2, frozenset([3]): 3, frozenset([3, 4]): 34 } biglist= [3, 4, 5] results = {k: v for k, v in dictionary.items() if k.issubset(biglist)} assert results == {frozenset([3]): 3, frozenset([3, 4]): 34} But it is very slow for millions keys. Question is: is there any structure for fast searches of this type? UPD: Basically, I don't want to iterate over all keys executing issubset on each one. Instead I can generate all posible sets from biglist and check if it in dictionary: results = {} maxkey = max(dictionary, key=len) maxlen = len(dictionary[maxkey]) for lenght in range(1, maxlen): for subset in itertools.combinations(biglist, lenght): key = frozenset(subset) if key in dictionary: results[key] = dictionary[key] But this method is also very expensive for long biglist.
has answer: http://stackoverflow.com/a/51636519
upvote count: 4
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/90035747
comment on: http://stackoverflow.com/a/51533985
type: Comment
score: 0
type: AnswerComment
has text: I am using 2.4 chromedriver

http://stackoverflow.com/comment/90042973
type: AnswerComment
has text: https://progur.com/2017/06/how-to-use-vlc-api-in-c.html I'll write you up a proper answer later. If I don't, feel free to remind me.
comment on: http://stackoverflow.com/a/51537047
type: Comment
score: 2

http://stackoverflow.com/comment/90219206
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51627081
has text: Select "New Environment" radio button, add your virtualenv path up to where python.exe resides
score: 0

http://stackoverflow.com/a/51487123
score: 0
answers question: http://stackoverflow.com/q/51485008
has body: Well it seems to run fine now...I don't know what the problem was in Visual Studio Code, but I didn't change anything...
type: Answer

http://stackoverflow.com/comment/90200609
type: QuestionComment
comment on: http://stackoverflow.com/q/51617421
type: Comment
has text: Indent your function properly please. Python is very whitespace sensitive.
score: 1

http://stackoverflow.com/comment/90084581
has text: Updated my answer.
score: 0
comment on: http://stackoverflow.com/q/51551891
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51628114
tagged with: django-orm
tagged with: django
upvote count: 1
has body: For an analytics app that utilizes Google Realtime Analytics API, I have my models.py definitions as follows: class Report(BaseModel): ios_report = JSONField() android_report = JSONField() class Article(BaseModel): internal_id = models.IntegerField(unique=True) title = models.CharField(max_length=500) short_title = models.CharField(max_length=500) picture_url = models.URLField() published_date = models.DateField() clip_link = models.URLField() reports = models.ManyToManyField( "Report", through="ArticleInReport", related_name="articles" ) class ArticleInReport(BaseModel): article = models.ForeignKey("core.Article", on_delete=models.CASCADE, related_name='articleinreports') report = models.ForeignKey("core.Report", on_delete=models.CASCADE, related_name='articleinreports') ios_views = models.IntegerField() android_views = models.IntegerField() @property def total_views(self): return self.ios_views + self.android_views Everything starts with a Report object that is created at set intervals. This report contains data about articles and their respective views. A Report will have a relationship with an Article through ArticleInReport, which holds the total number of users in Article at the time the report was imported. In my view, I need to display the following information: All articles that received views in the last 24 hours. With each article annotated with the following information: If present, the number of views the Article object had in the last Report. If not present, 0. I'm achieving this as follows in my views.py: reports_in_time_range = Report.objects.filter(created_date__range=[starting_range, right_now]) last_report = Report.objects.last() unique_articles = Article.objects.filter(articleinreports__report__in=reports_in_time_range).distinct('id') articles = Article.objects.filter(id__in=unique_articles).distinct('id').annotate( total_views=Case( When(articleinreports__report=last_report, then=(F("articleinreports__ios_views") + F("articleinreports__android_v…
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51714041
type: Question
linked to: http://stackoverflow.com/q/52689949
has comment: http://stackoverflow.com/comment/90342163
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51714041
has title: Django: Complex annotation, how to avoid for loop?
has comment: http://stackoverflow.com/comment/90220965
has comment: http://stackoverflow.com/comment/90247213
tagged with: python
has comment: http://stackoverflow.com/comment/90220645
favorite count: 0
has comment: http://stackoverflow.com/comment/90220914

http://stackoverflow.com/comment/90202497
type: Comment
has text: In case you down voted because of missing explanation, the explanation now should revert it
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51617479

http://stackoverflow.com/comment/90051975
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51542020
type: AnswerComment
has text: @Yuca - Special for you renamed columns ;)

http://stackoverflow.com/q/51550341
has answer: http://stackoverflow.com/a/51566445
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90094996
has title: Pyspark Dataframe - Median Without Numpy Or Other Libraries
has comment: http://stackoverflow.com/comment/90096225
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51566445
tagged with: pyspark
has comment: http://stackoverflow.com/comment/90093375
tagged with: median
has comment: http://stackoverflow.com/comment/90095887
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90096579
has body: I've been working on this in pyspark for a while and I'm stuck. I'm trying to get the median of the column numbers for its respective window. I need to do this without the use of other libraries such as numpy etc. So far (as depicted below), I've grouped the dataset into windows by the column id. This is depicted by the column row_numbers which shows you what each window looks like. There are three windows in this dataframe example. This is what I would like: I want each row to also contain the median of the window of the column id without taking its own row into consideration. The location of the median I require is in my function below called median_loc Example: For the row_number = 5, I need to find the median for the rows 1 to 4 above it (i.e. not including row_number 5). The median therefore (per my requirement) is the average of the column id in the same window where row_number = 1 and row_number = 2 i.e Date id numbers row_number med_loc 2017-03-02 group 1 98 1 [1] 2017-04-01 group 1 50 2 [1] 2018-03-02 group 1 5 3 [1, 2] 2016-03-01 group 2 49 1 [1] 2016-12-22 group 2 81 2 [1] 2017-12-31 group 2 91 3 [1, 2] 2018-08-08 group 2 19 4 [2] 2018-09-25 group 2 52 5 [1, 2] 2017-01-01 group 3 75 1 [1] 2018-12-12 group 3 17 2 [1] The code I used to get the last column med_loc is as follow def median_loc(sz): if sz == 1 or sz == 0: kth = [1] return kth elif sz % 2 == 0 and sz &gt; 1: szh = sz // 2 kth = [szh - 1, szh] if szh != 1 else [1, 2] return kth elif sz % 2 != 0 and sz &gt; 1: kth = [(sz + 1) // 2] return kth sqlContext.udf.register("median_location", median_loc) median_loc = F.udf(median_loc) df = df.withColumn("med_loc", median_loc(df.row_number)-1) Note : I only made them look like a list for easier understanding. It is just to show where the median is located in the respective window. It is just for the easier understanding of folks reading this on Stack Overflow The output that I desire is as follows: Date id numbers row_number med_loc median 2017-03-02 grou…
type: Question

http://stackoverflow.com/a/54143790
has body: For playing an audio(.mp3) file you can install sudo pip3 install playsound-for python3 sudo pip2 install playsound- for python2, then you have to so the following code: from playsound import playsound playsound(path of the audio file) Thanks
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51632499

http://stackoverflow.com/comment/90155404
type: Comment
comment on: http://stackoverflow.com/a/51592924
score: 0
has text: https://stackoverflow.com/questions/51594838/janusgraph-please-add-a-key-named-configurationmanagementgraph-to-the-graph I tried the exact code in documentation but it always throws the same exception
type: AnswerComment

http://stackoverflow.com/a/51615587
answers question: http://stackoverflow.com/q/51614538
type: AcceptedAnswer
downvote count: 0
has body: When you do from os import system, you get a variable named system pointing to os.system function. Later, you assign, via patching, a different function to os.system, but system keeps to point to the old function. This is the same reason why the following works: tmp = a a = b b = tmp It doesn't happen in the first example, because you reference os.system before it is mocked. To fix your second example, I'd go with the following: from os import system from unittest import mock def echo(): system('echo "Hello"') with mock.patch('__main__.system') as mocked: print(mocked) mocked.side_effect = Exception('Patching does not work!') echo() print('Patch was ignored!') This way you make sure you patch the right reference. This is a rather common pattern. If echo function were in a file named echo.py, the patch call would look like with mock.patch('echo.system').
type: Answer
accepted answer of: http://stackoverflow.com/q/51614538
upvote count: 7
score: 7

http://stackoverflow.com/comment/90127070
type: Comment
type: QuestionComment
has text: Can you try `df.set_index('Date').plot()` instead? Looks like pandas is having trouble figuring out how to plot that when the datetime column is not the index.
score: 5
comment on: http://stackoverflow.com/q/51580774

http://stackoverflow.com/q/51484189
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/89946134
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89944619
has comment: http://stackoverflow.com/comment/89938796
has comment: http://stackoverflow.com/comment/89944531
tagged with: python
has answer: http://stackoverflow.com/a/72313385
has title: How to unpack netCDF CMIP5 Climate data to a dataframe in Python?
has comment: http://stackoverflow.com/comment/89944782
type: Question
has body: I’m new to the .nc file format and have looked extensively through available answers – if I’ve missed something, any help is appreciated! I have a CMIP5 climate file (netCDF4 format) – the dimensions are daily values over ten years for: latitude, longitude, temperature, climate projection, time. I need to iterate through each location (lat/lon pair) for each projection and perform operations on the temperature data for each month or year by location (for example, I want to sum the temperature value for all days in a single year in a single location). Using ncdump, the following data is available: Currently, I am trying to write the file to an intermediate form as an array or dataframe in Python. Is there a simple way to unpack the netCDF data and write to an array? The ideal output format would be along the lines of a dataframe where each row is a single entry with the following column headers: “latitude”, “longitude”, “projection”, “temperature”, “time”. I’ve seen examples for 2D or 3D arrays, but can’t seem to work for the higher dimensional data. Time/memory is less important than having an intermediate data format to check the calculations against. Code: import netCDF4 import collections from collections import defaultdict t1 = netCDF4.MFDataset("Extraction_tasmax.nc") # t1.variables.keys() tmax = t1.variables['tasmax'] lat = t1.variables['latitude'][:] lon = t1.variables['longitude'][:] time = t1.variables['time'][:] tempmax = t1.variables['tasmax'][:, :, :, :] # projection, time, lat, lon column_names = ['tempmax', 'projection', 'time', 'latitude', 'longitude'] temp_list = [] for projection in tempmax: for time in projection: for lat in time: for lon in lat: temp_list.append([tempmax, projection, time, lat, lon]) temperature_data = pd.DataFrame(temp_list, columns = column_names) EDIT: Current output (small clip - returning very large data list)
has comment: http://stackoverflow.com/comment/89943123
has comment: http://stackoverflow.com/comment/89937320

http://stackoverflow.com/comment/90184704
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/a/11456666/3776299
comment on: http://stackoverflow.com/q/51610002
score: 0

http://stackoverflow.com/q/51503717
answer count: 2
tagged with: pandas
has body: I want to generate a summary table from a tidy pandas DataFrame. I now use groupby and two for loops, which does not seem efficient. Seems stacking and unstacking would get me there, but I have failed. Sample data import pandas as pd import numpy as np import copy import random df_tidy = pd.DataFrame(columns = ['Stage', 'Exc', 'Cat', 'Score']) for _ in range(10): df_tidy = df_tidy.append( { 'Stage': random.choice(['OP', 'FUEL', 'EOL']), 'Exc': str(np.random.randint(low=0, high=1000)), 'Cat': random.choice(['CC', 'HT', 'PM']), 'Score': np.random.random(), }, ignore_index=True ) df_tidy returns Stage Exc Cat Score 0 OP 929 HT 0.946234 1 OP 813 CC 0.829522 2 FUEL 114 PM 0.868605 3 OP 896 CC 0.382077 4 FUEL 10 CC 0.832246 5 FUEL 515 HT 0.632220 6 EOL 970 PM 0.532310 7 FUEL 198 CC 0.209856 8 FUEL 848 CC 0.479470 9 OP 968 HT 0.348093 I would like a new DataFrame with Stages as columns, Cats as rows and sum of Scores as values. I achieve it this way: Working but probably inefficient approach new_df = pd.DataFrame(columns=list(df_tidy['Stage'].unique())) for cat, small_df in df_tidy.groupby('Cat'): for lcs, smaller_df in small_df.groupby('Stage'): new_df.loc[cat, lcs] = smaller_df['Score'].sum() new_df['Total'] = new_df.sum(axis=1) new_df Which returns what I want: OP FUEL EOL Total CC 1.2116 1.52157 NaN 2.733170 HT 1.29433 0.63222 NaN 1.926548 PM NaN 0.868605 0.53231 1.400915 But I cannot believe this is the simplest or most efficient path. Question What pandas magic am I missing out on? Update - Timing the proposed solutions To understand the differences between pivot_table and crosstab proposed below, I timed the three solutions with a 100,000 row dataframe built exactly as above: groupby solution, that I thought was inefficient: %%timeit new_df = pd.DataFrame(columns=list(df_tidy['Stage'].unique())) for cat, small_df in df_tidy.groupby('Cat'): for lcs, smaller_df in small_df.groupby('Stage'): new_df.loc[cat, lcs] = smaller_df['Score'].sum() new_df['Total'] = new_df.sum(…
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/119661981
tagged with: python
linked to: http://stackoverflow.com/q/36267745
possible better answer: http://stackoverflow.com/a/51504105
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51504105
type: Question
has answer: http://stackoverflow.com/a/51503825
accepted answer: http://stackoverflow.com/a/51503825
has title: Alternative to groupby for generating a summary table from tidy pandas DataFrame

http://stackoverflow.com/q/51495283
has comment: http://stackoverflow.com/comment/89958687
has comment: http://stackoverflow.com/comment/89959665
tagged with: django
has comment: http://stackoverflow.com/comment/89959445
type: Question
has body: Can't figure out why, but after collecting new static files (collectstatic), nginx throws 403 Error. New files have different permissions from old static files. -rw-rw-r-- 1 django django 115206 Jul 9 15:23 dom.jpg -rw-r----- 1 django django 884 Jul 23 20:42 error.svg -rw-rw-r-- 1 django django 308934 Mar 11 16:30 header.bmp -rw-rw-r-- 1 django django 20188 Mar 11 16:30 header.jpg -rw-r----- 1 django django 910 Jul 23 20:42 success.svg -rw-rw-r-- 1 django django 1826 Jul 9 15:23 user.svg As you can see - error.svg and success.svg have different permissions, that's why nginx throws 403. Do you know how to fix this? I don't want just change permission for existing files, I want universal solution so this never happens again. top returns this: 9143 django 20 0 59124 6580 4904 S 0.0 1.3 0:07.44 gunicorn 9149 django 20 0 213640 67600 8692 S 0.0 13.5 0:07.91 gunicorn 9150 django 20 0 215224 68680 8520 S 0.0 13.7 0:08.95 gunicorn 9151 django 20 0 215056 68420 8512 S 0.0 13.7 0:09.32 gunicorn 32386 root 20 0 126132 1168 684 S 0.0 0.2 0:00.00 nginx 32387 www-data 20 0 127076 4580 3308 S 0.0 0.9 0:03.43 nginx
tagged with: nginx
has comment: http://stackoverflow.com/comment/89959557
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/89962622
score: 0
has comment: http://stackoverflow.com/comment/89959527
has comment: http://stackoverflow.com/comment/89960252
answer count: 1
has answer: http://stackoverflow.com/a/51495447
has comment: http://stackoverflow.com/comment/89959287
tagged with: django-staticfiles
type: UnansweredQuestion
has title: Django/Nginx 403 Error on new static files
tagged with: python

http://stackoverflow.com/a/51546652
upvote count: 1
answers question: http://stackoverflow.com/q/51545811
accepted answer of: http://stackoverflow.com/q/51545811
has body: You can simply wrap the code you've already written in a function. Maybe something like this could be enough: import pylab as plt import numpy as np def compute_derivative(x, y): # if finite differennces are enough # https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.diff.html return x[:-1], np.diff(y) # otherwise you can use the gradient function of numpy, # with the second argument as the step of your samples # take a look here https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.gradient.html # return x, np.gradient(y, 0.1) def create_graphs_from_file(filepath): data = np.loadtxt(filepath) x = data[:, 0] y = -1 * data[:, 1] z = data[:, 3] derivative_x, derivative_y = compute_derivative(x, y) fig_title = '{}: Length = 100, Width = 100'.format(filepath) plt.figure(fig_title) plt.title(fig_title) plt.plot(x, y, color='b', label='Drain Current') plt.plot(x, z, color='r', label='Leak Current') plt.plot(derivative_x, derivative_y, color='g', label='Derivative of the Drain Current') plt.xlabel(r'$V_G') plt.ylabel(r'$I_{DS}') plt.legend(loc=1) if __name__ == '__main__': # list with filepaths of the files you want to plot files_to_plot = [ 'filepath1', 'filepath2', 'filepath3', ] for f in files_to_plot: create_graphs_from_file(f) plt.show() Obviously you can change compute_derivative with whatever you want. You can take a look to these answers: Derivative using Numpy Finite differences vs derivative
has comment: http://stackoverflow.com/comment/90093727
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/90091579

http://stackoverflow.com/a/51485725
answers question: http://stackoverflow.com/q/51484371
has body: As I have mentioned in my comments; You cannot directly import ewma module in that way in later versions of Pandas. It worked for me in version 0.19, but not in 0.23, which you use. So what you would want to do is, try something like: df = DataFrame(...) df.ewm(com=0.5).mean() Hope it helps!!
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/a/51568025
has body: MEHTOD 1 We can use list comprehension, Slices and .join() operator. my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] for item in my_list: print ' '.join(str(x) for x in item[::-1]) output: 3 2 1 6 5 4 10 9 8 7 MEHTOD 2 We can use nested for loop and Slices operator. for xs in my_list: for x in xs[::-1]: print x, print And print() by default prints new-line characters at the end unless you use: print(end="") or if you were using Python 2.x print t, would work. output: 3 2 1 6 5 4 10 9 8 7
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51568024
has comment: http://stackoverflow.com/comment/90102394
answers question: http://stackoverflow.com/q/51568024
type: Answer

http://stackoverflow.com/comment/90061148
score: 1
comment on: http://stackoverflow.com/q/51546354
type: Comment
type: QuestionComment
has text: You can also use a dictionary to kinda emulate switch case functionality, if you don't like if/elif/else

http://stackoverflow.com/comment/89985126
has text: @stackuser So shouldn't there be 2 `12`'s instead of 2 `2`'s for the second list?
score: 0
comment on: http://stackoverflow.com/q/51507943
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90045871
type: Comment
comment on: http://stackoverflow.com/a/51529325
has text: Okay, glad to hear it. I'm not sure how to answer your question in a way that generalizes beyond PB though. I think it is strictly a question about the features and usage of PB. So I suppose I'll stand by my answer (or non-answer, if you like).
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90163397
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51597741
has text: @Jean-FrançoisFabre I changed map to list comprehensive

http://stackoverflow.com/comment/90119913
has text: This smells like an XY problem. What are you actually trying to do?
comment on: http://stackoverflow.com/q/51576921
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/51616596
answers question: http://stackoverflow.com/q/51616315
accepted answer of: http://stackoverflow.com/q/51616315
has comment: http://stackoverflow.com/comment/90200917
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90198904
type: Answer
has comment: http://stackoverflow.com/comment/90200051
score: 2
has body: Try this for a one-liner: r = get_finance_rate([eq_opt_px.index[0],vol_opt_px.index[0]], expiry)\ .pipe(lambda x: x.set_index(x.ticker.str.split().str[0]).rename_axis('aux_id') IIUC, you have to do this in two steps: r = get_finance_rate([eq_opt_px.index[0],vol_opt_px.index[0]], expiry) r = r.set_index(r.ticker.str.split().str[0]).rename_axis('aux_id') Output: ticker field value aux_id SPX SPX US 08/17/2018 C2830.0 Index OPT_FINANCE_RT 2.004648 VXX VXX US 08/17/2018 C27.0 Index OPT_FINANCE_RT 2.032480
has comment: http://stackoverflow.com/comment/90198850

http://stackoverflow.com/comment/90305416
comment on: http://stackoverflow.com/a/51638553
type: AnswerComment
score: 1
has text: `conda install tqdm`. Wait until it done. Then you try `pip install gender-guesser`
type: Comment

http://stackoverflow.com/q/51634965
tagged with: polygon
has answer: http://stackoverflow.com/a/51638674
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90234322
tagged with: psychopy
has comment: http://stackoverflow.com/comment/90235036
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/51638674
has body: I want to draw a right-angled triangle with a grey covered area in Psychopy but I only get an equilateral triangle. It should cover the half of a square. The blue lines indicate the frame of interest. #!/usr/bin/env python2 # -*- coding: utf-8 -*- #Designed for PsychoPy v1.85.6 from __future__ import unicode_literals from psychopy import visual, core, event, gui, data import sys # to get file system encoding reload(sys) sys.setdefaultencoding('utf8') win = visual.Window(fullscr=True, color= '#FFFFFF', monitor ="WorkingSpace", units="deg") border = visual.Rect(win, width=20,height=20, lineColor='black', lineWidth=5) diag = visual.Polygon(win, edges=3, radius=11.5, fillColor='#E6E6E6',pos=[-4.2,0], ori =90) line1 = visual.Line(win, start=(10, -10), end=(-10,10), lineColor="blue", lineWidth=10) line2 = visual.Line(win, start=(-10, -10), end=(-10,10), lineColor="blue", lineWidth=10) line3 = visual.Line(win, start=(10, -10), end=(-10,-10), lineColor="blue", lineWidth=10) border.draw() diag.draw() line1.draw() line2.draw() line3.draw() win.flip() event.waitKeys(keyList=['space']) #press space to continue win.close() I am using PsychoPy2 v1.85.6
upvote count: 1
has title: How can I draw a right-angled triangle in Python/PsychoPy?
type: AnsweredQuestion
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90235608

http://stackoverflow.com/q/51611532
downvote count: 1
score: 4
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51706342
upvote count: 5
tagged with: telegram-bot
has body: Here is my piece of code bot.edit_message_text(chat_id = CHAT_ID, message_id = MESSAGE_ID, text = "message has been updated", reply_markup=inline_keyboard)
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51706342
tagged with: python-telegram-bot
tagged with: telegram
tagged with: python
has title: how to get chat_id and message_id in telebot(pytelegramBotAPI) to update last sent message in telegram bot(Python)

http://stackoverflow.com/comment/116068453
comment on: http://stackoverflow.com/a/51790991
type: AnswerComment
score: 0
type: Comment
has text: Since SO comments are limited in terms of their length and formatting, feel free to post an actual SO question or post a question to the SQLAthanor [Issues](https://github.com/insightindustry/sqlathanor/issues) list - happy to give a more comprehensive answer if you’d find it helpful.

http://stackoverflow.com/q/51596908
has comment: http://stackoverflow.com/comment/90192971
has title: Django: Unable to login on site but on local server it works, not on site
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90160172
has comment: http://stackoverflow.com/comment/90164470
answer count: 0
type: UnansweredQuestion
tagged with: authentication
type: Question
has comment: http://stackoverflow.com/comment/90183331
has comment: http://stackoverflow.com/comment/90159900
score: 0
has comment: http://stackoverflow.com/comment/90160034
has comment: http://stackoverflow.com/comment/90183928
has body: I have tried to check my code, but I can't find the solution or bug... On local server the site runs normally, login works. but I have installed it on A2 hosting server, and the site runs but I can't login, I have logged in with correct user and password. But it always returned to wrong page and I'm not logged in, the session id cookie is set... Can someone help me? here the code of my settings Django settings for signbank project. import os from signbank.settings.server_specific import * from datetime import datetime DEBUG = True PROJECT_DIR = os.path.dirname(BASE_DIR) MANAGERS = ADMINS TIME_ZONE = 'Europe/Amsterdam' LOCALE_PATHS = [BASE_DIR+'conf/locale'] SITE_ID = 1 USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_ROOT = WRITABLE_FOLDER MEDIA_URL = URL+'/media/' MEDIA_MOBILE_URL = MEDIA_URL # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '/home/signbank/SB/static/' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = URL+'/files/static/' # Additional locations of static files STATICFILES_DIRS = ( os.path.join(STATIC_URL, "static"), ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '^g=q21r_nnmbz49d!vs*2gvpll-y9b@&amp;amp;t3k2r3c$*u&amp;amp;2la5!%s_' MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMid…

http://stackoverflow.com/q/51629107
has body: I'm trying to specify the dates on a datepicker from this application: http://www.wetter-by.de/Internet/AM/inetcntrBY.nsf/cuhome.xsp?src=4JHVFJGNW4&amp;p1=535TN12L42&amp;p3=2CQ7BH7901&amp;p4=4D078O1691 Though, I wasn't able to switch to the iframe, because Firefox would only give me the absolute xpath. Also, Chropath does not seem to work on this particular iframe. Instead, I switch to the direct link: http://dlr45.aspdienste.de/cgi-bin/wdaasc/wdaa_client.pl?cid=7 The datepicker takes numbers by typing, too, so I tried to specify my dates by sending keys. This is my first try: browser = webdriver.Firefox() browser.get('http://dlr45.aspdienste.de/cgi-bin/wdaasc/wdaa_client.pl?cid=7') browser.maximize_window() select = Select(browser.find_element_by_id('sid')) select.select_by_index(2) from_date = browser.find_element_by_xpath("//input[@id='from']") from_date.send_keys("01102016") from_date.send_keys(Keys.RETURN) The error states that the Element is not reachable by keyboard, so I accessed the calendar directly, here is my second try: browser = webdriver.Firefox() browser.get('http://dlr45.aspdienste.de/cgi-bin/wdaasc/wdaa_client.pl?cid=7') browser.maximize_window() select = Select(browser.find_element_by_id('sid')) select.select_by_index(2) from_date = browser.find_element_by_xpath("//input[@id='from']") #Specify year ActionChains(browser).move_to_element(from_date).click().send_keys("2016").perform() WebDriverWait(browser,4) #Jump to Oktober for i in np.arange(9): next_month = browser.find_element_by_class_name('ui-datepicker-next') next_month.click() day = browser.find_element_by_class_name('ui-state-default') ActionChains(browser).move_to_element(day).send_keys('01').perform() So far, the month and the year are correctly picked, and it looks like the 1st of October is being selected, but not clicked. Is there an easy way to send the dates (like in my first try)? If not, how can I click the day, as in the second? I don't need the iframe-switch anymore but if someon…
score: 1
tagged with: selenium
type: Question
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: datepicker
tagged with: python
has title: Access datepicker with python2.7 and selenium
downvote count: 0
answer count: 0

http://stackoverflow.com/comment/90096418
type: Comment
has text: @Sunitha. No Problem. It's working fine now. Thank you!
comment on: http://stackoverflow.com/a/51564433
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90202771
type: QuestionComment
has text: What Python version is this?
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51618579

http://stackoverflow.com/q/51527538
upvote count: 1
type: Question
has title: Function decorator raising positional argument error?
has answer: http://stackoverflow.com/a/51527614
downvote count: 0
answer count: 1
tagged with: decorator
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: python-decorators
accepted answer: http://stackoverflow.com/a/51527614
type: AnsweredQuestion
has body: I'm trying to write a function decorator that tests for bounds of x, y #this is my bound test function def boundtest(func): def onDecorator(self, x, y, *args, **kwargs): print(x, y, *args, **kwargs) assert x in range(self.width) and y in range(self.height) return func(x, y, *args, **kwargs) return onDecorator class Game: #these are the functions that need bound checking @boundtest def at(self, x: int, y: int) -&gt; int: return self.map[x, y] @boundtest def set(self, x: int, y: int, data): self.map[x, y] = data.value When I execute game.set(1, 1, Color.RED) I get: Traceback (most recent call last): File "C:\Users\Ben\Desktop\Projects\bubble-breaker-bot\game.py", line 61, in &lt;module&gt; game.set(1, 1, Color.RED) File "C:\Users\Ben\Desktop\Projects\bubble-breaker-bot\game.py", line 21, in onDecorator return func(x, y, *args, **kwargs) TypeError: set() missing 1 required positional argument: 'data' I need the boundtest function to check if x and y are in range of self.width, and self.height respectively while being able to pass an arbitrary amount of parameters to the function it is decorating. Why does this happen?
score: 1

http://stackoverflow.com/comment/90140654
has text: Not sure about a downvote, but pretty sure it is a dupe. Both the OP and the linked question are about adding missing dates from a range.
score: 0
comment on: http://stackoverflow.com/q/51587601
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51577346
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51577270
answers question: http://stackoverflow.com/q/51577270
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/90120910
has comment: http://stackoverflow.com/comment/90120853
has body: You have to count all divisors, before you make a conclusion, your code goes up to 8 for 24, then sums up all divisors so far and declares 24 a perfect number, not waiting for other divisors to appear. Your code should looks like this: for i in range(1,num+1): count = 0 for k in range(1,i): # no point searching for numbers greater than i if i%k == 0 : count += k if count == i: print('Perfect',i) and produce: ('Perfect', 6) ('Perfect', 28)
score: 2

http://stackoverflow.com/comment/89990061
score: 0
has text: can u please tell me how to add them?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51510616

http://stackoverflow.com/comment/90131035
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51566483
has text: thanks for your answer, it indeed works but is longer than the for loop (10.4ms vs 4.2 ms on my matrix which is quite small (832x832)).
type: AnswerComment

http://stackoverflow.com/comment/90075552
has text: try shift 4 blanks to your last 5 lines of code.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51554322
score: 2

http://stackoverflow.com/q/51502983
answer count: 1
has comment: http://stackoverflow.com/comment/89974691
tagged with: keras
accepted answer: http://stackoverflow.com/a/51503286
has comment: http://stackoverflow.com/comment/89974963
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89974898
tagged with: tensorflow
has title: Keras Error when checking input
type: Question
has comment: http://stackoverflow.com/comment/89974800
has answer: http://stackoverflow.com/a/51503286
has comment: http://stackoverflow.com/comment/89974663
score: 0
has body: I want to explore and intermediate layer on a tensorflow model defined with Keras: input_dim = 30 input_layer = Input(shape=(input_dim, )) encoder = Dense(encoding_dim, activation="tanh", activity_regularizer=regularizers.l1(10e-5))(input_layer) encoder = Dense(int(encoding_dim / 2), activation="relu")(encoder) decoder = Dense(int(encoding_dim / 2), activation='tanh')(encoder) decoder = Dense(input_dim, activation='relu')(decoder) autoencoder = Model(inputs=input_layer, outputs=decoder) ####TRAINING.... #inspect layer 1 intermediate_layer_model = Model(inputs=autoencoder.layers[0].input, outputs=autoencoder.layers[1].output) xtest = #array of dim (30,) intermediate_output = intermediate_layer_model.predict(xtest) print(intermediate_output) However I got the error on dimension when I inspect: /usr/local/lib/python2.7/site-packages/keras/engine/training_utils.pyc in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix) 134 ': expected ' + names[i] + ' to have shape ' + 135 str(shape) + ' but got array with shape ' + --&gt; 136 str(data_shape)) 137 return data 138 ValueError: Error when checking input: expected input_4 to have shape (30,) but got array with shape (1,) Any help appreciated
has comment: http://stackoverflow.com/comment/89974852

http://stackoverflow.com/q/51601670
tagged with: python
has title: Converting Java escape characters & emojis in a sentence with Python
type: AnsweredQuestion
downvote count: 0
score: 1
has body: For example, if I was given the following string: temp = "That looks great \ud83d\udc4c Good Job!" How can I convert it so that it either shows the actual emoji () or the textual meaning (OK HAND SIGN)? Final result should like: temp = "That looks great Good Job!" or temp = "That looks great :OK HAND SIGN: Good Job!" I have tried using the emoji library in Python but it appears to only support Python escape characters. Is there any way to convert Java escape characters to Python escape characters? Thanks in advance!
tagged with: emoji
type: Question
has answer: http://stackoverflow.com/a/51601905
accepted answer: http://stackoverflow.com/a/51601905
tagged with: type-conversion
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/a/51499816
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89977505
answers question: http://stackoverflow.com/q/51499765
score: 1
has body: Why not just check if the line contains the BEGIN CERTIFICATE string and then iterate until you find the END CERTIFICATE string?
downvote count: 0

http://stackoverflow.com/q/51556961
has title: How does Pandas.read_csv type casting work?
favorite count: 0
has body: Using pandas.read_csv with parse_dates option and a custom date parser, I find Pandas has a mind of its own about the data type it's reading. Sample csv: "birth_date", "name" "","Dr. Who" "1625", "Rembrandt" "1533", "Michel" The actual datecleaner is here, but what I do boils down to this: import pandas as pd def dateclean(date): return str(int(date)) # Note: we return A STRING df = pd.read_csv( 'my.csv', parse_dates=['birth_date'], date_parser=dateclean, engine='python' ) print(df.birth_date) Output: 0 NaN 1 1625.0 2 1533.0 Name: birth_date, dtype: float64 I get type float64, even when I specified str. Also, take out the first line in the CSV, the one with the empty birth_date, and I get type int. The workaround is easy: return '"{}"'.format(int(date)) Is there a better way? In data analysis, I can imagine it's useful that Pandas will say 'Hey dude, you thought you were reading strings, but in fact they're numbers'. But what's the rationale for overruling me when I tell it not to?
tagged with: pandas
has answer: http://stackoverflow.com/a/51557280
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/51557328
type: Question
type: AnsweredQuestion
score: 3
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51557328
accepted answer: http://stackoverflow.com/a/51557280

http://stackoverflow.com/comment/90002122
type: Comment
comment on: http://stackoverflow.com/a/51515920
score: 0
has text: Add these 3 to `Argument` like other dictionaries, yes?
type: AnswerComment

http://stackoverflow.com/a/51540762
has body: Based on https://pytest-ordering.readthedocs.io (alpha) plug-in you can do: import pytest @pytest.mark.order2 def test_foo(): assert True @pytest.mark.order1 def test_bar(): assert True See also a discussion at Test case execution order in pytest. My personal take on this if your tests require sequence, they are not really well isolated and some other test suit design is possible.
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90049322
answers question: http://stackoverflow.com/q/51539570
type: Answer
score: 1

http://stackoverflow.com/comment/89984343
type: QuestionComment
comment on: http://stackoverflow.com/q/51507047
has text: solve by adding wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "Singles")))
score: 0
type: Comment

http://stackoverflow.com/comment/90244974
has text: I think this maybe an [X-Y problem](https://meta.stackexchange.com/a/66378).
type: QuestionComment
comment on: http://stackoverflow.com/q/51639295
score: 0
type: Comment

http://stackoverflow.com/comment/90218949
comment on: http://stackoverflow.com/q/51626680
score: 0
type: QuestionComment
has text: line breaks after bracket completion
type: Comment

http://stackoverflow.com/q/51632310
has comment: http://stackoverflow.com/comment/90237264
has comment: http://stackoverflow.com/comment/90237490
has comment: http://stackoverflow.com/comment/90235476
type: Question
tagged with: anaconda
has title: Is it possible to set pre-existing anaconda2 as an py2 environment in anaconda3?
score: 0
has comment: http://stackoverflow.com/comment/90234576
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90237143
has body: Previously I have anaconda2 installed under ~/anaconda2. Recently I installed anaconda3 to ~/anaconda3 and replaced: export PATH="/home/xxx/anaconda2/bin:$PATH" with: export PATH="/home/xxx/anaconda3/bin:$PATH" Every time when I want to use python2 I would manually edit the .bashrc and change that line back to export PATH="/home/xxx/anaconda2/bin:$PATH" and start a new terminal session. Recently, I noted here that it is possible to switch python3 to python2 without creating a new session. However, When I run conda create --name py2 python=2.7, I get the following output: conda create --name py2 python=2.7 Solving environment: done ## Package Plan ## environment location: /home/xxx/anaconda3/envs/py2 added / updated specs: - python=2.7 The following packages will be downloaded: package | build ---------------------------|----------------- python-2.7.15 | h1571d57_0 12.1 MB ... (many lines not important) ------------------------------------------------------------ Total: 16.3 MB The following NEW packages will be INSTALLED: ca-certificates: 2018.03.07-0 .... (many lines not important) Proceed ([y]/n)? n It seems that this will initiate a new python2 installation. My question is: Is it possible to instruct conda create to use the existing ~/anaconda2 as py2 environment rather than install a new python2 environment de novo?
has comment: http://stackoverflow.com/comment/90237062
tagged with: python
has comment: http://stackoverflow.com/comment/90234450
answer count: 0

http://stackoverflow.com/comment/109208047
type: Comment
comment on: http://stackoverflow.com/a/53375405
has text: I have a big problem when installing with _conda install rpy2_ and is that it broke my R_PATH to the condo environment. then I got error like this one: `ValueError: r_home is None. Try python -m rpy2.situation` which can be solved by: `import os` and `os.environ['R_HOME'] = '/home/my_user/anaconda3/envs/my_envi/lib/R'` . Do you know how to do it globally?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90044534
comment on: http://stackoverflow.com/q/51537149
score: 0
type: Comment
type: QuestionComment
has text: Did you even read the link? You didn't provide any data. How do you expect help?

http://stackoverflow.com/comment/90125454
has text: Do you have script of your own called `numpy.py`?
score: 4
type: QuestionComment
comment on: http://stackoverflow.com/q/51579470
type: Comment

http://stackoverflow.com/q/51498464
has comment: http://stackoverflow.com/comment/89964966
has body: I am parsing HTML table with BeautifulSoup like this: for tr in table_body.find_all('tr'): for td in tr: if td.text == 'Description': description = td.find_next('td').text if td.text == 'Category': category = td.find_next('td').text if td.text == 'Department': department = td.find_next('td').text if td.text == 'Justification': justification = td.find_next('td').text print(description, category, department, justification) I refactored the multiple if statements into a function: def html_check(td, text): if td.text == text: value = td.find_next('td').text return value that is called like this: for tr in table_body.find_all('tr'): for td in tr: description= html_check(td, 'Description') category = html_check(td, 'Category') department = html_check(td, 'Department') justification = html_check(td, 'Justification') print(description, category, department, justification) My problem is that when the function html_check will not find a match, it will return None, which will be printed. This is not desirable. Is there any way to make this function return a value only when the if condition in it is met?
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/51498636
accepted answer: http://stackoverflow.com/a/51498550
has comment: http://stackoverflow.com/comment/89964887
downvote count: 0
has title: How to prevent Python function from returning None
possible better answer: http://stackoverflow.com/a/51498617
has answer: http://stackoverflow.com/a/51498617
has answer: http://stackoverflow.com/a/71948834
favorite count: 0
has comment: http://stackoverflow.com/comment/89964790
has answer: http://stackoverflow.com/a/51498795
answer count: 5
has comment: http://stackoverflow.com/comment/89964917
has answer: http://stackoverflow.com/a/51498550
tagged with: python
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/89964926

http://stackoverflow.com/q/51550602
has title: When is __init__.py in a module executed?
score: 0
linked to: http://stackoverflow.com/q/448271
has answer: http://stackoverflow.com/a/51550643
tagged with: python
tagged with: module
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90068800
has body: Based on this post: What is __init__.py for?, I know that __init__.py in a module has two functions: 1) make the directory into a package so that the module can be imported. 2) do some necessary initialization job, if any. My question is when this __init__.py is executed? Every time the module is imported into a module? Or there is something like a shared library in the memory so that this __init__.py is only executed once in the whole application? Further, I do not find good resources on how python interpreter executes python code, any suggestions on this would be appreciated.
type: Question
accepted answer: http://stackoverflow.com/a/51550643
has comment: http://stackoverflow.com/comment/90068559
answer count: 1

http://stackoverflow.com/a/51603873
has body: Another way to achieve this using regex is: import re str1 = "[Delta-1234, United-1345] Testing different airlines" str2 = "[Delta-1234] Testing different airlines" regex_pattern = r"[^[]*\[([^]]*)\]" print(re.match(regex_pattern, str1).groups()[0]) print(re.match(regex_pattern, str2).groups()[0]) It will print Delta-1234, United-1345 Delta-1234
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51603751

http://stackoverflow.com/a/51593328
has body: Idea is swap values of FROM and TO by condition: mask = df['DIRECTION'] == 'IN' df.loc[mask, ['TO', 'FROM']] = df.loc[mask, ['FROM', 'TO']].values print (df) FROM TO DIRECTION AMOUNT 0 A B IN 100 1 A B OUT 200 2 B A IN 300 3 B A OUT 40 And then aggregate sum: df = df.groupby(['FROM', 'TO'], as_index=False)['AMOUNT'].sum() print (df) FROM TO AMOUNT 0 A B 300 1 B A 340 Very similar solution if dont want modify original DataFrame: mask = df['DIRECTION'] == 'IN' df1 = df'TO','FROM'.mask(mask, df'FROM','TO'.values) #output is same like above, only changed order of columns print (df1) TO FROM 0 B A 1 B A 2 A B 3 A B df2 = df['AMOUNT'].groupby([df1['FROM'], df1['TO']]).sum().reset_index() print (df2) FROM TO AMOUNT 0 A B 300 1 B A 340
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51593268
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51593268
type: Answer

http://stackoverflow.com/a/51599525
answers question: http://stackoverflow.com/q/51599472
score: 0
has body: A list is a mutable reference so can't be hashed since it references memory. If you can convert the lists to tuples you can hash them. set((1, 2, [3, 4])) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-5-d0176c73c39f&gt; in &lt;module&gt;() ----&gt; 1 set((1, 2, [3, 4])) TypeError: unhashable type: 'list' As opposed to: set((1, 2, (3, 4))) {(3, 4), 1, 2}
type: Answer

http://stackoverflow.com/comment/90092506
type: QuestionComment
has text: wow I'm so dumb.. thanks dude..
comment on: http://stackoverflow.com/q/51561894
score: 0
type: Comment

http://stackoverflow.com/comment/90106572
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51569746
has text: I could get the attributes of the class in a list but I dont know how to access it: members = [attr for attr in dir(foo) if not callable(getattr(foo, attr)) and not attr.startswith('__')]

http://stackoverflow.com/a/51602743
has body: You can use numpy.tile: import numpy as np res = np.tile(range(10), (5, 1)) print(res) array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]) Alternatively, you can add to an array of zeros: res = np.zeros((5, 10)) + range(10)
has comment: http://stackoverflow.com/comment/90172238
upvote count: 5
has comment: http://stackoverflow.com/comment/90171584
type: Answer
answers question: http://stackoverflow.com/q/51602708
downvote count: 0
has comment: http://stackoverflow.com/comment/90172321
accepted answer of: http://stackoverflow.com/q/51602708
has comment: http://stackoverflow.com/comment/90171716
score: 5
has comment: http://stackoverflow.com/comment/90171570
has comment: http://stackoverflow.com/comment/90171676
type: AcceptedAnswer

http://stackoverflow.com/q/51577844
has title: Is Django Channel Appropriate implementing Optimistic Chat application like telegram or whatsapp?
favorite count: 0
tagged with: sockets
tagged with: python
has body: I had implemented a real-time chat application web service which gives services to the web and mobile client. I found that channel makes separate sockets for every user and bind them in groups and rooms in Redis handling where a specific socket message should be sent. So in this case, for example, the mobile platform has to save which sockets belong to which rooms and groups and in every message sending from the server, the mobile platform has to check what room this message belongs and send it on. think big like telegram and WhatsApp. it seems to me that it's not appropriate client saves multiple sockets for every user communicating with one server. Am i right?? Also in cases like WhatsApp(large scale applications) servers have sockets for every user in every room if they choose the Django channel. it makes a lot and lots of ports busy on the server. I have experience implementing socket implementation using Redis, SocketIo, Laravel to. using these tools, I was free to use few sockets for sending all kinds of notifications to users using few socket ports. it was seemed lighter than Django channel. With these kinds of thinkings, I have doubt to continue using Django channel in my project, and I am a little worried about when it deploys in large scales. Should I be worried??
downvote count: 0
answer count: 0
type: UnansweredQuestion
tagged with: django-channels
type: Question
score: 1
tagged with: chat
upvote count: 1

http://stackoverflow.com/comment/90029088
comment on: http://stackoverflow.com/a/51530047
has text: looks like it might be a problem with the server you're trying to connect to https://github.com/requests/requests/issues/4413
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89939218
score: 0
type: Comment
type: QuestionComment
has text: I should clarify the reason for the timedelta calculation. I need it because this is controlling a small thermal camera that must take measurements at given intervals between 8AM and 5PM. I could survive without the timedelta comparison but wanted to include it just in case of some lag in time and it doesn't turn the loop on.
comment on: http://stackoverflow.com/q/51484983

http://stackoverflow.com/comment/89985583
type: Comment
comment on: http://stackoverflow.com/a/51495186
type: AnswerComment
has text: Hm, I don't think I like the exec idea. I'd have to use it every time I do inheritance. I mean in other languages Builder would solve this problem, at least partially. Strange how in Python there isn't an easier way for this. But makeinit() doesn't feel very.. OOP-ish.
score: 0

http://stackoverflow.com/a/51536592
answers question: http://stackoverflow.com/q/51534586
type: Answer
upvote count: 7
accepted answer of: http://stackoverflow.com/q/51534586
score: 7
has body: Try this: from nltk.corpus import stopwords stop_words = set(stopwords.words('french')) #add words that aren't in the NLTK stopwords list new_stopwords = ['cette', 'les', 'cet'] new_stopwords_list = stop_words.union(new_stopwords) #remove words that are in NLTK stopwords list not_stopwords = {'n', 'pas', 'ne'} final_stop_words = set([word for word in new_stopwords_list if word not in not_stopwords]) print(final_stop_words)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51590045
type: AnsweredQuestion
tagged with: html-parsing
type: Question
has answer: http://stackoverflow.com/a/51590144
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51590144
tagged with: beautifulsoup
tagged with: python-3.x
linked to: http://stackoverflow.com/q/51592631
tagged with: python
has title: KeyError 0 on tag
has body: I'm trying to parse HTML site, but I have KeyError. Here is the code: from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = "http://www.kontrakt.szczecin.pl/mieszkanie-sprzedaz-6664m2-339600pln-potulicka-nowe-miasto-szczecin-zachodniopomorskie,351165" #PL: otwiera połączenie z wybraną stroną, pobieranie zawartości strony (urllib) #EN: Opens a connection and grabs url uClient = uReq(my_url) page_html = uClient.read() uClient.close() #html parsing (BeautifulSoup) page_soup = soup(page_html, "html.parser") #html.parser -&gt; zapisujemy do html, nie np. do xml #PL: zbiera tabelkę z numerami ofert, kuchnią i innymi danymi o nieruchomości z tabelki #EN: grabs the data about real estate like kitchen, offer no, etc. containers = page_soup.findAll("section",{"class":"clearfix"},{"id":"quick-summary"}) # print(len(containers)) - len(containers) sprawdza ile takich obiektów istnieje na stronie #PL: Co prawda na stronie jest tylko jedna taka tabelka, ale dla dobra nauki zrobię tak jak gdyby tabelek było wiele. #EN: There is only one table, but for the sake of knowledge I do the container variable container = containers[0] print(len(container.dl)) print(container.dl[0]) And this is the log with an error, that shows. runfile('/home/bartosz/Pulpit/web_scrap.py', wdir='/home/bartosz/Pulpit') 36 Traceback (most recent call last): File "&lt;ipython-input-70-e826e21c585a&gt;", line 1, in &lt;module&gt; runfile('/home/bartosz/Pulpit/web_scrap.py', wdir='/home/bartosz/Pulpit') File "/home/bartosz/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/home/bartosz/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/home/bartosz/Pulpit/web_scrap.py", line 30, in &lt;module&gt; print(container.dl[0]) File "/home/bartosz/anaconda3/lib/python3.6/site-packages/bs4/element.py", …

http://stackoverflow.com/q/51611362
has comment: http://stackoverflow.com/comment/90189095
has comment: http://stackoverflow.com/comment/90187366
has comment: http://stackoverflow.com/comment/90188690
has comment: http://stackoverflow.com/comment/90188784
tagged with: python
tagged with: bottle
tagged with: php
accepted answer: http://stackoverflow.com/a/51636351
has comment: http://stackoverflow.com/comment/90188879
has title: Echo statement is echoing non-text
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90188082
tagged with: echo
type: Question
has comment: http://stackoverflow.com/comment/90188542
has answer: http://stackoverflow.com/a/51636351
score: 0
has comment: http://stackoverflow.com/comment/90237082
has comment: http://stackoverflow.com/comment/90217671
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/90209179
answer count: 1
has comment: http://stackoverflow.com/comment/90189142
has body: I am running a simple bottle server that I set up on python: from bottle import route, run, static_file @route('/') def home(): return static_file("home.html", root='.') @route("/<fileName>") def respond(fileName): return static_file("%s" % fileName, root='.') run(host="localhost", port=8080, reloader=True) When I run this code, it works perfectly and I can add any filename to the localhost url(http://localhost:8080) and the code will return the file specified if it is there. So I can type "https://localhost:8080/home.html" and it will return my home.html file that displays: Welcome to my home page! test page Welcome to my home page! However, whenever I try to embed a PHP echo statement, it always adds on what is after the text, for example: PHP test page <?php echo " Welcome! "; ?> Returns: Welcome!"; ?> This also happens when I try to use a pure PHP file with the php extension: <?php echo " Welcome! "; ?> Is there something I need to add to my server code or is there something wrong with my PHP installation? (I know that the PHP code is right)
has comment: http://stackoverflow.com/comment/90187833

http://stackoverflow.com/q/51520714
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90017751
has comment: http://stackoverflow.com/comment/90019027
answer count: 0
score: 1
type: Question
has body: I am trying to assign a group ID to my table. For each group in "part" column, acording to order in "ord" column, the 1st elements I encounter in "id" column will receive a new_id 0, then each time I encounter a different ID, i increase the "new_id". Currently, I need to use 2 window functions and the process is therefore quite slow. df = sqlContext.createDataFrame( [ (1,1,'X'), (1,2,'X'), (1,3,'X'), (1,4,'Y'), (1,5,'Y'), (1,6,'Y'), (1,7,'X'), (1,8,'X'), (2,1,'X'), (2,2,'X'), (2,3,'X'), (2,4,'Y'), (2,5,'Y'), (2,6,'Y'), (2,7,'X'), (2,8,'X'), ], ["part", "ord", "id"] ) df.withColumn( "new_id", F.lag(F.col("id")).over(Window.partitionBy("part").orderBy("ord"))!=F.col('id') ).withColumn( "new_id", F.sum( F.col("new_id").cast('int') ).over(Window.partitionBy("part").orderBy("ord")) ).na.fill(0).show() +----+---+---+------+ |part|ord| id|new_id| +----+---+---+------+ | 2| 1| X| 0| | 2| 2| X| 0| | 2| 3| X| 0| | 2| 4| Y| 1| | 2| 5| Y| 1| | 2| 6| Y| 1| | 2| 7| X| 2| | 2| 8| X| 2| | 1| 1| X| 0| | 1| 2| X| 0| | 1| 3| X| 0| | 1| 4| Y| 1| | 1| 5| Y| 1| | 1| 6| Y| 1| | 1| 7| X| 2| | 1| 8| X| 2| +----+---+---+------+ Can I achieve the same using only one window function ?
downvote count: 0
tagged with: pyspark
has title: Generate a group ID with only one Window function
tagged with: apache-spark
tagged with: sql
favorite count: 0
type: UnansweredQuestion

macos
tags question: http://stackoverflow.com/q/51570306
tags question: http://stackoverflow.com/q/51638773
tags question: http://stackoverflow.com/q/51520359
tags question: http://stackoverflow.com/q/51567190
tags question: http://stackoverflow.com/q/51525487
tags question: http://stackoverflow.com/q/51485570
tags question: http://stackoverflow.com/q/51601335
tags question: http://stackoverflow.com/q/51598745
tags question: http://stackoverflow.com/q/51604543
tags question: http://stackoverflow.com/q/51538665
tags question: http://stackoverflow.com/q/51555834
type: Tag
tags question: http://stackoverflow.com/q/51603459
tags question: http://stackoverflow.com/q/51559628
tag name: macos
tags question: http://stackoverflow.com/q/51604181
tags question: http://stackoverflow.com/q/51568743
tags question: http://stackoverflow.com/q/51524934

http://stackoverflow.com/q/51510373
has answer: http://stackoverflow.com/a/51514862
accepted answer: http://stackoverflow.com/a/51514862
type: Question
possible better answer: http://stackoverflow.com/a/59901923
upvote count: 2
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/89990115
favorite count: 0
has title: How to carry out uploading multiple files in Django with CreateView?
has body: Please help me. I am new to Django, cannot undertsand the following thing - I have subclass of CreateView for creating a comment. I want to create a project where people can leave their comments and attach files (images) to this comment. One should have possibility to attach as many images as he wants to ONE form with text comment. I have found in Internet a decision that I need to use 2 models - 1 model for text comment + 1 separate model for images. Is it so? Comment (text) form is created and handled in my views.py by sublass of CreateView. How to connect new separate model for images with my CreateView ? models.py class Descriptions(models.Model): … city = models.ForeignKey(Cities, on_delete=models.CASCADE) description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.DO_NOTHING) … class Description_Photos(models.Model): image = models.ImageField(upload_to='images/', blank=True) description = models.ForeignKey(Descriptions, on_delete=models.CASCADE, related_name='photos') forms.py class DescriptionsForm(forms.ModelForm): class Meta: model = Descriptions exclude = [] widgets = {'description': forms.Textarea(attrs={'cols':90})} class Photos_form(forms.Form): photos = forms.FileField(widget=forms.FileInput(attrs={'multiple': True})) views.py class DescriptionCreate(CreateView): model = Descriptions form_class = DescriptionsForm template_name = 'countries/new_description.html' def get_success_url(self): return reverse('countries:descr', args=[self.kwargs['country_id'], self.kwargs['city_id']]) def get_context_data(self, **kwargs): self.city = get_object_or_404(Cities, id=self.kwargs['city_id']) kwargs['city'] = self.city return super().get_context_data(**kwargs) def form_valid(self, form): form.instance.city = get_object_or_404(Cities, id=self.kwargs['city_id']) form.instance.owner = self.request.user messages.success(self.request, 'Your post has been added, thank you') return super().form_vali…
has answer: http://stackoverflow.com/a/59901923
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89992583
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89992625

http://stackoverflow.com/q/51557693
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90082120
has comment: http://stackoverflow.com/comment/90083133
has title: Python creating a regex from a list and its variations
has comment: http://stackoverflow.com/comment/90082533
tagged with: difflib
has comment: http://stackoverflow.com/comment/90082470
favorite count: 0
has answer: http://stackoverflow.com/a/51679646
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90082252
tagged with: list
score: 1
has comment: http://stackoverflow.com/comment/90082348
type: Question
has body: I have a list of months in Latin: latinMonths = ['januarii', 'februarii','martii', 'aprilis', 'maii', 'junii', 'julii', 'augusti', 'septembris', 'octobris', 'novembris', 'decembris'] which unfortunately in my text I find variations of them spelled differently ex: 'januarij' or 'septembrjs' etc... I am trying to scan the text to find the exact word as the the list or variations of it. I know I can use difflib and found that I can check a sentence with a list of words in this post: Python: how to determine if a list of words exist in a string. Is there a way I can combine both, thus finding an instance in a string where the months in the list or variations of it exist? ex: If I have the text "primo januarij 1487" I would like to return true as januarij is a close match to january while if I have 'I love tomatoes' neither of the words are a close match or exact match to the words in the list
linked to: http://stackoverflow.com/q/21718345

http://stackoverflow.com/q/51577437
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/51577479
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51577479
tagged with: python
has body: I have an hour and one minute worth of data which we resample in 5 minute bins: (In production we have no control over the dataframe received. This produces a sample.) import numpy as np import pandas as pd rng = pd.date_range('7/29/2018 17:00', periods=61, freq='min') ts = pd.DataFrame(np.ones(len(rng)), index=rng) five_min_bins = ts.resample('5min').sum() This (correctly) gives a bin starting at 18:00: five_min_bins[-3:] Out[]: 0 2018-07-29 17:50:00 5.0 2018-07-29 17:55:00 5.0 2018-07-29 18:00:00 1.0 What is a good way to nudge the last data point into the previous bin? The best I came up with so far looks hacky: # hack, this question is how to improve this piece of code. import datetime ts = ts.reset_index(drop=False) ts['index'].iloc[-1] = ts['index'].iloc[-1] - datetime.timedelta(milliseconds=1) ts = ts.set_index('index') It works. But does anyone knows of a more elegant solution? ts[-1:] Out[]: level_0 0 index 2018-07-29 17:59:59.999 60 1.0 ts.resample('5min').sum()[-3:] Out[]: level_0 0 index 2018-07-29 17:45:00 235 5.0 2018-07-29 17:50:00 260 5.0 2018-07-29 17:55:00 345 6.0
score: 2
type: AnsweredQuestion
downvote count: 0
has title: How to update a datetime index value of a pandas dataframe?

redis
tags question: http://stackoverflow.com/q/51539056
tags question: http://stackoverflow.com/q/51570206
tags question: http://stackoverflow.com/q/51606105
tags question: http://stackoverflow.com/q/51519333
tags question: http://stackoverflow.com/q/51553688
tags question: http://stackoverflow.com/q/51536577
type: Tag
tags question: http://stackoverflow.com/q/51573566
tag name: redis

http://stackoverflow.com/q/51608043
has answer: http://stackoverflow.com/a/51608077
tagged with: with-statement
type: Question
has title: Reading from several .csv files simultaneously
score: 0
answer count: 2
tagged with: for-loop
linked to: http://stackoverflow.com/q/11295171
has answer: http://stackoverflow.com/a/51608102
duplicate of: http://stackoverflow.com/q/11295171
has body: I am trying to read values through a loop from two different .csv files. I am being able to run the program perfectly when opening one .csv file; however, when I import the second .csv file, I get an error stated below: Traceback (most recent call last): File "C:\Users\crteeic\Desktop\Project\Full Program (Testing).py", line 210, in with open('MagnaDC Set Points.csv', 'r') and ('Amatek Set Points.csv', 'r') as csvfile: AttributeError: enter The aim of the program is to read values from two .csv files and send these values to two different power supplies. Please find the code below: with open('MagnaDC Set Points.csv', 'r') and ('Amatek Set Points.csv', 'r') as csvfile: dataset = csv.reader(csvfile, delimiter=',') next(dataset) rows = list(dataset) inputSamplesm = np.empty([len(rows), 2], dtype=float) outputSamplesm = np.empty([1,3], dtype=float) inputSamplesa = np.empty([len(rows), 2], dtype=float) outputSamplesa = np.empty([1,3], dtype=float) testStartTime = time.time() for idx, data in enumerate(rows): inputSamplesm[idx] = [data[0], data[1]] inputSamplesa[idx] = [data[0], data[1]] s.sendall('VOLT {0}\n'.format(data[0]).encode('utf-8')) conn.write('VOLT {0}\n'.format(data[0]).encode('utf-8')) stopTime = testStartTime + int(data[1]) Please advice. Thank you.
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/51635061
has comment: http://stackoverflow.com/comment/90260063
upvote count: 1
type: Answer
has body: Like Ben said, it would be great to see a sample from the JSON file, but the issue could be with how your trying to split your abstract data. With what you're doing now, you're asking it to split at every space. Try something like this if you're wanting to split by line: if 'abstract' in data: csvwriter.writerow(data['abstract'].split(","))
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51634824

http://stackoverflow.com/q/51602211
has answer: http://stackoverflow.com/a/51602638
accepted answer: http://stackoverflow.com/a/51602638
has body: I have a pandas dataframe that, at every iteration of a loop, I need to find a specific row in based on a condition unique to each iteration. I do this by doing: condition = ((all_together["Chr"] == chrom) &amp; (all_together["Start"] &lt;= true_center) &amp; (all_together["End"] &gt;= true_center)) this_bin = all_together[condition] Where all_together is the name of my dataframe, and chrom and true_center are parameters unique to each loop iteration. Based on %prun and %lprun profiling, the vast majority of time spent is in the "Start" and "End" parts of the condition. I optimized the "Chr" lookup by converting to a categorical datatype, but for "Start" and "End" columns the value in the dataframe is a number that needs to be compared to true_center, another number. Does anyone have any ideas on how to speed this up? The data is effectively "sorted" numerically but I can't find a good way to use that to y advantage here. Any other approaches are welcome too, thanks for any help!
tagged with: indexing
type: AnsweredQuestion
tagged with: dataframe
has title: Optimizing Pandas DataFrame Filtering
type: Question
tagged with: numpy
score: 0
tagged with: pandas
answer count: 1
tagged with: python

http://stackoverflow.com/comment/90077894
type: QuestionComment
has text: Ok, interesting development. I was wrong again: `len(training_label_data[0]` is only 4, and so smaller than `len(training_label_data)`. Therefore, the batch size is different in the two implementations; it is much smaller with the Keras implementation. When I changed the TensorFlow implementation to have a batch size of 4, the training curve was more similar to that of the Keras implementation, and it was actually able to reduce the loss. So it seems that a smaller batch size here allows the optimisation to avoid a local minimum, perhaps because the gradients are more stochastic....?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51546176

http://stackoverflow.com/q/51625869
type: Question
downvote count: 2
answer count: 1
has title: when i am using sqlite3 with tkinter i am getting Error in create password column
has comment: http://stackoverflow.com/comment/90216373
tagged with: sqlite
has comment: http://stackoverflow.com/comment/90219086
favorite count: 0
upvote count: 0
tagged with: tkinter
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51625956
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/90230881
has body: In my project, I am creating a Login and Registration form using Tkinter and Sqlite3 I am getting Error in Query . def database(): name1 = Fullname.get() email = Email.get() passData = Password.get() gender = var.get() country = c.get() prog = var1.get() conn = sqlite3.connect('Form.db') with conn: cursor = conn.cursor() cursor.execute( 'CREATE TABLE IF NOT EXISTS Student (Fullname TEXT,Email TEXT,Password TEXT ,Gender TEXT,country TEXT,Programming TEXT)') cursor.execute('INSERT INTO Student (FullName,Email,Password,Gender,country,Programming ) VALUES(?,?,?,?,?,?)', (name1, email, passData, gender, country, prog)) conn.commit() Error Message: File "C:/Users/JMD1/PycharmProjects/BugFreeRam/registrationFor.py", line 44, in database (name1, email, passData, gender, country, prog)) sqlite3.OperationalError: table Student has no column named Password

http://stackoverflow.com/comment/90176490
score: 1
comment on: http://stackoverflow.com/q/51605561
type: Comment
type: QuestionComment
has text: What does "top 10 choice" mean? What have you tried ?

http://stackoverflow.com/a/51625696
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51625686
type: Answer
upvote count: 3
has body: This first column is called index. For avoid write it to file use index=False: df.to_csv('toy_data.csv', index=False) df1 = pd.read_csv('toy_data.csv') Or use index_col parameter in read_csv: df.to_csv('toy_data.csv') df1 = pd.read_csv('toy_data.csv', index_col=[0])
score: 3
answers question: http://stackoverflow.com/q/51625686
type: AcceptedAnswer

http://stackoverflow.com/comment/117491117
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/62584802
has text: I tried the same way, I initialized it after import. It returns Not Founds 404. Please check [this link](https://stackoverflow.com/q/66445198/8340027).

http://stackoverflow.com/comment/90221994
comment on: http://stackoverflow.com/q/51618410
has text: Still the same error
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89977470
comment on: http://stackoverflow.com/q/51502987
score: 0
type: QuestionComment
type: Comment
has text: I suggested the time because your lack of progress suggests that you need tutelage on several language facilities and perhaps looping applications. From what you've written so far, it appears that a straightforward loop, plus the `any` and/or `replace` functions will cover what you need.

http://stackoverflow.com/comment/90001816
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51516510
has text: yes it does but also should be fetched in the photoedit view. add this line to your photoedit. image = Images.objects.filter(file__startswith=ZSN)

http://stackoverflow.com/comment/90262673
comment on: http://stackoverflow.com/q/51630229
type: Comment
type: QuestionComment
has text: @RhythemAggarwal, after a minute of delay below is an extract of the output: `[ec2-user@ip-XXXXXXXX ~]$ python nofilters-latest-ami.py us-west-2` `{u'Images': [{u'VirtualizationType': 'paravirtual', u'Hypervisor': 'xen', u'ImageOwnerAlias': 'amazon', u'ImageId': 'aki-30fd7000', u'State': 'available', u'BlockDeviceMappings': [], u'Architecture': 'i386', u'ImageLocation': 'ec2-pub`
score: 0

http://stackoverflow.com/q/51484153
upvote count: 1
has body: I've created a Flask app, throughout which I create loggers in each module with the line LOGGER = logging.getLogger(__name__). In the app's main module is if __name__ == '__main__': app.run(host='0.0.0.0', port=9876) # subprocess.call(['gunicorn', 'main:app', '-w', '5', '-b', '0.0.0.0:9876']) The two lines under the if are alternatively commented and uncommented whether I choose to run through gunicorn or not. When not running through gunicorn, a request to an endpoint will result in logs being printed. For example: 07-23 10:38 - INFO - 127.0.0.1 - - [23/Jul/2018 10:38:49] "POST /path/to-endpoint HTTP/1.1" 200 - But when run through gunicorn, no such logs are printed (though the expected results of the request are returned. This question is similar to the one posed here, but the scenario is different enough that the proposed fix does not help. Any ideas?
type: Question
tagged with: flask
has title: Flask logs not printing when app is run through gunicorn
answer count: 1
downvote count: 0
favorite count: 0
tagged with: gunicorn
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/26578733
tagged with: python
tagged with: logging
has answer: http://stackoverflow.com/a/51484400
score: 1

http://stackoverflow.com/a/51585789
upvote count: 8
has comment: http://stackoverflow.com/comment/90137113
has body: Using describe: df.groupby(['c1', 'c2']).describe().stack(level=0)'25%', '50%', '75%', 'mean'
type: AcceptedAnswer
score: 8
type: Answer
answers question: http://stackoverflow.com/q/51585660
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51585660

http://stackoverflow.com/a/56271625
answers question: http://stackoverflow.com/q/51566762
has body: In my case it was due to new OpenSSL version vs. old node.js installed on the server. I found the solution here: Run the following command to fix the key: openssl rsa -in key.txt -out key.txt Where key.txt is the private key file.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51566762

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/51636383

http://stackoverflow.com/a/51624098
has body: It was fixed by creating a .htaccess file with the following rules in the cgi-bin folder: Options +ExecCGI AddHandler cgi-script .py
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51620390
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51620390

http://stackoverflow.com/comment/89977434
type: QuestionComment
comment on: http://stackoverflow.com/q/51503845
has text: I thought that there may be possible solution for it.
score: 0
type: Comment

http://stackoverflow.com/a/51549405
has body: You can do df.replace('',np.nan).apply(lambda x: sorted(x, key=pd.isnull), 1).fillna('') Out[538]: A B C 0 Foo X 1 Bar Y 2 Foo X 3 Bar Y
score: 1
has comment: http://stackoverflow.com/comment/90066635
answers question: http://stackoverflow.com/q/51549281
has comment: http://stackoverflow.com/comment/90066619
has comment: http://stackoverflow.com/comment/90066371
has comment: http://stackoverflow.com/comment/90066676
downvote count: 0
has comment: http://stackoverflow.com/comment/90066514
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90028872
type: QuestionComment
has text: You could use shell wildcards: `python myscript.py tx0[0-5].data`
comment on: http://stackoverflow.com/q/51530358
score: 1
type: Comment

http://stackoverflow.com/q/51639481
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51642547
type: Question
has answer: http://stackoverflow.com/a/51641581
accepted answer: http://stackoverflow.com/a/51641581
score: 0
answer count: 2
has title: Specify colors above and below median on violin plot in Seaborn / Matplotlib
tagged with: seaborn
has body: I am generating violin plots and would like to display a line at the median of the distribution, with different colors for the areas above and below the median. Here is a MVCE: import numpy as np import matplotlib.pyplot as plt import seaborn np.random.seed(1) d1 = np.random.normal(size=5000) d2 = np.random.normal(scale=0.5, size=5000) x = d1 + d2 plt.figure(figsize=(5, 5)) seaborn.violinplot(y=x) Here is the resulting plot: and the output I'd like to create: I've searched for a while now and cannot seem to find any documentation or examples for doing this. Can it be done in matplotlib or seaborn (or any other plotting library in Python)?
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51642547

odoo-10
tags question: http://stackoverflow.com/q/51580882
tags question: http://stackoverflow.com/q/51630239
tags question: http://stackoverflow.com/q/51605392
tag name: odoo-10
tags question: http://stackoverflow.com/q/51613748
tags question: http://stackoverflow.com/q/51633376
type: Tag
tags question: http://stackoverflow.com/q/51626461
tags question: http://stackoverflow.com/q/51564243
tags question: http://stackoverflow.com/q/51535808

http://stackoverflow.com/q/51525237
has comment: http://stackoverflow.com/comment/90020389
downvote count: 0
has title: How to set up HTTPHandler for python logging
tagged with: httphandler
has answer: http://stackoverflow.com/a/64360700
has answer: http://stackoverflow.com/a/51528564
answer count: 3
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
score: 16
tagged with: python
tagged with: python-requests
upvote count: 16
tagged with: logging
has comment: http://stackoverflow.com/comment/90020791
has body: I'm trying to use HTTPHandler class of standard python logging library to send logs. I need to make a https post request with basic credentials(username and password). This is how i'm setting up the HTTPHandler- host = 'example.com' url = '/path' handler = logging.handlers.HTTPHandler(host, url, method='POST', secure=True, credentials=('username','password'), context=None) logger.addHandler(handler) But the problem is, I'm not getting anylogs in my remote server.I'm not even seeing any exception from the handler. Am I setting up the handler arguments incorrectly? I can send similar logs using simple pythong http request- url = 'https://username:password@example.com/path' headers = {'content-type': 'application/json'} jsonLog = { 'id': '4444','level': 'info', 'message': 'python log' }; r = requests.post(url, data = json.dumps(jsonLog), headers=headers) Do i need to setup header somehow because of json content-type? If yes than how do i set that up in the httphandler? Update I thought I should update what I ended up doing. After numerous search i found i can create a custom handler by overriding emit() of logging.Handler. class CustomHandler(logging.Handler): def emit(self, record): log_entry = self.format(record) # some code.... url = 'url' # some code.... return requests.post(url, log_entry, headers={"Content-type": "application/json"}).content Feel free to post if any has any better suggestions.
has answer: http://stackoverflow.com/a/72714858
type: Question

http://stackoverflow.com/a/51629186
has comment: http://stackoverflow.com/comment/122714796
type: Answer
score: 35
has comment: http://stackoverflow.com/comment/122735777
has body: type annotations sometimes need to be set before the object has been created, for example: class Node: def next() -&gt; Node: pass This piece of code actually fails, because Node is referenced as an annotation of Node.next while the class Node is still being created. This is the same reason why the following fails: class T: t = T() To get around this, you can use a string instead class Node: def next() -&gt; 'Node': pass so the typechecker will only evaluate Node later (a forward reference). This was actually decided to be a design flaw so in python 3.7 you can use from __future__ import annotations and the first example will work. Edit April 2022 So a lot has changed (and yet a lot hasn't) since this was made. The most important difference is that string annotations was deferred from py 3.10 and it sounds like it will never be stabilized. Instead the steering committee will probably end up stabilizing PEP 649 instead which has slightly more complex behavior, but still supports self-referential type hints. See the PEP for details.
answers question: http://stackoverflow.com/q/51629105
upvote count: 35
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51629105

http://stackoverflow.com/comment/90041442
comment on: http://stackoverflow.com/a/51536354
has text: Thank you, but the solution should fit a single line of code like my try above without any python code
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/113461003
has text: One small extra question: I tried your approach from github.com/realead/commonso/blob/master/setup.py , and while it works perfectly in Linux (Ubuntu), it fails for Windows, complaining that it cannot find the `*.lib` file. Indeed, when compiling the shared `dll` library in windows, I only get a `dll` file, and not a `lib` file. You won't happen to know how to generate both the `dll` and the `lib` files, do you?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51635113

http://stackoverflow.com/q/51527566
has comment: http://stackoverflow.com/comment/90023811
type: Question
score: 0
tagged with: for-loop
has body: I'm going through each url page, and want to have all of the titles of all of the links from each page in their own respective cell in my content list. However, I believe I'm missing something obvious but I'm quite a novice. I know at the moment that every iteration creates a new cell in my list, so I'm trying to prevent that. for url in url_list: open_page = driver.get(url) html_source = driver.page_source soup = BeautifulSoup(html_source, 'html.parser') links = soup.find('div', {'class': 'body'}) content = [] for link in links.find_all('a'): temp = link.get_text() content.append(temp) print(content)
has title: How to for loop strings into a single element to a list
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90023866
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90023814
tagged with: list
answer count: 0

http://stackoverflow.com/q/51540467
has answer: http://stackoverflow.com/a/52198861
tagged with: bash
answer count: 3
tagged with: kubectl
has body: I have generated a python script that opens a deployment config_file.yaml, modifies some parameters and saves it again, using pyyaml. This python script will be executed in the master node of a Kubernetes cluster. Once is generated the new file, my intention is to execute kubectl apply -f config_file.yaml in the python script to apply the modifications to the deployment. I have been reading how to do it using kubernetes python client, but it seems it is not prepare to execute kubectl apply. So the other option is to create a bash script and execute it from python script. Bash scripts: #!/bin/bash sudo kubectl apply -f config_file.yaml I give it permissions chmod +x shell_scipt.sh Python script: import subprocess subprocess.call(['./shell_script.sh']) But an error appears: File "/usr/lib/python2.7/subprocess.py", line 1047, in _execute_child raise child_exception OSError: [Errno 13] Permission denied I don't know how to resolve this error, I have tested givin permissions to the bash script, but nothing worked.
has comment: http://stackoverflow.com/comment/90052583
favorite count: 0
type: UnansweredQuestion
tagged with: kubernetes
tagged with: python
has title: Python scripts executes Kubernetes command: kubectl apply -f config_file.yaml
upvote count: 2
has answer: http://stackoverflow.com/a/64126579
score: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52198631

http://stackoverflow.com/q/51520143
downvote count: 0
has comment: http://stackoverflow.com/comment/90011244
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90014385
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/12015427
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51533483
has body: I've got a loop that's processing images and I want, on every 100th iteration (say) to display the image in a single output window using matplotlib. So I'm trying to write a function which will take a numpy tensor as input and display the corresponding image. Here's what I have which isn't working: def display(image): global im # If im has been initialized, update it with the current image; otherwise initialize im and update with current image. try: im im.set_array(image) plt.draw() except NameError: im = plt.imshow(image, cmap=plt.get_cmap('gray'), vmin=0, vmax=255) plt.show(block=False) plt.draw() I was trying to pass it through FuncAnimation at first, but that seems designed to have the animation call a function to do the update, rather than having a function call on matplotlib to display the result. The code above opens a window but it doesn't seem to update. Can anyone point me in the right direction here? Many thanks, Justin
answer count: 1
has title: Update matplotlib image in a function
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90025775
accepted answer: http://stackoverflow.com/a/51533483
score: 2

http://stackoverflow.com/a/51549007
score: 1
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51548950
has body: Pretty straightforward from collections import defaultdict d = defaultdict(list) # initialize a dict with values as lists with open('Kennedy.txt') as fin: for idx, line in enumerate(fin): # for index, line in file words = line.lower().split() # make it case insensitive for word in words: # for word in list of lower-case words d[word].append(idx) # append the value to the list

http://stackoverflow.com/q/51541452
has comment: http://stackoverflow.com/comment/90050600
has answer: http://stackoverflow.com/a/51543231
score: 0
has body: I have Multiple CSV files like below CSV1 and CSV2 and need to combine both csv into email body using python CSV1 :- S.No Name Student 1 Rishabh Engg 2 Samee Engg CSV1 :- S.No Name Student 1 Ankit Med 2 Arjun Engg =====Expected output i need is like below :-=========== Dear Rishabh , PFB the Data :- CSV1 :- S.No Name Student 1 Rishabh Engg 2 Samee Engg CSV1 :- S.No Name Student 1 Ankit Med 2 Arjun Engg Regards, Rishabh Jaiswal ========================= FYI , I have tried and sucessfully help to do single csv into email body with below code :- with open('input.csv') as input_file: reader = csv.reader(input_file) data = list(reader) text = text.format(table=tabulate(data, headers="firstrow", tablefmt="grid")) html = html.format(table=tabulate(data, headers="firstrow", tablefmt="html")) message = MIMEMultipart( "alternative", None, [MIMEText(text), MIMEText(html,'html')]) message['Subject'] = "Your data" message['From'] = me message['To'] = you server = smtplib.SMTP(server) server.ehlo() server.starttls() server.login(me, password) server.sendmail(me, you, message.as_string()) server.quit()
answer count: 1
tagged with: email
tagged with: python
has comment: http://stackoverflow.com/comment/90054007
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90050936
type: Question
has title: Combile multiple CSV Contents into email body with python

http://stackoverflow.com/q/51625016
score: 3
answer count: 1
downvote count: 0
has body: I use Fortran to create a binary file which contains multiple lines: Program write_binary implicit none integer i real x open(10,file="test.dat",form="unformatted") do i=1,10 write(10),i*1.0,i*2.0 end do close(10) end Then I use Python, trying to read the whole file. However, the FortranFile package can only read line by line (see code below). Is there any way that I can read all lines of the binary files created by Fortran? Great thanks. from scipy.io import FortranFile import numpy as np f=FortranFile('test.dat','r') x=read_reals(dtype='f4') print(x)
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51626380
accepted answer: http://stackoverflow.com/a/51626380
type: AnsweredQuestion
upvote count: 3
tagged with: fortran
tagged with: scipy
has title: How to use Python to read the whole binary file created by Fortran
type: Question
has comment: http://stackoverflow.com/comment/90214950

http://stackoverflow.com/comment/90174255
has text: The issue is that the regex wouldn't work if the string becomes `[Delta-1234, United-1345, Spirit-8778] Testing different airlines`. My point being, the airlines and their code can vary and can be more than 1.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51603792
type: Comment

http://stackoverflow.com/comment/90395581
type: AnswerComment
has text: oh yeah i saw the misspell and now it working all fine
type: Comment
comment on: http://stackoverflow.com/a/51646657
score: 0

http://stackoverflow.com/q/51545992
score: 2
has body: I have main raw data of securities, out of which I need to create multiple portfolios of securities based on certain filtering criterias. I am used to working in C++, not very clear on how the below can be implemented in python. I tried to make different dataframes using nested for-loops: i - used to loop through years from 2007 to 2017 (column yr in raw data) j - used to loop through regions from 1 to 4 (column Region in raw data) for i in range (2007, 2018): for j in range (1,5): dfij_filter = (df['yr'] == i) &amp; (df['Region'] == j) dfij = dfij[dfij_filter] dfij = dfij.join(dfco.groupby('ISSUER_NAME')['E_SCORE'].mean(), on = 'ISSUER_NAME', rsuffix = '_ry') dfij = dfij.join(dfco.groupby('ISSUER_NAME')['P_SCORE'].mean(), on = 'ISSUER_NAME', rsuffix = '_ry') dfij = dfij.join(dfco.groupby('ISSUER_NAME')['Q_SCORE'].mean(), on = 'ISSUER_NAME', rsuffix = '_ry') dfij = dfij.drop_duplicates(subset['ISSUER_NAME'], keep=False) dfij_E = dfij.sort_values('E_SCORE_ry', ascending = False) dfij_ETOP = dfij_E.iloc[:50, :] dfij_P = dfij.sort_values('P_SCORE_ry', ascending = False) dfij_PTOP = dfij_P.iloc[:50, :] dfij_Q = dfij.sort_values('E_SCORE_ry', ascending = False) dfij_QTOP = dfij_Q.iloc[:50, :] I need to create different dataframes and then apply few functions on those dataframes: Essentially the flow is: Step 1: Yr filter --> Step 2: Region filter --> Step 3: Calc an average E score value, avg P score value, avg Q score value for that yr and region --> (E, P, Q are different columns) Step 4: Arrange the securities in descending order of average E score --> Step 5: Pick top 50 securities and put them in a dataframe Repeat Step 4 and 5 for P and Q scores as well. Essentially creating 10*4*3 dataframes. These dataframes can then be used for backtesting purposes Any help would be greatly appreciated. Thanks
has answer: http://stackoverflow.com/a/51546143
has title: Need to create multiple dataframes in nested for loops based on certain filters
type: Question
has comment: http://stackoverflow.com/comment/90061609
tagged with: dataframe
upvote count: 2
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51550018
downvote count: 0
tagged with: nested
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90060925
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89961375
type: Comment
type: QuestionComment
has text: https://docs.python.org/3/library/string.html#module-string
comment on: http://stackoverflow.com/q/51496696
score: 0

http://stackoverflow.com/comment/90076365
type: Comment
has text: i'm not quite sure but i think passing a function two lists is different than passing it one list of lists
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51553921

http://stackoverflow.com/comment/90223544
type: Comment
has text: Hi, tnx for you reply, Actually if you check load is a method of dataset, using that to load the data from excel to dataset object . After that will loop with dataset object(variable) to get each line of data
score: 0
comment on: http://stackoverflow.com/q/51629540
type: QuestionComment

http://stackoverflow.com/comment/90131521
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51583060
has text: You appear to be using code designed for an older version of the library. The `create_rows()` method was [deprecated in version 0.29](https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/changelog.html#id26).

http://stackoverflow.com/q/51584192
has answer: http://stackoverflow.com/a/74281590
has title: add row to a csv file with python
has comment: http://stackoverflow.com/comment/90133774
answer count: 2
accepted answer: http://stackoverflow.com/a/51584256
has comment: http://stackoverflow.com/comment/90133760
has comment: http://stackoverflow.com/comment/90133970
has comment: http://stackoverflow.com/comment/90133786
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/90133816
has comment: http://stackoverflow.com/comment/90133775
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90133788
score: 0
has answer: http://stackoverflow.com/a/51584256
tagged with: file
possible better answer: http://stackoverflow.com/a/74281590
type: Question
has body: I have two csv files that each have 2 columns, one of them being the date. I want to add the second column of the second file to the first file, resulting a file with 3 columns. I did it by creating a new file and appending the data to it this way: import csv coinsfile = open('total-bitcoins.csv', newline='') pricesfile = open('market-price.csv', newline='') coins = csv.reader(coinsfile, delimiter=',') prices = csv.reader(pricesfile, delimiter=',') with open('result.csv', 'w') as res: for coin_row, price_row in zip(coins, prices): line = str(coin_row[0]) + ',' + str(coin_row[1]) + ',' + str(price_row[1]) res.append(line) The code runs without any errors but the result is a csv file which is completely empty. Where am I making the mistake, or is there a better way to do this job?

http://stackoverflow.com/q/51615872
has title: Typerror() in python while passing parameters to the route
score: -1
duplicate of: http://stackoverflow.com/q/14032066
linked to: http://stackoverflow.com/q/35188540
upvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/35188540
tagged with: flask
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I need to pass parameter to routes using url_for() function and redirect() I think I did the same. But, I get TypeError: book() missing 1 required positional argument: 'book_title' I know that the parameter book_title is not being recieved by the book() function in my code and thats why the error. But, I dont know what's going wrong behind the scenes. These are my routes @app.route('/search/ /',methods=['GET','POST']) def btitle(title): book_title = db.execute("SELECT title,author,isbn from books WHERE (title LIKE :title)",params={"title":title}).fetchall() if request.method == 'GET': #book_title = db.execute("SELECT title,author,isbn from books WHERE (title LIKE :title)",params={"title":title}).fetchall() if book_title: return render_template("booktitle.html",book_title=book_title) else: return render_template("error.html") else: #book_title = db.execute("SELECT title,author,isbn from books WHERE (title LIKE :title)",params={"title":title}).fetchall() if book_title: return redirect(url_for("book",book_title=book_title)) @app.route('/books',methods=['GET','POST']) def book(book_title): if request.method == 'GET': return render_template("individualbook.html",book_title=book_title) And, this is my booktitle.html {% extends "layout.html" %} {% block title %} {{ book }} {% endblock %} {% block body %} Search results {% for book in book_title %} {{ book }} {% endfor %} {% endblock %}
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51616020

http://stackoverflow.com/a/51483414
type: Answer
upvote count: 56
has body: The same manner as inside your link: user_agent = driver.execute_script("return navigator.userAgent;") PS: Using execute_script method you can run JS inside your driver. Hope it helps you!
answers question: http://stackoverflow.com/q/51482697
accepted answer of: http://stackoverflow.com/q/51482697
downvote count: 0
type: AcceptedAnswer
score: 56

http://stackoverflow.com/a/51583493
has comment: http://stackoverflow.com/comment/90134567
score: 1
has comment: http://stackoverflow.com/comment/90132444
has comment: http://stackoverflow.com/comment/90132425
upvote count: 1
type: AcceptedAnswer
has body: IIUC, use min() with a key [min(v.values(), key=lambda x: float(x[-1])) for k,v in d.items()] Outputs 'KL', 'AMS', '59.84' For your edited data, just do min(d.values(), key=lambda x: float(x[-1]))
type: Answer
has comment: http://stackoverflow.com/comment/90132403
accepted answer of: http://stackoverflow.com/q/51583471
answers question: http://stackoverflow.com/q/51583471
downvote count: 0

http://stackoverflow.com/a/51541312
answers question: http://stackoverflow.com/q/51540966
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51540966
score: 1
has comment: http://stackoverflow.com/comment/90050561
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90050423
has body: You can use keyword arguments and update object dictionary with update() method (works only if the variables aren't properties of the class. If that's the case, use setattr() method). class MyCalculationClass(): def __init__(self): # set some defaults self.A = 45454 self.B = [0, 0, 0, 0, 0] self.C = (1.0,2.5,30.0) def runRaw(self): print(self.A, self.B, self.C) def run(self, **kwargs): self.__dict__.update(kwargs) return self.runRaw() c = MyCalculationClass() c.run(B=[1, 1, 1]) Prints: 45454 [1, 1, 1] (1.0, 2.5, 30.0)
type: Answer

http://stackoverflow.com/a/51558851
answers question: http://stackoverflow.com/q/51555008
type: Answer
upvote count: 0
score: -1
downvote count: 1
has body: I see that this function checks two conditions. ResourceVariable and VarHandleOp This is a ResourceVariable according to the comments in the code "For example, if there is more than one assignment to a ResourceVariable in a single session.run call there is a well-defined value for each operation which uses the variable's value if the assignments and the read are connected by edges in the graph. Consider the following example, in which two writes can cause tf.Variable and tf.ResourceVariable to behave differently:" a = tf.Variable(1.0, use_resource=True) a.initializer.run() assign = a.assign(2.0) with tf.control_dependencies([assign]): b = a.read_value() with tf.control_dependencies([b]): other_assign = a.assign(3.0) with tf.control_dependencies([other_assign]): # Will print 2.0 because the value was read before other_assign ran. If # `a` was a tf.Variable instead, 2.0 or 3.0 could be printed. tf.Print(b, [b]).eval() VarHandleOp seems to have deeper semantics as per this "A common approach to managing where variables are placed, is to create a method to determine where each Op is to be placed and use that method in place of a specific device name when calling with tf.device(): Consider a scenario where a model is being trained on 2 GPUs and the variables are to be placed on the CPU. There would be a loop for creating and placing the "towers" on each of the 2 GPUs. A custom device placement method would be created that watches for Ops of type Variable, VariableV2, and VarHandleOp and indicates that they are to be placed on the CPU. All other Ops would be placed on the target GPU." It explains this scenario further with sample code.

http://stackoverflow.com/q/51601838
score: 5
answer count: 1
favorite count: 0
has body: I want to separate my model classes into separate files in a models directory. I would like to have a separate file for: general (authentication and global classes/tables) requisitions (tables used for requisitions) workorders (tables used for workorders) sales_orders (tables used for sales orders) ...etc I'm not sure how to structure my project to make that happen. I've tried putting my main imports into init.py in the directory and them importing those into the individual model files, but I don't know where to put my db.generate_mapping() so that all classes are available. I'm guessing this is a best practice for a large application. I've got about 150 tables in my app at this point. Any help/pointers would be appreciated.
upvote count: 5
has answer: http://stackoverflow.com/a/51671065
accepted answer: http://stackoverflow.com/a/51671065
tagged with: python
has title: PonyORM - multiple model files
tagged with: ponyorm
type: AnsweredQuestion
downvote count: 0
type: Question

http://stackoverflow.com/q/51527472
score: 0
has body: I'm junior python dev, mainly backend Django. One of my first tasks in work to write program on raspberry pi that set state to LOW and after 5 sec to HIGH. Seems not a problem but.... I think the proper way of waiting 5 sec to change to HIGH is not via time.sleep() but via threading.Timer (I found it on stackoverflow)... It will be connected via web socket so I think one thread must listen and another must change states My problem is half pythonic, half raspberrian... this is my code: import RPi.GPIO as GPIO from threading import Timer from time import sleep pin = 22 GPIO.setmode(GPIO.BCM) GPIO.setup(pin, GPIO.OUT) def set_high(): GPIO.output(pin, GPIO.HIGH) def web_socket_loop(): GPIO.output(pin, GPIO.LOW) t = Timer(5, set_high(GPIO)) t.start() web_socket_loop() GPIO.cleanup() When I run this code states are changing, but after few sec I also got an error: Exception in thread Thread-1: Traceback (most recent call last): File "/usr/local/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/local/lib/python3.7/threading.py", line 1158, in run self.function(*self.args, **self.kwargs) TypeError: 'NoneType' object is not callable I found on stack that I have to do something like this: (but it does not work properly): ;/ t = Timer(5, set_high, args=[GPIO]) And it does repair error about NoneType... but I got another error: Exception in thread Thread-1: Traceback (most recent call last): File "/usr/local/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/local/lib/python3.7/threading.py", line 1158, in run self.function(*self.args, **self.kwargs) RuntimeError: Please set pin numbering mode using GPIO.setmode(GPIO.BOARD) or GPIO.setmode(GPIO.BCM) I probably know why this error is but have no idea how to deal with it. I think that on another thread RPi.GPIO is not configured (GPIO.setmode(GPIO.BCM), GPIO.setup(pin, GPIO.OUT)) Thats why I pass GPIO as a variable to the function set_high(GPIO), without it on another th…
answer count: 1
has answer: http://stackoverflow.com/a/51527662
tagged with: timer
linked to: http://stackoverflow.com/q/8269096
tagged with: multithreading
has title: Threading Timer - NoneType error on raspberry pi - passing variable to another thread
tagged with: gpio
linked to: http://stackoverflow.com/q/277922
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51527662
has comment: http://stackoverflow.com/comment/90023768
type: Question
tagged with: raspberry-pi
duplicate of: http://stackoverflow.com/q/277922

http://stackoverflow.com/q/51501074
type: Question
has answer: http://stackoverflow.com/a/53363710
has body: I just started some couple hours ago with Pulp. I'm solving a MCLP problem, but i have no idea how to implement the Ni formula: see below in picture. My idea is that if a demand node is covered that another demand node less then 100m should also be covered by the facility.
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Implementing MCLP in pulp
score: 2
has comment: http://stackoverflow.com/comment/89970341
upvote count: 2
tagged with: pulp

http://stackoverflow.com/comment/90060919
has text: its k pal no need to apologise, we are all users here, I too was pointed out when I started
type: Comment
comment on: http://stackoverflow.com/q/51533619
type: QuestionComment
score: 1

uint32
tag name: uint32
tags question: http://stackoverflow.com/q/51565436
type: Tag

http://stackoverflow.com/q/51566331
type: UnansweredQuestion
tagged with: seaborn
has title: Code works in Jupyter but not in PyCharm
tagged with: python
has comment: http://stackoverflow.com/comment/90099801
has comment: http://stackoverflow.com/comment/90099378
score: 1
upvote count: 1
has body: I know this might be a very simple problem to solve, but I have been googling all day and cannot make it work. Please be patient with me - I just started working with Python. I have a very simple code, that I can execute well in Jupyter, but it does not work in PyCharm: import matplotlib.pyplot as plt import seaborn as sns; sns.set() import pandas as pd import numpy y = pd.read_csv('data_all.csv') df = y.iloc[:, 0:10] print(df) g = sns.PairGrid(df, hue='TP_PSP') g = g.map(plt.scatter) g = g.map_diag(plt.hist) g = g.map_offdiag(plt.scatter) g = g.add_legend() I receive the following error: Traceback (most recent call last): File "C:/Users/lukas/PycharmProjects/untitled/mtth-matplot.py", line 18, in &lt;module&gt; g = g.map_diag(plt.hist) File "C:\Users\lukas\PycharmProjects\untitled\venv\lib\site-packages\seaborn\axisgrid.py", line 1399, in map_diag func(data_k, label=label_k, color=color, **kwargs) File "C:\Users\lukas\PycharmProjects\untitled\venv\lib\site-packages\matplotlib\pyplot.py", line 3132, in hist stacked=stacked, normed=normed, data=data, **kwargs) File "C:\Users\lukas\PycharmProjects\untitled\venv\lib\site-packages\matplotlib\__init__.py", line 1855, in inner return func(ax, *args, **kwargs) File "C:\Users\lukas\PycharmProjects\untitled\venv\lib\site-packages\matplotlib\axes\_axes.py", line 6713, in hist labels = [six.text_type(lab) for lab in label] TypeError: 'numpy.int64' object is not iterable I have all packages installed and the interpreter works for "normal" python code. I am sorry posting such a trivial problem, but I cannot find a solution on the web that works for me. I am so grateful every hint to make it work. Thanks in advance and best regards LGR
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90100030
favorite count: 0
has answer: http://stackoverflow.com/a/66037090
tagged with: pycharm
has comment: http://stackoverflow.com/comment/90099403

http://stackoverflow.com/a/51536792
upvote count: 1
downvote count: 0
type: Answer
has body: Here's a simpler solution: weathers = ['sunny', 'rainy', 'cloudy'] weathers_dict = dict(enumerate(weathers, 1)) df_vc = df['weather'].value_counts() df_vc.index = df_vc.index.map(weathers_dict.get) Explanation Use dict with enumerate to construct a dictionary mapping integers to a list of weather types. Use dict.get with pd.Index.map. Unlike pd.Series.apply, you cannot pass a dictionary directly, but you can pass a callable function instead. Update the index directly rather than using an intermediary variable. Alternatively, you can apply your map to weather before using pd.Series.value_counts. This way, you do not need to update the index of your result. df['weather'] = df['weather'].map(weathers_dict) df_vc = df['weather'].value_counts()
has comment: http://stackoverflow.com/comment/90043370
answers question: http://stackoverflow.com/q/51536617
has comment: http://stackoverflow.com/comment/90046436
score: 1

http://stackoverflow.com/q/51599488
has body: I am trying to train a Tensorflow Convolutional Neural Network, and I am always getting a cryptic error regardless of the environment in which i run the program. In Jupyter Notebook, the kernel simply dies. In Terminal, I get "Illegal Instruction: 4" with no Traceback. In Pycharm, I get: "Process finished with exit code 132 (interrupted by signal 4: SIGILL)". I have looked all over the Internet and I have not found any instance in which this particular error was thrown in this situation. I would appreciate it if someone could help shed some light on this error. I am using Mac OS X High Sierra with python 3.6.2 My code can be found below and, as I said earlier, there is no traceback. import tensorflow as tf import numpy as np import pandas as pd # OS to load files and save checkpoints import os image_height = 60 image_width = 1 image1_height = 15 image2_width = 1 model_name = "tensorflowCNN" train_data = np.asarray(pd.read_csv("/home/student/Desktop/TrainingInput.csv", usecols=[1])) lis = train_data.tolist() lis = lis[0:60] lis = [x[0].strip('[]\n,') for x in lis] nlis = [] for i in lis: nlis.append(i.split()) for i in range(len(nlis)): nlis[i] = [float(x) for x in nlis[i] if x != "...,"] nlis = [np.mean(x) for x in nlis] train_data = np.asarray(nlis) train_labels = np.asarray(pd.read_csv("/home/student/Desktop/TrainingInput.csv", usecols=[2])) mylist = train_labels.tolist() mylist = mylist[0:60] mylist = [x[0] for x in mylist] for i in range(len(mylist)): if mylist[i] == "GravelTraining": mylist[i] = 1.0 elif mylist[i] == "WaterTraining": mylist[i] = 2.0 else: mylist[i] = 3.0 print(mylist) train_labels = np.asarray(mylist) eval_data = np.asarray(pd.read_csv("/home/student/Desktop/TestingInput.csv", usecols=[1])) List = eval_data.tolist() List = List[0:15] eval_data = np.asarray(List) eval_labels = np.asarray(pd.read_csv("/home/student/Desktop/TestingInput.csv", usecols=[2])) myList = eval_labels.tolist() myList = myList[0:15] eval_labels = np.asarray(myList) categor…
downvote count: 0
has comment: http://stackoverflow.com/comment/90166220
favorite count: 0
has comment: http://stackoverflow.com/comment/90203405
has comment: http://stackoverflow.com/comment/90205783
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/49092527
tagged with: jupyter-notebook
tagged with: conv-neural-network
tagged with: pycharm
upvote count: 2
has comment: http://stackoverflow.com/comment/90174898
answer count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90165545
has title: Illegal Instruction: 4 error when running any Tensorflow program
has answer: http://stackoverflow.com/a/51604520
has comment: http://stackoverflow.com/comment/90165996
linked to: http://stackoverflow.com/q/49122044
accepted answer: http://stackoverflow.com/a/51604520
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/51595736
has answer: http://stackoverflow.com/a/51596575
type: AnsweredQuestion
has title: Convert hex to 15 bit RGB value in python
has comment: http://stackoverflow.com/comment/90157462
has body: im a beginner with python and want to make a program that converts a hex RGB value to a 15 bit RGB one (5 bits for every color) i heard that it can be done by bitshifts but i don´t get how i also didn´t find anything helpful on the internet can someone please help me
tagged with: bit-shift
tagged with: rgb
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/51596575
answer count: 1
has comment: http://stackoverflow.com/comment/90157331
favorite count: 0
tagged with: python
score: -2
downvote count: 2

http://stackoverflow.com/comment/90176252
score: 0
has text: When doing rolling window operations like this, use stride tricks. The more you can get numpy to do for you under the hood, the happier you'll be.
comment on: http://stackoverflow.com/q/51605146
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90174792
comment on: http://stackoverflow.com/q/51604543
type: Comment
type: QuestionComment
score: 0
has text: Brew used to treat Python specially, but nowadays it treats Python the same as any other recipe. If you want an old version, you have to ask for it, with `brew install python@2`.

http://stackoverflow.com/q/51502156
has answer: http://stackoverflow.com/a/51502200
answer count: 1
has comment: http://stackoverflow.com/comment/89973212
has comment: http://stackoverflow.com/comment/89972704
favorite count: 0
tagged with: python-3.x
downvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/51502200
type: AnsweredQuestion
tagged with: oop
has body: I have a doubt about storing a class variables in a second variable, in order to be called later. This is my code (simplified to be readable): class Agent(object): def __init__(self): self.actual = [] class Play(object): def __init__(self): self.x = 0.45 * 400 self.y = 0.5 * 400 self.position = [] self.position.append([self.x, self.y]) self.x_change = 20 self.y_change = 0 def do_move(self, move, x, y): move_array = [self.x_change, self.y_change] if move == 1 and self.x_change == 0: # right move_array = [20, 0] self.x_change, self.y_change = move_array self.x = x + self.x_change self.y = y + self.y_change self.update_position(self.x, self.y) def update_position(self, x, y): self.position[-1][0] = x self.position[-1][1] = y def run(): agent = Agent() player1 = Play() agent.actual = [player1.position] print(agent.actual[0]) i = 1 player1.do_move(i, player1.x, player1.y) print(agent.actual[0]) run() &gt;&gt; [[180.0, 200.0]] &gt;&gt; [[200.0, 200.0]] This is what I cannot understand. Why, if agent.actual stores the player.position and it is not modified after agent.actual = [player1.position], its value actually changes between the two print()? I modify player.position, but not agent.actual, which means it should stay the same. I cannot figure this out! EDIT: I tried, as suggested, with the following methods: agent.actual = player1.position.copy() agent.actual = player1.position[:] agent.actual= list(player1.position) import copy agent.actual = copy.copy(player1.position) agent.actual = copy.deepcopy(player1.position) All these methods always return, as before, two different values: &gt;&gt; [[180.0, 200.0]] &gt;&gt; [[200.0, 200.0]]
tagged with: methods
duplicate of: http://stackoverflow.com/q/2612802
type: Question
has title: Python: variable changes without being called
has comment: http://stackoverflow.com/comment/89980101
upvote count: 0
score: -2
linked to: http://stackoverflow.com/q/2612802
tagged with: class

http://stackoverflow.com/q/51633831
type: AnsweredQuestion
score: 1
type: Question
answer count: 3
has comment: http://stackoverflow.com/comment/90232663
upvote count: 1
has comment: http://stackoverflow.com/comment/90232082
favorite count: 0
possible better answer: http://stackoverflow.com/a/51634065
tagged with: python
has answer: http://stackoverflow.com/a/51634537
accepted answer: http://stackoverflow.com/a/51634537
has body: I have 3 menus, where each menu depends on the subsequent menu choice (menu_3 depends on menu_2 selection, menu_2 depends on menu_1 selection). I'm trying to get every possible combination by clicking through to the last menu, then iterating through the options. Then going back to menu_2, select the next item, and iterate through all of the NEW menu_3 options. I keep creating either an endless loop/infinite recursion, or I get through one iteration and it stops. (I'm doing this on a website, so instead of continuing to send requests to the site, I'm trying to work through it locally.) Here's where I am currently, which is creating an infinite recursion: menu_1 = ['apple', 'orange', 'banana'] menu_2 = ['cat', 'dog', 'bird', 'fish'] menu_3 = ['red', 'orange', 'yellow', 'green', 'blue'] menu_names = ['menu 1', 'menu 2', 'menu 3'] menus = [menu_1, menu_2, menu_3] def recursion_testing(depth = len(menus) - 1, count = 0): for i in range(depth): print('count: ' + str(count)) if count == depth: print('menu: ' + menu_names[count]) for j in range(len(menus[count])): print(menus[count][j]) count = 0 else: return recursion_testing(depth, count+1) recursion_testing() Ultimately, my output would be the lists that show up when you click on red, orange, etc. If I can get this little test to output something like this, I could figure out the last bit: 'apple' 'cat' 'red' 'orange' 'yellow' 'green' 'blue' 'apple' 'dog 'red' 'orange' 'yellow' 'green' 'blue' ...etc.
downvote count: 0
has title: Python: Clicking through all possible (changing) menu combinations
has answer: http://stackoverflow.com/a/51634337
has answer: http://stackoverflow.com/a/51634065
tagged with: recursion

serverless-framework
tag name: serverless-framework
tags question: http://stackoverflow.com/q/51579814
type: Tag

http://stackoverflow.com/comment/90170714
type: AnswerComment
comment on: http://stackoverflow.com/a/51602318
type: Comment
has text: Yeah, as I said, just either say if levelNum == 3: buildLevel(level3) or make them all in a list.
score: 2

http://stackoverflow.com/comment/89990017
has text: You did not add your submodules to `setup.py`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51510616

http://stackoverflow.com/comment/90066354
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51549376
has text: Yes, they will work together. You don't really *need* either one, but if your course recommends Anaconda then you should probably use it, no? Personally, I think you should ditch Pycharm if you are a beginner
score: 0

http://stackoverflow.com/q/51623191
has answer: http://stackoverflow.com/a/60518275
downvote count: 0
tagged with: keras
upvote count: 8
answer count: 3
score: 8
favorite count: 0
has comment: http://stackoverflow.com/comment/90213846
has comment: http://stackoverflow.com/comment/119601831
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55892107
tagged with: python
has body: Without arguing the pros and cons of whether to actually do this, I'm curious if anyone has created or knows of a simple way to mutate the training data between epochs during the fitting of a model using keras. Example: I have 100 vectors and output features that I'm using to train a model. I randomly pick 80 of them for the training set, setting the other 20 aside for validation, and then run: model.fit(train_vectors,train_features,validation_data=(test_vectors,test_features)) Keras fitting allows one to shuffle the order of the training data with shuffle=True but this just randomly changes the order of the training data. It might be fun to randomly pick just 40 vectors from the training set, run an epoch, then randomly pick another 40 vectors, run another epoch, etc.
has title: Keras: is there an easy way to mutate (shuffle) data in/out of the training set between epochs?
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51625119

http://stackoverflow.com/q/51560490
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90087839
has body: I would like to get a list a=['wA', 'xB', 'yC', 'zD'], what argument to provide in commented section? i=None j=None a=[] for i in "wxyz": for j in "ABCD": while i!=j: # &lt;-- here break a.append(i+j) Thanks!
duplicate of: http://stackoverflow.com/q/1663807
score: 0
has answer: http://stackoverflow.com/a/51560545
has comment: http://stackoverflow.com/comment/90087859
duplicate of: http://stackoverflow.com/q/19560044
tagged with: python-3.x
linked to: http://stackoverflow.com/q/1919044
tagged with: python
has title: Double for loops
duplicate of: http://stackoverflow.com/q/1919044
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51560545
possible better answer: http://stackoverflow.com/a/51560586
has comment: http://stackoverflow.com/comment/90087814
has answer: http://stackoverflow.com/a/51560586

http://stackoverflow.com/a/51513333
has comment: http://stackoverflow.com/comment/90015397
has comment: http://stackoverflow.com/comment/90020164
has comment: http://stackoverflow.com/comment/90015692
type: Answer
has comment: http://stackoverflow.com/comment/90015352
has comment: http://stackoverflow.com/comment/90015946
has comment: http://stackoverflow.com/comment/90015284
upvote count: 1
has comment: http://stackoverflow.com/comment/90016145
answers question: http://stackoverflow.com/q/51507322
has body: Since you are using the backend directly, I think you also need to use gradients method from the backend: grads = K.gradients(...)
has comment: http://stackoverflow.com/comment/90020356
has comment: http://stackoverflow.com/comment/90012131
has comment: http://stackoverflow.com/comment/90013392
has comment: http://stackoverflow.com/comment/90011528
downvote count: 0
score: 1

http://stackoverflow.com/a/51593245
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51593062
upvote count: 3
answers question: http://stackoverflow.com/q/51593062
type: Answer
downvote count: 0
has body: property is a descriptor, and like all descriptors it is only invoked when resolved as a class attribute - as you discovered, when it's an instance attribute, it's __get__ and __set__ methods are not invoked. If your point is only to avoid rewriting the same getters and setters for N properties, the plain simple solution is to write your own descriptor: class MyProp(object): def __init__(self, name): self.name = name def __get__(self, obj, cls): if obj is None: return self value = getattr(obj, "_" + self.name) if value is None: return "This is None!" else: return value def __set__(self, obj, value): setattr(obj, "_" + self.name, value) class Foo(object): prop1 = MyProp("prop1") prop2 = MyProp("prop2")
has comment: http://stackoverflow.com/comment/90152975
has comment: http://stackoverflow.com/comment/90191297
has comment: http://stackoverflow.com/comment/90152671
has comment: http://stackoverflow.com/comment/90192227
score: 3

http://stackoverflow.com/comment/90204398
has text: I get key error when I try this. I do not understand why. it works for the given example but the actual data frames it gives key error. This may be because of the dimensions because originally df1 is 3 rows 3686 columns and df 2 is 1353379 rows × 2 columns @jpp
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51603410
type: AnswerComment

http://stackoverflow.com/comment/90032808
type: QuestionComment
has text: did you try to remove `id` for new records?
comment on: http://stackoverflow.com/q/51532492
score: 0
type: Comment

http://stackoverflow.com/q/51622411
type: AnsweredQuestion
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/51644241
answer count: 2
tagged with: python
has title: Can't import frozen graph after adding layers to Keras model
linked to: http://stackoverflow.com/q/51858203
tagged with: tensorflow
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51644241
has body: I'm trying to load a trained Keras model from the .h5 file, then wrap a couple TensorFlow layers around it and save as a ProtoBuf. The saving works just fine, but when I import the graph def, I get the error: ValueError: Input 0 of node batch_normalization_24_1/cond/ReadVariableOp/Switch_1 was passed float from batch_normalization_24/gamma_1:0 incompatible with expected resource. Below is a minimum reproducible example of this error: import tensorflow as tf import keras import keras.backend.tensorflow_backend as K import base64 def bitstring_to_float32_tensor(input_bytes, image_size): """ Transforms image bitstring to float32 tensor. Args: input_bytes: A bitstring representative of an input image. image_size: The input image size (e.g., 512). Returns: A batched float32 tensor representative of the input image. """ input_bytes = tf.reshape(input_bytes, []) # Transforms bitstring to uint8 tensor input_tensor = tf.image.decode_png(input_bytes, channels=3) # Converts to float32 tensor input_tensor = tf.image.convert_image_dtype(input_tensor, dtype=tf.float32) input_tensor = input_tensor / 127.5 - 1.0 # Ensures tensor has correct shape input_tensor = tf.reshape(input_tensor, [image_size, image_size, 3]) # Expands the single tensor into a batch of 1 input_tensor = tf.expand_dims(input_tensor, 0) return input_tensor def float32_tensor_to_bitstring(output_tensor): """ Transforms float32 tensor to list of image bitstrings. Args: output_tensor: A float32 tensor representative of an inferred image. Returns: output_node_names: A list containing the name of the output node in the graph. """ # Converts to uint8 tensor output_tensor = (output_tensor + 1.0) / 2.0 output_tensor = tf.image.convert_image_dtype(output_tensor, tf.uint8) output_tensor = tf.squeeze(output_tensor) # Transforms uint8 tensor to bitstring output_bytes = tf.image.encode_png(output_tensor) output_bytes = tf.identity(output_bytes, name="output_bytes") # Adds output node name to list output_node_names = ["output_…
possible better answer: http://stackoverflow.com/a/52823898
tagged with: keras
has answer: http://stackoverflow.com/a/52823898

http://stackoverflow.com/comment/90220049
comment on: http://stackoverflow.com/q/51627294
type: Comment
type: QuestionComment
score: 1
has text: state it, and give example of it, otherwise you'll need to write another if :>

http://stackoverflow.com/comment/90228334
score: 0
type: Comment
has text: @user308827 - Mybe problem is need something else for `both` output, can you explin more?
type: AnswerComment
comment on: http://stackoverflow.com/a/51631883

http://stackoverflow.com/q/51590818
score: 0
answer count: 1
has title: Appending data to an existing Json file
has answer: http://stackoverflow.com/a/51591357
tagged with: python
type: AnsweredQuestion
has body: i have json file of the following format: {"CustomerNo": "858017D", "SalesOrder": "ERI2380", "Brand": "HONAC", "Item": "HL10CESWB", "Qty": "1", "Month": "6","time": "2018-06-19T16:28:58Z"} {"CustomerNo": "072881D", "SalesOrder": "W619091", "Brand": "HONAC", "Item": "MO10CESWK", "Qty": "-1", "Month": "6","time": "2018-06-08T12:36:29Z"} {"CustomerNo": "072881D", "SalesOrder": "W642501", "Brand": "HONAC", "Item": "MO08CESWK", "Qty": "1", "Month": "6", "time": "2018-06-19T08:20:51Z"} {"CustomerNo": "072866D", "SalesOrder": "W645370", "Brand": "HONAC", "Item": "MN10CESBB", "Qty": "1", "Month": "6", "time": "2018-06-19T16:36:22Z"} Need to append to an existing file which has data in a similar format. But the resulting file is getting all messed up. I need append this file several times a day. The code looks like: csvfile1 = open('daily.csv', 'r') jsonfile1 = open('test3.json', 'a') fieldnames = list(raw_data.columns.values) reader1 = csv.DictReader( csvfile1, fieldnames) next(reader1) jsonfile1.write('\n') pos = next1 = 0 for row in reader1: pos = next1 next1 += len(row) # compute position of beginning of next line json.dump(row, jsonfile1) jsonfile1.write('\n') jsonfile1.truncate(pos) The final output is not exactly the append. It is some malformed file with incomplete json objects.
type: Question
accepted answer: http://stackoverflow.com/a/51591357

http://stackoverflow.com/q/51486219
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51486327
type: AnsweredQuestion
downvote count: 0
has title: Linux: file descriptors from os.pipe() not appearing in /dev/fd
has answer: http://stackoverflow.com/a/51486327
type: Question
score: 3
tagged with: pipe
upvote count: 3
has body: In the past, I've seen virtual files for all open file descriptors appear in /dev/fd. However, currently I'm using Amazon Linux and I am not seeing new file descriptors appear when I run os.pipe() in a Python program. For example: MASTER:hadoop@imrdasem2d14$ ls -l /dev/fd/ total 0 lrwx------ 1 hadoop hadoop 64 Jul 23 15:39 0 -&gt; /dev/pts/0 lrwx------ 1 hadoop hadoop 64 Jul 23 15:39 1 -&gt; /dev/pts/0 lrwx------ 1 hadoop hadoop 64 Jul 23 15:39 2 -&gt; /dev/pts/0 lr-x------ 1 hadoop hadoop 64 Jul 23 15:39 3 -&gt; /proc/30933/fd MASTER:hadoop@imrdasem2d14$ % python &gt;&gt;&gt; import os &gt;&gt;&gt; a,b = os.pipe() &gt;&gt;&gt; c,d = os.pipe() &gt;&gt;&gt; [2]+ Stopped python MASTER:hadoop@imrdasem2d14$ !ls ls -l /dev/fd/ total 0 lrwx------ 1 hadoop hadoop 64 Jul 23 15:39 0 -&gt; /dev/pts/0 lrwx------ 1 hadoop hadoop 64 Jul 23 15:39 1 -&gt; /dev/pts/0 lrwx------ 1 hadoop hadoop 64 Jul 23 15:39 2 -&gt; /dev/pts/0 lr-x------ 1 hadoop hadoop 64 Jul 23 15:39 3 -&gt; /proc/31001/fd MASTER:hadoop@imrdasem2d14$ But it's clear that the pipe is working: a,b,c,d (3, 4, 5, 6) &gt;&gt;&gt; os.write(b,b"foo") 3 &gt;&gt;&gt; os.read(a,3) b'foo' So how come my file descriptors for 3, 4, 5 and 6 aren't in /dev/fd?
answer count: 1

http://stackoverflow.com/a/51604772
downvote count: 0
type: Answer
upvote count: 1
has body: I found the similar question and answer: Packing array into lower triangular of a tensor Based on the page above, I made a function which transform a vector into a lower triangular with unit diagonal elements: def flat_to_mat_TF(vector, n): idx = list(zip(*np.tril_indices(n, k=-1))) idx = tf.constant([list(i) for i in idx], dtype=tf.int64) values = tf.constant(vector, dtype=tf.float32) dense = tf.sparse_to_dense(sparse_indices=idx, output_shape=[n, n], \ sparse_values=values, default_value=0, \ validate_indices=True) mat = tf.matrix_set_diag(dense, tf.cast(tf.tile([1], [n]), dtype=tf.float32)) return mat If the input vector is already a Tensor, values = tf.constant() could be eliminated.
score: 1
answers question: http://stackoverflow.com/q/51571032

http://stackoverflow.com/comment/90233864
has text: I recommend taking a read through [here](http://explained.ai/rf-importance/index.html). It's a fantastic walkthrough of what Feature Importances are in SkLearn and how speed was substituted for accuracy.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51634774

http://stackoverflow.com/comment/90217183
has text: Here is the dropbox link for the screenshot of my ngninx config https://www.dropbox.com/s/8qbgj4gwb6jfrch/nginx_config.PNG?dl=0. Thanks for helping me find it. I will not be on until tomorrow, around 8 PST, so I might not respond to your questions. Just informing you. Thanks.
type: AnswerComment
comment on: http://stackoverflow.com/a/51625654
score: 0
type: Comment

mysql
tags question: http://stackoverflow.com/q/51574834
tags question: http://stackoverflow.com/q/51620610
tag name: mysql
tags question: http://stackoverflow.com/q/51505589
tags question: http://stackoverflow.com/q/51611126
tags question: http://stackoverflow.com/q/51582331
tags question: http://stackoverflow.com/q/51561421
tags question: http://stackoverflow.com/q/51529872
tags question: http://stackoverflow.com/q/51585732
tags question: http://stackoverflow.com/q/51633002
tags question: http://stackoverflow.com/q/51529641
tags question: http://stackoverflow.com/q/51493021
tags question: http://stackoverflow.com/q/51553157
tags question: http://stackoverflow.com/q/51503358
tags question: http://stackoverflow.com/q/51601335
tags question: http://stackoverflow.com/q/51522716
tags question: http://stackoverflow.com/q/51577056
tags question: http://stackoverflow.com/q/51537507
tags question: http://stackoverflow.com/q/51510716
tags question: http://stackoverflow.com/q/51570218
type: Tag
tags question: http://stackoverflow.com/q/51483611
tags question: http://stackoverflow.com/q/51543505
tags question: http://stackoverflow.com/q/51493860
tags question: http://stackoverflow.com/q/51536577
tags question: http://stackoverflow.com/q/51597780
tags question: http://stackoverflow.com/q/51541762
tags question: http://stackoverflow.com/q/51578425
tags question: http://stackoverflow.com/q/51534069
tags question: http://stackoverflow.com/q/51596225
tags question: http://stackoverflow.com/q/51548079
tags question: http://stackoverflow.com/q/51484521
tags question: http://stackoverflow.com/q/51527075
tags question: http://stackoverflow.com/q/51587078
tags question: http://stackoverflow.com/q/51579233
tags question: http://stackoverflow.com/q/51613359
tags question: http://stackoverflow.com/q/51606054
tags question: http://stackoverflow.com/q/51547302
tags question: http://stackoverflow.com/q/51488421
tags question: http://stackoverflow.com/q/51620173
tags question: http://stackoverflow.com/q/51580601
tags question: http://stackoverflow.com/q/51631243
tags question: http://stackoverflow.com/q/51547926
tags question: http://stackoverflow.com/q/51505912
tags question: http://stackoverflow.com/q/51632003

http://stackoverflow.com/a/51574805
has comment: http://stackoverflow.com/comment/90115414
type: Answer
has body: you can do: asym1 = [n for n in asym1 if n.is_real][0]
answers question: http://stackoverflow.com/q/51574700
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51574700

http://stackoverflow.com/q/51602575
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51603735
tagged with: python
has comment: http://stackoverflow.com/comment/90171790
has comment: http://stackoverflow.com/comment/90173383
has title: Drop 0 values, NaN values, and empty strings
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90171618
type: Question
has comment: http://stackoverflow.com/comment/90171264
has comment: http://stackoverflow.com/comment/90171632
score: 1
has comment: http://stackoverflow.com/comment/90171336
has comment: http://stackoverflow.com/comment/90171519
has comment: http://stackoverflow.com/comment/90171219
has comment: http://stackoverflow.com/comment/90171285
has body: import pandas as pd import csv import numpy as np readfile = pd.read_csv('50.csv') filevalues= readfile.loc[readfile['Customer'].str.contains('Lam Dep', na=False), 'Jul-18\nQty'] filevalues = filevalues.replace(r'^\s*$', np.nan, regex=True) filevalues = filevalues.fillna(int(0)) int_series = filevalues.astype(int) calculated_series = int_series.apply(lambda x: x*(1/1.2)) print(calculated_series) So I have hundreds of csv files with many empty spots for values. Some of the blanks spaces are detected as NaNs and others are empty strings.This has Forced me to create my code in the way it is right now, and the reason so is that I need to conduct a formula on each value so I changed all such NaNs and empty strings to 0 so that I am able to conduct any formula ( in this example 1/1.2.) The problem is that I do not want to see values that are 0, NaN or empty strings when printing my dataframe. I have tried to use the following: filevalues = filevalues.dropna() But because certain csv files have empty strings, this method does not fully work and get the error: ValueError: invalid literal for int() with base 10: ' ' I have also tried the following after converting all values to 0: filevalues = filevalues.loc[:, (filevalues != 0).all(axis=0)] and mask = np.any(np.isnan(filevalues) | np.equal(a, 0), axis=1) Every method seems to be giving different errors. Is there a clean way to not count these types of values when I am printing my pandas dataframe? Please let me know if an example csv file is needed.
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90171614
has comment: http://stackoverflow.com/comment/90171797
favorite count: 0
has comment: http://stackoverflow.com/comment/90171471
has comment: http://stackoverflow.com/comment/90171374
tagged with: pandas

http://stackoverflow.com/q/51527868
has body: I've been trying to display a gif in Jupyter notebook and have had some trouble. I keep getting a blank image file. I've tried using html from this GitHub repository. ![wignerfunction][1](../gifs/wigner_rotation_animate.gif "wigner") And from IPython.display import Image Image(url='example.gif') None of the above have worked so far. Thanks
has answer: http://stackoverflow.com/a/71262575
linked to: http://stackoverflow.com/q/32370281
tagged with: ipython
has title: How do I embed a gif in Jupyter notebook?
type: Question
has answer: http://stackoverflow.com/a/75054402
has answer: http://stackoverflow.com/a/59988258
has comment: http://stackoverflow.com/comment/90024895
has comment: http://stackoverflow.com/comment/129243043
has answer: http://stackoverflow.com/a/60547855
has comment: http://stackoverflow.com/comment/90024615
answer count: 7
accepted answer: http://stackoverflow.com/a/51528612
has comment: http://stackoverflow.com/comment/90024599
favorite count: 0
linked to: http://stackoverflow.com/q/61110188
upvote count: 31
has comment: http://stackoverflow.com/comment/90024496
has comment: http://stackoverflow.com/comment/90024775
has answer: http://stackoverflow.com/a/71852681
has answer: http://stackoverflow.com/a/51528612
tagged with: python
tagged with: jupyter
downvote count: 0
possible better answer: http://stackoverflow.com/a/60547855
has comment: http://stackoverflow.com/comment/90024440
has answer: http://stackoverflow.com/a/74135713
score: 31
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90024464
has comment: http://stackoverflow.com/comment/90024637

http://stackoverflow.com/q/51526353
has title: Twisted: cache list of instances
has body: I am currently working through the twisted Developer Guides and would like to get some information/guide regarding extending the usecase of one of the provides examples, namely caching instances of objects: The example code is: cache.classes.py from twisted.spread import pb class MasterDuckPond(pb.Cacheable): def __init__(self, ducks): self.observers = [] self.ducks = ducks def count(self): print "I have [%d] ducks" % len(self.ducks) def addDuck(self, duck): self.ducks.append(duck) for o in self.observers: o.callRemote('addDuck', duck) def removeDuck(self, duck): self.ducks.remove(duck) for o in self.observers: o.callRemote('removeDuck', duck) def getStateToCacheAndObserveFor(self, perspective, observer): self.observers.append(observer) # you should ignore pb.Cacheable-specific state, like self.observers return self.ducks # in this case, just a list of ducks def stoppedObserving(self, perspective, observer): self.observers.remove(observer) class SlaveDuckPond(pb.RemoteCache): # This is a cache of a remote MasterDuckPond def count(self): return len(self.cacheducks) def getDucks(self): return self.cacheducks def setCopyableState(self, state): print " cache - sitting, er, setting ducks" self.cacheducks = state def observe_addDuck(self, newDuck): print " cache - addDuck" self.cacheducks.append(newDuck) def observe_removeDuck(self, deadDuck): print " cache - removeDuck" self.cacheducks.remove(deadDuck) pb.setUnjellyableForClass(MasterDuckPond, SlaveDuckPond) cache_sender.py #!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb, jelly from twisted.python import log from twisted.internet import reactor from cache_classes import MasterDuckPond class Sender: def __init__(self, pond): self.pond = pond def phase1(self, remote): self.remote = remote d = remote.callRemote("takePond", self.pond) d.addCallback(self.phase2).addErrback(log.err) def phase2(self, response): self.pond.addDuck("ugly duckling") self.po…
has answer: http://stackoverflow.com/a/51529325
tagged with: twisted
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
type: Question

http://stackoverflow.com/q/51561493
tagged with: python-2.7
score: 0
has title: New construct 2.9 syntax for struct staticfield data type
answer count: 1
has answer: http://stackoverflow.com/a/53037884
type: UnansweredQuestion
tagged with: construct
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/90090038
has body: I had this, using construct 2.5.2: something=Struct("somename", Bytes("version",4), StaticField("somefieldname",32) ) myVar=something.parse('John') myVar.version=struct.pack('&lt;I',1) myVar.somefieldname=struct.pack('&lt;qqqq',0,0,0,0) Now I have to change it in order to satisfy the new construct 2.9 syntax: something="somename" / Struct ( "version" / Bytes(4) "somefieldname" / ???? ) What is the old "StaticField" I used in order to store the struct.pack result called in the new construct version?

http://stackoverflow.com/comment/90124253
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51579371
has text: @WillemVanOnsem good point, then maybe `for s in map(list, itertools...):`.

http://stackoverflow.com/comment/90133821
has text: I am confused about the def _is_valid_operand portion of the code and whether my code above would need it.
comment on: http://stackoverflow.com/q/51584100
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90111490
type: QuestionComment
score: 0
has text: I'm guessing Player_Height is a list in which case, try this: str = ''.join(Player_Height) . Is that what you are looking for?
comment on: http://stackoverflow.com/q/51572720
type: Comment

http://stackoverflow.com/comment/90101584
has text: @YvesDaoust In non-equilibrium statistical mechanics, solution of the Fokker-Planck equation often needs such huge evaluations.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51556833

http://stackoverflow.com/q/51499084
has body: I'm trying to create a confirmation system using email link and tokens using Django here are my files : tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() That is where I've created the token Forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, help_text='Must be a valid E-mail') user_name = forms.CharField(required=True, help_text='') password1 = forms.CharField(widget=forms.PasswordInput, help_text='') password2 = forms.CharField(widget=forms.PasswordInput, help_text='Password confirmation') avatar = forms.ImageField(required=False) class Meta: model = User fields = ('email', 'user_name', 'password1', 'password2', 'avatar') labels = { 'user_name': 'user_name', 'email': ' email', 'password1': 'password1', 'password2': 'password2', 'avatar': 'avatar', } def clean_email(self): data = self.cleaned_data['email'] return data.lower() That is where I've created the signup form views.py def signup(request): current_user_ip = get_client_ip(request) current_temp = Temp.objects.filter(created_by_ip=current_user_ip) current_temp.delete() if request.method == 'POST': signup_form = SignUpForm(request.POST, request.FILES) if signup_form.is_valid(): user = signup_form.save(commit=False) user.is_confirmed = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your Jehlum account.' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = signup_form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confir…
has comment: http://stackoverflow.com/comment/89966742
tagged with: python
has comment: http://stackoverflow.com/comment/89966442
answer count: 0
score: 1
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/105203253
has comment: http://stackoverflow.com/comment/89967153
has comment: http://stackoverflow.com/comment/89969830
upvote count: 1
downvote count: 0
has title: Email confirmation link fail in django
has comment: http://stackoverflow.com/comment/89966916
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/89945304
score: 0
type: Comment
has text: Thanks. I updated my answer with my new attempt based on your response, but still failed.
comment on: http://stackoverflow.com/a/51487945
type: AnswerComment

http://stackoverflow.com/q/51599659
tagged with: python
has comment: http://stackoverflow.com/comment/90167955
tagged with: selenium-chromedriver
tagged with: selenium
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51605292
type: Question
has answer: http://stackoverflow.com/a/51605292
has title: chromedriver.exe stopped working issue
answer count: 1
downvote count: 1
favorite count: 0
score: 0
has body: I am using a windows client to perform UI automated tests. each time i start the test using cmd or eclipse the browser opens up and goes to the given url but it does not continue, instead, a small window is opened with "Chromedriver.exe stopped working" message on it. how can I solve this issue? I am using on this windows client : python 2.7.15, selenium 3.5.0 , robot framework 3.0.2,windows 7 professional , and chrome P.S. : I already tried upgrading and downgrading both chrome and chrome driver, also, used selenium 3.13.0 then downgraded again to selenium 3.5.0.
upvote count: 1

http://stackoverflow.com/a/51546697
upvote count: 1
has body: It seems like you expect the output to stop after the first three lines of output. But although the if body is not executed the fourth time, the overall execution does not stop. There is still a call stack that is not empty. That particular function call (that did not execute the if block), returns to the execution context of the function that called it, which still has things to do. Namely, it should print "second value" ... and then also it returns to the place where it was called from, ...etc. Note that when a function is called (maybe from within a function -- which could be the same function), the calling code will resume once that function returns. In your case the code returns within an if block of which the condition is not re-evaluated, as that was already done before. So even though center_length became 0, it does not affect where the calling code will proceed. What's more, each function execution context has its own, separate center_length variable. So even if it is passed on as one less, this does not influence the value center_length has in the calling function. This fact does not influence the execution order in your case, but it may help to get grips on recursion.
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51546593

http://stackoverflow.com/comment/89998671
comment on: http://stackoverflow.com/a/51514834
has text: By the way, why Python 2.7? Python 3 has been out for ages, Python 2 has only received bug fixes since 2010...
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90210635
type: AnswerComment
has text: Good to know but take a while for me to digest. I will keep `[\w ]*` for now because it's more explicit and natural to my brain. Thanks!
comment on: http://stackoverflow.com/a/51622212
type: Comment
score: 0

http://stackoverflow.com/q/51562908
has answer: http://stackoverflow.com/a/51563088
accepted answer: http://stackoverflow.com/a/51563088
tagged with: python
has title: Python Discord ChatBot: Making a mood counter
has body: I want to make a mood counter for my discord ChatBot. This variable should influence responses to the user. I made two dictionaries in python so far, one called responses and one called insults. The responses are straightforward, with the bot replying if the user sent a message that was in the dictionary. The insult dictionary subtracts a set amount from the variable mood every time you insult the bot. I wrote an if statement trying to subtract the mood by a little bit but whenever I try actually insulting the bot, the bot doesn't say anything to me. Please help. Keep in mind this is not all the code and I am willing to provide a more in-depth explanation as to what problem I have. @client.event async def on_message(message) : content = message.content.upper() mood = 2 if content in responses: if mood &lt;= 0: await client.send_message(message.channel, responses[content]["RANG"]) if mood == 1: await client.send_message(message.channel, responses[content]["ANG"]) if mood == 2: await client.send_message(message.channel, responses[content]["NEU"]) if mood == 3: await client.send_message(message.channel, responses[content]["HAP"]) if mood == 4: await client.send_message(message.channel, responses[content]["RHAP"]) if content in insults: mood = mood - 0.25 if mood &lt;= 0: await client.send_message(message.channel, insults[content]["RANG"]) if mood == 1: await client.send_message(message.channel, insults[content]["ANG"]) if mood == 2: await client.send_message(message.channel, insults[content]["NEU"]) if mood == 3: await client.send_message(message.channel, insults[content]["HAP"]) if mood == 4: await client.send_message(message.channel, insults[content]["RHAP"])
tagged with: discord
type: AnsweredQuestion
type: Question
tagged with: discord.py
score: 0
linked to: http://stackoverflow.com/q/47955125
answer count: 1

http://stackoverflow.com/comment/90128910
type: Comment
type: QuestionComment
has text: Take a look at the Django REST Framework. You'll need to create an API for the CRUD operations, then you can use `get` or `post` http requests to get and update data on the server.
comment on: http://stackoverflow.com/q/51581792
score: 0

http://stackoverflow.com/q/51613686
accepted answer: http://stackoverflow.com/a/51628542
possible better answer: http://stackoverflow.com/a/51627593
has comment: http://stackoverflow.com/comment/90204601
has title: Play sound when objects collide
answer count: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51628542
has answer: http://stackoverflow.com/a/51627964
upvote count: 1
has body: I'm trying to play the ouch sound when the object ball collides with an angryball, but the sound doesn't always play. It starts on the first collision when the two objects are on the same x or y coordinate but after that it doesn't play correctly for future collisions. Maybe it's my fault on how I manage to handle their coordinates to check for the collision? import pygame import os import random size = width, height = 750, 422 screen = pygame.display.set_mode(size) img_path = os.path.join(os.getcwd()) background_image = pygame.image.load('background.jpg').convert() bg_image_rect = background_image.get_rect() pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.display.set_caption("BallGame") class Ball(object): def __init__(self): self.image = pygame.image.load("ball.png") self.image_rect = self.image.get_rect() self.image_rect.x self.image_rect.y self.facing = 'LEFT' def handle_keys(self): key = pygame.key.get_pressed() dist = 5 if key[pygame.K_DOWN] and self.image_rect.y &lt; 321: self.facing = 'DOWN' self.image_rect.y += dist elif key[pygame.K_UP] and self.image_rect.y &gt; 0: self.facing = 'UP' self.image_rect.y -= dist if key[pygame.K_RIGHT] and self.image_rect.x &lt; 649: self.facing = 'RIGHT' self.image_rect.x += dist elif key[pygame.K_LEFT] and self.image_rect.x &gt; 0: self.facing = 'LEFT' self.image_rect.x -= dist def draw(self, surface): if self.facing == "RIGHT": surface.blit(pygame.transform.flip(self.image, True, False),(self.image_rect.x,self.image_rect.y)) elif self.facing == "DOWN": surface.blit(pygame.image.load("ball_down.png"),(self.image_rect.x,self.image_rect.y)) if self.facing == "UP": surface.blit(pygame.image.load("ball_up.png"),(self.image_rect.x,self.image_rect.y)) elif self.facing == "LEFT": surface.blit(self.image,(self.image_rect.x,self.image_rect.y)) mob_images = [pygame.image.load("image1.png").convert_alpha(),pygame.image.load("image2.png").convert_alpha(),pygame.image.load("image3.png").convert_alpha(),pygame.image.load("image4.png").c…
tagged with: python
tagged with: pygame
tagged with: virtualbox
type: AnsweredQuestion
tagged with: ubuntu-18.04
has answer: http://stackoverflow.com/a/51627593
score: 1
has comment: http://stackoverflow.com/comment/90219543
type: Question

http://stackoverflow.com/comment/90145013
type: QuestionComment
type: Comment
has text: The best way to be sure that OpenCL is in the prebuilt python binaries is to write: `print (cv2.getBuildInformation())` and to look for the OpenCL tag.
comment on: http://stackoverflow.com/q/51588683
score: 0

http://stackoverflow.com/a/51620472
answers question: http://stackoverflow.com/q/51620157
has comment: http://stackoverflow.com/comment/90207643
has comment: http://stackoverflow.com/comment/90207137
type: Answer
has comment: http://stackoverflow.com/comment/90206761
has comment: http://stackoverflow.com/comment/90207441
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90207679
has body: You are probably completing the form while the user field is expecting a value when none is passed. Add this to your view: class NotesCreateView(LoginRequiredMixin,CreateView): model=Notes form_class=NotesCreateForm redirect_field_name='notes_detail.html' def form_valid(self, form): form.instance.user = self.request.user return super(NotesCreateView, self).form_valid(form) This will assign the Note to the current logged in user.
has comment: http://stackoverflow.com/comment/90207324
has comment: http://stackoverflow.com/comment/90206855
has comment: http://stackoverflow.com/comment/90207223
has comment: http://stackoverflow.com/comment/90206949
accepted answer of: http://stackoverflow.com/q/51620157
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51618569
has body: The quick fix is to change b = Tk() to b = Toplevel(root) in class Individual():. Other than that you need to rework some of your code to be more DRY as I mentioned in my comment. I feel you can benefit from seeing what this code would look like written to be DRY and following the PEP8 standard. Here is your code re-written to better follow PEP8 and the DRY practice. Less white-space the below code is only 42 lines of code. import tkinter as tk lbl_list = ['ID Number: ', 'Name: ', "Father's Name: ", 'Address: ', 'Mobie Number ', 'ID Card Number: ', 'Date of Joining: ', 'Skill: ', 'Wages: ', 'Over Time: ', 'Go'] string_var_list = [] entry_list = [] font32 = ('Comic Sans MS', 32, 'bold') font28 = ('Comic Sans MS', 28, 'bold') font20 = ('Comic Sans MS', 20) class MainWindow(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.config(background='black') tk.Label(self, text='Welcome to Worker Management App...', font=font32, fg='white', bg='black').grid(row=1, column=0, columnspan=3) tk.Label(self, text='Choose a category:', font=font32, fg='white', bg='black').grid(row=2, column=0, columnspan=3) tk.Button(self, text='1. Individual', font=font28, fg='white', bg='black', command=self.gui_indi).grid(row=3, column=1, pady=25) b2 = tk.Button(self, text='2. Contractor', font=font28, fg='white', bg='black') b2.grid(row=4, column=1, pady=25) def gui_indi(self): B1 = tk.Button(self, text='Register New', font=font20, fg='white', bg='black') B1.grid(row=2, column=0, rowspan=3, sticky="e") B1.config(command=lambda: Individual(self)) B2 = tk.Button(self, text='Existing', font=font20, fg='white', bg='black') B2.grid(row=2, column=2, rowspan=3, sticky="w") def savedata(self): for strvar in string_var_list: print(strvar.get()) class Individual(tk.Toplevel): def __init__(self, master): tk.Toplevel.__init__(self) self.config(background='black') for i in range(len(lbl_list)): string_var_list.append(tk.StringVar()) entry_list.append(tk.Entry(self, textvariable=string_var_list[i])) for nde…
answers question: http://stackoverflow.com/q/51617405
accepted answer of: http://stackoverflow.com/q/51617405
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90204273
type: Answer

http://stackoverflow.com/q/51618560
downvote count: 0
tagged with: google-ads-api
has body: I'm building a helper library to call the AdWords (Google Ads) Keyword Planner API and having trouble catching RateExceededError errors when they come up. The specific error message that I'm getting is below. GoogleAdsServerFault: RateExceededError &lt;rateName=RATE_LIMIT, rateKey=null, rateScope=ACCOUNT, retryAfterSeconds=30, errorDetails="Quota check failed: QuotaInfo{quotaGroupId=v2-kwi-webapi-global, userId=global}"&gt; Original AdsAPI trace for debugging [ com.google.ads.api.services.common.error.ApiException: RateExceededError &lt;rateName=RATE_LIMIT, rateKey=null, rateScope=ACCOUNT, retryAfterSeconds=30, errorDetails="Quota check failed: QuotaInfo{quotaGroupId=v2-kwi-webapi-global, userId=global}"&gt; Underlying ApiErrors are: RateExceededError &lt;rateName=RATE_LIMIT, rateKey=null, rateScope=ACCOUNT, retryAfterSeconds=30&gt; I'm currently working with the below setup to call the API and catch errors, however exceptions are still being raised occasionally. Is there a better way I should catch these errors and just log the exceptions as warnings? class AdwordsAPIException(Exception): pass def call_adwords_api_client(self, selector): try: return _adwords_client.get(selector) except AdwordsAPIException: return None Many thanks in advance!
favorite count: 0
accepted answer: http://stackoverflow.com/a/51618638
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51618638
has title: AdWords RateExceededError
answer count: 1

http://stackoverflow.com/q/51571362
score: 2
type: AnsweredQuestion
tagged with: list
upvote count: 3
possible better answer: http://stackoverflow.com/a/51571796
has answer: http://stackoverflow.com/a/51571796
downvote count: 1
type: Question
has title: add a single spaces in list containing characters
has answer: http://stackoverflow.com/a/51571558
has answer: http://stackoverflow.com/a/51571668
has answer: http://stackoverflow.com/a/51571398
tagged with: string
favorite count: 0
tagged with: python-3.x
has body: I am new to the programming. I have a list. List contains multiple spaces. All the multiple spaces should be replaced with single space. lis = ['h','e','l','l','','','','','o','','','','w'] output = ['h','e','l','l','','o','','w'] Could anyone tell how to do?
has answer: http://stackoverflow.com/a/51571587
accepted answer: http://stackoverflow.com/a/51571558
answer count: 5
tagged with: python

http://stackoverflow.com/comment/89987393
comment on: http://stackoverflow.com/a/51509189
has text: Round is one of the functions that will not backpropagate, though. :( When fitting, you will see either "An operation has None for gradient" or "None values not supported".
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51500873
type: UnansweredQuestion
has title: SQL connection (sybase driver) with python pandas
tagged with: python
has body: I'm trying to connect to a database with python. I'm not an expert in SQL, So I will put the parameters of my db Driver = Sybase jConnect 6.0 (com.sybase.jdbc4.SybDriver) URL = jdbc:sybase:Tds:slpdfrsiqq3401.fr.intranet:20301 Usename = myusername Password = mypassword Database = databasename Since I don't have the right to install the package sybase-python, I'm trying to do the job with available packages. This is my code : import pandas as pd import pyodbc from sqlalchemy import create_engine engine=create_engine("jdbc+sybase://myusername:mypassword@slpdfrsiqq3401.fr.intranet:20301/databasename") #Trying to creating engine to use then pd.read_sql_query() My code doesn't work and I have this error : "Can't load plugin: sqlalchemy.dialects:jdbc.sybase" Could anyone help me to fix the problem?
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89973420
tagged with: pandas
tagged with: sql
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51502415

http://stackoverflow.com/comment/90127849
type: QuestionComment
type: Comment
score: 1
has text: Yes, you are missing the fact, that dicts are atomic mappings, while you are trying to access a nested structure. Moreover, the `geometry` key is not even in a second-level dictionary: `X` is a mapping from strings to lists. `[row.get('x') for row in X['Deck'][0]['geometry']]`
comment on: http://stackoverflow.com/q/51581271

http://stackoverflow.com/q/51598822
score: 0
answer count: 1
tagged with: django-tables2
has body: I have a page with Bootstrap-style tabs that uses anchors. When I click a header field to sort one of the tables, the sorting works fine, but the result URL doesn't retain the original #anchor location and I am sent to a different tab. Original URL: http://localhost:8000/wakemeup/myaccount#reputation Actual Sort URL: http://localhost:8000/wakemeup/myaccount?sort=pointvalue Desired Sort URL: http://localhost:8000/wakemeup/myaccount#reputation?sort=pointvalue Problem How can I get the table sort headers to retain the original anchor location in the URL?
type: UnansweredQuestion
tagged with: python
tagged with: anchor
has title: Sort links don't retain page anchor in django-tables2
type: Question
has answer: http://stackoverflow.com/a/51784720
tagged with: sorting

http://stackoverflow.com/q/51573408
has answer: http://stackoverflow.com/a/51574141
tagged with: loops
downvote count: 1
answer count: 1
type: UnansweredQuestion
upvote count: 0
favorite count: 0
has title: project Euler #12 - Difference between the two codes' performance
type: Question
tagged with: python
has body: I have recently begun learning python and in order to familiarise myself with the concepts I began solving Euler's problem. I have been trying to solve Euler's problem number 12 however my code runs for a long period of time (Greater than 10 minutes and still running). I checked online and ran this piece of code, surprisingly it took only 11 seconds. But I am unable to understand the difference between the two. Really appreciate if someone could help me understand the difference my code #1: from time import time import math def divisors(n): n = int(n) sqrt = int(math.sqrt(n)) result = sum(2 for i in range(1, sqrt+1) if n%i == 0) for i in range(1, n+1): if i**2 == n: result = result - 1 return result i = 1 num = 0 a = 0 t = time() while a &lt; 500: num = num+i print(num, i) i = i+1 a = divisors(num) print(a) tt = time() - t print(tt) my code #2 from time import time import math def divisors(n): n = int(n) sqrt = int(math.sqrt(n)) for i in range(1, n+1): result = sum(2 for i in range(1, sqrt+1) if n%i == 0) if i**2 == n: result = result - 1 return result i = 1 num = 0 a = 0 t = time() while a &lt; 500: num = num+i print(num, i) i = i+1 a = divisors(num) print(a) tt = time() - t print(tt) Code which took 11 seconds: import math from time import time t = time() def divisors(n): number_of_factors = 0 for i in range(1, int(math.ceil(math.sqrt(n)))): if n % i == 0: number_of_factors +=2 else: continue return number_of_factors x=1 for y in range(2,1000000): x += y if divisors(x) &gt;= 500: print x break tt = time()-t print tt
score: -1
has comment: http://stackoverflow.com/comment/90113172
tagged with: numbers
has comment: http://stackoverflow.com/comment/90113354

http://stackoverflow.com/q/51502851
type: Question
tagged with: pymysql
tagged with: amazon-web-services
has answer: http://stackoverflow.com/a/51503976
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
tagged with: python
has body: try: engine = create_engine('mysql+pymysql:///mysqladmin:***@***.us-west-2.rds.amazonaws.com:3306/peopledb') print "Opened database successfully"; except Exception as e: print("Error during connection: ", str(e)) print engine.table_names() I am attempting to use SQLAlchemy and PyMySQL to connect to a database in AWS RDS. The above code errors on the final line, when I access engine.table_names(). The error I receive is: sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 10061] No connection could be made because the target machine actively refused it)") Obviously I am not trying to connect to my localhost, I am connecting/connected to a remote host. Also I was able to successfully connect and access the database using native PyMySQL commands, this issue has to do with SQLAlchemy. Thanks in advance!
score: 2
has title: SQLAlchemy and PyMySQL refusing connection to 'localhost' after connecting to AWS RDS
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51503976
tagged with: sqlalchemy

http://stackoverflow.com/comment/90144979
has text: Please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) including a full traceback of the error message and a toy dataset that reproduces the error.
comment on: http://stackoverflow.com/q/51589814
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51598902
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90163873
upvote count: 5
answers question: http://stackoverflow.com/q/51598770
has body: Using the string accessor is converting your numbers to NaN, it is happening before you even try to use isnumeric: s = pd.Series([100, 50, 0, 'foo', 'bar', 'baz']) s.str[:] 0 NaN 1 NaN 2 NaN 3 foo 4 bar 5 baz dtype: object So the NaN's remain when you use isnumeric. Use astype first instead: s.astype(str).str.isnumeric() 0 True 1 True 2 True 3 False 4 False 5 False dtype: bool
score: 5

http://stackoverflow.com/a/51557146
type: Answer
answers question: http://stackoverflow.com/q/51556953
has body: It seems that your issue might be to do with the way your times are stored. If they are of time or datetime dtypes then the following should work nicely for you. Set Time as the index and simply call plot. Pandas sets the index as the x-axis by default. df.Time = df.Time.dt.time df.set_index('Time').plot() However, by the looks of your code, they are not. We can pass these as datetimes first, and then convert them to times (if needed). This can be done using pd.to_datetime as follows, df.Time = pd.to_datetime(df.Time).dt.time df.set_index('Time').plot() Note: This will default to using today's date to add to the datetime. However this is then dropped when converting to a Time dtype.
downvote count: 0
type: AcceptedAnswer
score: 8
upvote count: 8
accepted answer of: http://stackoverflow.com/q/51556953

http://stackoverflow.com/q/51602796
has answer: http://stackoverflow.com/a/51602940
tagged with: python
has body: I am creating a csv that will serve as a reference for acceptable nicknames for any given name. I then take an input name, look through each row to see if that name exists, and then return all other cells in the row, which are the nicknames. The input name does not have to be in the first column to have results returned. However, I created the list from a few different sources, and now I have duplicates. Is there a way to combine each row if any of the cells match up? Solutions in Excel/VBA/Python would be great. Example rows from csv: a b c d steven steve abigail abby abby gail stephen steve steph abraham ab abe Desired output: a b c d steven steve stephen steph abigail abby abby gail abraham ab abe
has title: Combine Rows if a Cell Value is Shared
type: AnsweredQuestion
score: 1
tagged with: excel
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/51602940
has comment: http://stackoverflow.com/comment/90171887
answer count: 1
tagged with: vba
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/90022459
type: Comment
has text: thanks for you help, pd.to_datetime fixed the problem.
type: AnswerComment
comment on: http://stackoverflow.com/a/51524368
score: 0

http://stackoverflow.com/q/51633187
type: Question
tagged with: try-catch
score: 3
upvote count: 3
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/51633578
tagged with: python
has title: Should I define try-except in module where function is defined or in module where it is called in Python?
possible better answer: http://stackoverflow.com/a/51633292
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51633292
has answer: http://stackoverflow.com/a/51633486
accepted answer: http://stackoverflow.com/a/51633486
has body: Let's say I have the following 2 modules: a.py: def connect(): bla bla bla.. b.py: from a import connect connect() should I define try-except clause for connect() in module a or b? So a.py: def connect(): try: bla bla bla.. except: bla bla bla.. or b.py: from a import connect try: connect() except: bla bla bla.. ? Btw, what would happen I have 'nested' try-except? a.py: def connect(): try: bla bla bla.. except ValueError: bla bla bla.. b.py: from a import connect try: connect() except Exception, e: bla bla bla..

http://stackoverflow.com/a/51631176
downvote count: 0
type: Answer
score: 22
has body: You must use one of the geometry managers for that: here with grid: import tkinter as tk root = tk.Tk() b1 = tk.Button(root, text='b1') b2 = tk.Button(root, text='b2') b1.grid(column=0, row=0) # grid dynamically divides the space in a grid b2.grid(column=1, row=0) # and arranges widgets accordingly root.mainloop() there using pack: import tkinter as tk root = tk.Tk() b1 = tk.Button(root, text='b1') b2 = tk.Button(root, text='b2') b1.pack(side=tk.LEFT) # pack starts packing widgets on the left b2.pack(side=tk.LEFT) # and keeps packing them to the next place available on the left root.mainloop() The remaining geometry manager is place, but its use is sometimes complicated when resizing of the GUI occurs.
answers question: http://stackoverflow.com/q/51631105
has comment: http://stackoverflow.com/comment/90226531
has comment: http://stackoverflow.com/comment/90226461
accepted answer of: http://stackoverflow.com/q/51631105
upvote count: 22
type: AcceptedAnswer

http://stackoverflow.com/a/55841447
score: 1
answers question: http://stackoverflow.com/q/51608482
upvote count: 1
type: Answer
downvote count: 0
has body: def main(model=None, output_dir=r'model', n_iter=100): """Load the model, set up the pipeline and train the entity recognizer.""" if model is not None: nlp = spacy.load(model) # load existing spaCy model print("Loaded model '%s'" % model) else: nlp = spacy.blank("en") # create blank Language class print("Created blank 'en' model") # create the built-in pipeline components and add them to the pipeline # nlp.create_pipe works for built-ins that are registered with spaCy if "ner" not in nlp.pipe_names: ner = nlp.create_pipe("ner") nlp.add_pipe(ner, last=True) # otherwise, get it so we can add labels else: ner = nlp.get_pipe("ner") # add labels for _, annotations in TRAIN_DATA: for ent in annotations.get("entities"): ner.add_label(ent[2]) # get names of other pipes to disable them during training other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "ner"] with nlp.disable_pipes(*other_pipes): # only train NER # reset and initialize the weights randomly – but only if we're # training a new model if model is None: nlp.begin_training() for itn in range(n_iter): random.shuffle(TRAIN_DATA) losses = {} # batch up the examples using spaCy's minibatch batches = minibatch(TRAIN_DATA, size=compounding(4.0, 32.0, 1.001)) for batch in batches: texts, annotations = zip(*batch) nlp.update( texts, # batch of texts annotations, # batch of annotations drop=0.5, # dropout - make it harder to memorise data losses=losses, ) print("Losses", losses) # test the trained model for text, _ in TRAIN_DATA: doc = nlp(text) print("Entities", [(ent.text, ent.label_) for ent in doc.ents]) print("Tokens", [(t.text, t.ent_type_, t.ent_iob) for t in doc]) # save model to output directory if output_dir is not None: output_dir = Path(output_dir) if not output_dir.exists(): output_dir.mkdir() nlp.to_disk(output_dir) print("Saved model to", output_dir) then, load the same model: print("Loading from", output_dir) nlp2 = spacy.load(output_dir) doc = nlp2("&lt;your any text&gt;") print("Entities", [(ent.te…

http://stackoverflow.com/comment/90140710
score: 1
has text: What are the permissions for the content of `/home/uay/anaconda3`? Everything owned and read and writable for your user?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51587727

http://stackoverflow.com/comment/90176215
score: 1
comment on: http://stackoverflow.com/q/51605360
type: Comment
type: QuestionComment
has text: use single quote while using static tag i.e `href="{% static '/appointments/css/all.css/' %}"`

http://stackoverflow.com/a/51560835
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51560689
type: Answer
answers question: http://stackoverflow.com/q/51560689
has comment: http://stackoverflow.com/comment/90088748
has body: You are trying to use lists as the keys in your dict, which is not possible because lists are mutable and not hashable. Instead, use the strings by iterating through the values: sectores = {i: k for k, v in sectores.items() for i in v} Then, you can use pd.Series.map and df['sectores']=df['district'].map(sectores) should work
upvote count: 1
score: 1

http://stackoverflow.com/comment/90031255
has text: I'm not sure if Django sets default in the DB. Try saving the form and see if the default works.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51531399
type: QuestionComment

http://stackoverflow.com/comment/90119501
type: AnswerComment
type: Comment
has text: This doesn't work. It says, "TypeError: Fields may not be added to Form instances, only classes." But perhaps I misunderstood as I declared the field in the previous scope and then redefined -- are only defining it when you get a default arg (I need this field to be present no matter what - the same form is used for add/edit but default should only be populated on add which is standard behavior)? I'd be happy with a means to simply populate the value data only when the form is being used to add a new record as well - I don't have to use default constructor option.
comment on: http://stackoverflow.com/a/51576986
score: 0

http://stackoverflow.com/q/51513603
score: 1
has body: In a Jupyter notebook, I want to use a python code to generate some markdown cells if some conditions are met. I use Ipython.display.Mardown. It works fine if no conditions are given, but fails to display anything if a condition is given. Here is a minimal example : In cell 1, a code that generates the expected Markdown: from IPython.display import display, Markdown Markdown(""" # First test Here, Markdown is used outside a condition test \n It works as I expect """) In cell 2, a code which generates no output cell: SHOW=True if SHOW: Markdown(""" # Second test Here, Markdown is used inside a condition test \n It won't show """) Using the Ipython.display.display function, the string shows in the output but in a raw form. In cell 3, a code which generates an output cell but the string is not interpreted as a Markdown: SHOW=True if SHOW: display(Markdown(""" # Third test Here, I also use the display function. \n It kind of helps but won't show as I expect """))
upvote count: 1
type: Question
answer count: 1
downvote count: 0
has title: generate Markdown from code with condition
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52825137
tagged with: python
tagged with: jupyter-notebook

http://stackoverflow.com/q/51591776
answer count: 0
downvote count: 0
score: 1
has body: i am new to python.And i was trying to use mitmdump to crawl an app and use mongodb to store datus. But...I found no answer on google, and i got no idea what to do... my Windows10 platform. I assume whether windows doesnt support it D:\Users\Administrator\Desktop\Python>mitmdump -s ScriptsTest.py Loading script ScriptsTest.py Addon error: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Roaming\Python\Python36\site- packages\mitmproxy\addonmanager.py", line 42, in safecall yield File "C:\Users\Administrator\AppData\Roaming\Python\Python36\site- packages\mitmproxy\addons\script.py", line 102, in loadscript ctx.master.addons.register(ns) File "C:\Users\Administrator\AppData\Roaming\Python\Python36\site- packages\mitmproxy\addonmanager.py", line 161, in register self.master.commands.collect_commands(a) File "C:\Users\Administrator\AppData\Roaming\Python\Python36\site- packages\mitmproxy\command.py", line 144, in collect_commands self.add(o.command_path, o) File "C:\Users\Administrator\AppData\Roaming\Python\Python36\site- packages\mitmproxy\command.py", line 151, in add self.commands[path] = Command(self, path, func) File "C:\Users\Administrator\AppData\Roaming\Python\Python36\site- packages\mitmproxy\command.py", line 51, in init sig = inspect.signature(self.func) File "d:\users\administrator\anaconda3\lib\inspect.py", line 3033, in signature return Signature.from_callable(obj, follow_wrapped=follow_wrapped) File "d:\users\administrator\anaconda3\lib\inspect.py", line 2783, in from_callable follow_wrapper_chains=follow_wrapped) File "d:\users\administrator\anaconda3\lib\inspect.py", line 2183, in _signature_from_callable raise TypeError('{!r} is not a callable object'.format(obj)) TypeError: MongoClient(host=['127.0.0.1:27017'], document_class=dict, tz_aware=False, connect=True) is not a callable object here is my script code import json import pymongo from mitmproxy import ctx client = pymongo.MongoClient(host='127.0.0.1') db = client['igetget'…
type: Question
has title: mitmdump not working with pymongo
upvote count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90241547
comment on: http://stackoverflow.com/a/51638570
type: AnswerComment
type: Comment
score: 2
has text: Really, they should just do `sheet_list = wb.sheet_names` instead of creating a list of lists, then un-nesting it.

http://stackoverflow.com/a/51613528
type: Answer
score: 2
upvote count: 2
has body: I don't think you're cloning the correct url. You're getting the same "could not unpack" error as the question you linked, hinting that it might be the exact same problem. Try: pip install git+https://github.com/pdfminer/pdfminer.six.git or pip install git+git://github.com/pdfminer/pdfminer.six.git Typically git repos end with .git, and when I added it to my clipboard from github that's the url I got. You could also try pip install pdfminer.six, which I copied directly from their documentation: https://github.com/pdfminer/pdfminer.six/blob/master/README.md
answers question: http://stackoverflow.com/q/51613291
has comment: http://stackoverflow.com/comment/90193188
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51613291
downvote count: 0

http://stackoverflow.com/a/52393629
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51532359
type: Answer
answers question: http://stackoverflow.com/q/51532359
upvote count: 1
score: 1
has body: There are couple of ways to do it: Plot it against a normal fitted probability distribution. Like: plt.hist(x, norm.pdf(x,mu, std)) Compare kdepdf distribution with a uniform random dataset using something like Q-Q plot for both dataset. Use chi square test, be cautious with the bin size you choose. Basically, this tests whether the number of draws that fall into various intervals is consistent with a uniform random distribution.chi square test. Basically, this tests whether the number of draws that fall into various intervals is consistent with a uniform random distribution.

http://stackoverflow.com/a/51509321
has body: There are a lot of creative ways to go about edge detection for high frequency edges (like sperm tails for example) I recommend cv2.Canny() for general edge detection - you will have to play around with the inputs for your specific application. Alternatively, you can do a difference of gaussian, where you take cv2.GaussianBlur() with two different sigmas and take the difference (https://en.wikipedia.org/wiki/Difference_of_Gaussians) i.e, blur1 = cv2.GaussianBlur(im, (5,5), sigmaX_1, sigmaY_1) blur2 = cv2.GaussianBlur(im, (5,5), sigmaX_2, sigmaY_2) DoG_edge = blur1 - blur2 One final possibility is that you could also try some histogram manipulation to enhance the tails of the sperm.
type: Answer
answers question: http://stackoverflow.com/q/51491771
has comment: http://stackoverflow.com/comment/89991405
score: 0

http://stackoverflow.com/a/51585929
has comment: http://stackoverflow.com/comment/90137902
type: Answer
has body: token auth in settings.py JWT_AUTH = { # Authorization:Token xxx 'JWT_AUTH_HEADER_PREFIX': 'Token', } the default JWT_AUTH_HEADER_PREFIX is JWT. JWT_AUTH_HEADER_PREFIX You can modify the Authorization header value prefix that is required to be sent together with the token. The default value is JWT. This decision was introduced in PR #4 to allow using both this package and OAuth2 in DRF. Another common value used for tokens and Authorization headers is Bearer. Default is JWT. Doc is here.
upvote count: 10
type: AcceptedAnswer
score: 10
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51585240
answers question: http://stackoverflow.com/q/51585240

http://stackoverflow.com/comment/89988062
has text: @Felix thank you! I posted some example output.. However I adjusted it and added Mangohero1's most recent addition and it now says "AttributeError: 'list' object has no attribute 'close" and does the min, max and avg calcs
comment on: http://stackoverflow.com/q/51508906
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51540331
downvote count: 0
linked to: http://stackoverflow.com/q/6903557
type: Question
has answer: http://stackoverflow.com/a/51541582
tagged with: pyspark
accepted answer: http://stackoverflow.com/a/51540774
upvote count: 3
has body: I want to separate the column of a Spark DataFrame into 2 different columns depending on the first appearance of a character, which in this case is an underscore ("_"). I have prepared a 100% reproducible example: The mock Spark DataFrame is: df = spark.createDataFrame( [ (1, 1.8, 'newyork_3434_north'), (4, 2.6, 'la_432432432_south'), (6, 3.3, 'boston_234324_east'), (8, 4.1, 'detroit_6757_west'), (2, 5.7, 'miami_133123_north'), (3, 6.2, 'atlanta_093394_west'), (1, 6.1, 'houston_87342_east') ], ('ranking', "coordenate", "city") ) The above code creates a table like the following one: ranking coordenate city 1 1.8 newyork_3434_north 4 2.6 la_432432432_south 6 3.3 boston_234324_east 8 4.1 detroit_6757_west 2 5.7 miami_133123_north 3 6.2 atlanta_093394_west 1 6.1 houston_87342_east What I would like to do is separating the column city in 2 different columns depending on the location of the first underscore from left to right. The final desired table would be then something like: ranking coordenate city code 1 1.8 newyork 3434_north 4 2.6 la 432432432_south 6 3.3 boston 234324_east 8 4.1 detroit 6757_west 2 5.7 miami 133123_north 3 6.2 atlanta 093394_west 1 6.1 houston 87342_east I have seen several threads about this topic, but they do not speak about the first appearance of a character (link_1, link_2, etc.), but splitting by all specific characters that are on a string; or splitting by specific position of the character in the string. I have also tried Python Pandas approach but as expected, it is not applicable in PySpark by extension or analogy (link_3) Thank you in advance for your help.
answer count: 2
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/90048750
has comment: http://stackoverflow.com/comment/90049005
linked to: http://stackoverflow.com/q/39235704
has answer: http://stackoverflow.com/a/51540774
favorite count: 0
possible better answer: http://stackoverflow.com/a/51541582
has comment: http://stackoverflow.com/comment/90048523
has comment: http://stackoverflow.com/comment/90048395
has title: Separate a string column depending on first character appearance
linked to: http://stackoverflow.com/q/41283478
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90048942
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/64171308
downvote count: 0
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51488470
has body: One liner using subset parameter from pandas dropna. df.dropna(subset=[n for n in df if n != 'column_to_keep'], inplace=True) column_to_keep is the column where you want nan to be preserved.

http://stackoverflow.com/comment/90209606
type: AnswerComment
has text: What do you mean? What values do you get? What do you expect?
type: Comment
comment on: http://stackoverflow.com/a/51621728
score: 0

http://stackoverflow.com/comment/90288969
has text: Here is a sample in Node.js doing what you're trying to do: https://github.com/dialogflow/fulfillment-firestore-nodejs
comment on: http://stackoverflow.com/q/51621553
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/51577587
type: Answer
accepted answer of: http://stackoverflow.com/q/51577561
answers question: http://stackoverflow.com/q/51577561
score: 0
type: AcceptedAnswer
has body: So it depends on what your requirements are...but you should check the value of behavior and limit before setting: if behavior is not None: row.behavior = behavior if limit is not None: row.limit = limit However, you might consider that there will be times when you WANT to be able to set those fields to None. In that case you could set your parameters to a specific object by default. Example: no_value = object() def set_warn_settings(serverID, behavior=no_value, limit=no_value): ... if behavior is not no_value: row.behavior = behavior if limit is not no_value: row.limit = limit ...

http://stackoverflow.com/a/51544431
score: 2
has body: Like this: data = BeautifulSoup(your_html, 'html.parser') clean_data = (data.find_all('p'),data.find_all('ruby')) print(clean_data) To get the content/text within those tags: p_text = clean_data.find_all('p').get_text() Let me know if this works.
has comment: http://stackoverflow.com/comment/90069584
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51544103
type: Answer
has comment: http://stackoverflow.com/comment/90070143

http://stackoverflow.com/a/51550676
has comment: http://stackoverflow.com/comment/90068676
has body: Try to use b__bags lookup in annotation: from django.db.models import Count A.objects.annotate(bags_count=Count('b__bags'))
answers question: http://stackoverflow.com/q/51550581
has comment: http://stackoverflow.com/comment/90071812
accepted answer of: http://stackoverflow.com/q/51550581
has comment: http://stackoverflow.com/comment/90071994
has comment: http://stackoverflow.com/comment/90068726
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90071623
has comment: http://stackoverflow.com/comment/90071695
has comment: http://stackoverflow.com/comment/90068758
upvote count: 2
has comment: http://stackoverflow.com/comment/90068797
type: Answer
score: 2

http://stackoverflow.com/comment/89951466
type: QuestionComment
comment on: http://stackoverflow.com/q/51488228
score: 0
has text: It would be useful to know which is the failing line... Is this `name, sequence = seq_record.id, str(seq_record.seq)`?
type: Comment

http://stackoverflow.com/comment/90088263
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51560655
has text: So, how can I save `hdr` as well as rest of the data?

http://stackoverflow.com/q/51627294
has comment: http://stackoverflow.com/comment/90220049
answer count: 3
has body: I want to create an object of a class based on value of a field. For eg: if r_type == 'abc': return Abc() elif r_type == 'def': return Def() elif r_type == 'ghi': return Ghi() elif r_type == 'jkl': return Jkl() What is a pythonic way to avoid if else here. I was thinking to create a dictionary with r_type being key and classname being value, and do a get of the value and instantiate, is it a proper way, or there is something better idiomatic way in python?
downvote count: 0
has answer: http://stackoverflow.com/a/51627446
favorite count: 0
accepted answer: http://stackoverflow.com/a/51627424
tagged with: python
tagged with: design-patterns
has title: Avoid if else to instantiate a class - python
type: AnsweredQuestion
tagged with: conditional-statements
has comment: http://stackoverflow.com/comment/90219744
has comment: http://stackoverflow.com/comment/90219309
tagged with: switch-statement
type: Question
possible better answer: http://stackoverflow.com/a/51627533
score: 5
has answer: http://stackoverflow.com/a/51627533
upvote count: 5
has answer: http://stackoverflow.com/a/51627424
linked to: http://stackoverflow.com/q/245192

http://stackoverflow.com/q/51493021
answer count: 1
has body: I just want to insert the table list into the mysql database table. Here's the code: import mysql.connector # Open database connection a = [('apq3'), ('aquaporin')] b = ["skin"] c = ["down-regulated", "down regulation", "down regulate"] def input_mysql(a1, b1, c1): db = mysql.connector.connect(user='root', password='xxxx', host='localhost', database='crawling') #sql = 'INSERT INTO crawling_result(search_content, content) VALUES(%s)' sql_target_a = 'INSERT INTO a (term) VALUES(%s)' sql_target_b = 'INSERT INTO b (term) VALUES(%s)' sql_target_c = 'INSERT INTO c (term) VALUES(%s)' cursor=db.cursor() cursor.execute(sql_target_a, a1) cursor.execute(sql_target_b, b1) cursor.execute(sql_target_c, c1) db.commit() db.close() a_content = a b_content = b c_content = c input_mysql (a_content, b_content, c_content) After running, it keeps showed that "mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement". Can some one help me?
score: 0
has answer: http://stackoverflow.com/a/51493075
tagged with: python
type: AnsweredQuestion
tagged with: sql-insert
tagged with: mysql
type: Question
has title: mysql insert table by python
accepted answer: http://stackoverflow.com/a/51493075

http://stackoverflow.com/q/51564420
has comment: http://stackoverflow.com/comment/90095849
has body: I am curious whether it is possible to keep track of the number of times a specific .py file is ran without ever reading and writing to/from a file. This thread: how can i count how many time program has been executed in python uses atexit module to update a json file and log the number of times the script has ran in its lifetime. I guess this type of data must be logged in a file?
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/30961310
type: Question
has comment: http://stackoverflow.com/comment/90099006
has answer: http://stackoverflow.com/a/51565366
downvote count: 0
tagged with: counting
tagged with: execution
has comment: http://stackoverflow.com/comment/90095911
tagged with: operating-system
has comment: http://stackoverflow.com/comment/90096651
answer count: 1
has title: Is it possible to keep track of how many times a Python Script has been ran without writing to a file?
tagged with: atexit
favorite count: 0
linked to: http://stackoverflow.com/q/716011
accepted answer: http://stackoverflow.com/a/51565366
upvote count: 2
tagged with: python

http://stackoverflow.com/a/51563261
has comment: http://stackoverflow.com/comment/90093563
has comment: http://stackoverflow.com/comment/90094604
answers question: http://stackoverflow.com/q/51563203
has body: Is table initialized somewhere? You need to initialize it. UPDATE: In the function insert check if the followings actually exist every time the loop iterates? - tablilla[field][0] - textFields[field] - tablilla.loc[r, field] I suggest you comment out each for loop one by one and see what part causes the error.
score: 0
has comment: http://stackoverflow.com/comment/90093758
has comment: http://stackoverflow.com/comment/90094096
type: Answer

http://stackoverflow.com/a/51574970
type: AcceptedAnswer
type: Answer
has body: For avoiding exhausting checks, you need to restructure your code to smaller parts and introduce control structures, such as while. In my example I created two functions get_data_set() and check_months(). Function get_data_set() loops infinitely, until the input is correct. That means the number of words is divisible by 4 and every 4th word is a months name. Function check_months() has one argument - data_set and checks it if every 4th word is month. If it is, returns True, in not False. Example is bellow: import re def get_data_set(): while True: data_input = input("Please input data.\n") data_set = re.sub(r"[^\w]", " ", data_input).split() if len(data_set) % 4 != 0: print("That\'s not a valid input. For formatting help, type \'help\'.'") continue if check_months(data_set) == False: print("That\'s not a valid input.'") continue return data_set def check_months(data_set): for word in data_set[::4]: if word not in ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"): return False return True data_set = get_data_set() print('Valid data set!') print(data_set) Output: Please input data. JUL ENT 20 K AUG SAL 2 M MAR OTR 200 K Valid data set! ['JUL', 'ENT', '20', 'K', 'AUG', 'SAL', '2', 'M', 'MAR', 'OTR', '200', 'K']
answers question: http://stackoverflow.com/q/51574675
accepted answer of: http://stackoverflow.com/q/51574675
score: 0

http://stackoverflow.com/a/51612502
downvote count: 0
has body: You can use process shared queue from multiprocessing module. The code may look something like this: from multiprocessing import Process, Queue def executor(queue): queue.put({"key": "value"}) def run(queue): process = Process(target=executor, args=(queue,)) process.start() process.join() print(queue.get()) if __name__ == '__main__': run(Queue()) Output: &gt;&gt;&gt; {'key': 'value'} There are also proxy objects for sharing data between multiple processes.
type: Answer
accepted answer of: http://stackoverflow.com/q/51610295
answers question: http://stackoverflow.com/q/51610295
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/51608861
answers question: http://stackoverflow.com/q/51607904
type: Answer
has body: Use the os module Ex: import os script1Path = os.path.dirname(__file__) script2Path = os.path.join(script1Path, "folder2", "script2.py") print(script2Path)
score: 0

http://stackoverflow.com/q/51635285
has body: So far I have: (for context, I am parsing lines of code) for line in file.readlines(): pattern = r'"((\\\\"|[^"])*")|\'((\\\\\'|[^\'])*\')' matches = re.search(pattern, line) however doing matches.group() only gives the first string in code that is caught, how can I get multiple strings in a single line.
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4697882
type: Question
has comment: http://stackoverflow.com/comment/90235605
has comment: http://stackoverflow.com/comment/90235240
has title: Get all strings surrounded by double quotes or single quotes in line with python
score: 0
duplicate of: http://stackoverflow.com/q/4697882
tagged with: python
tagged with: regex
tagged with: python-3.x

http://stackoverflow.com/comment/90114745
type: Comment
comment on: http://stackoverflow.com/a/51574479
has text: do I have to include the extension in the {testfile.save}?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51485597
has comment: http://stackoverflow.com/comment/89941290
answer count: 2
has comment: http://stackoverflow.com/comment/89941768
downvote count: 0
has body: The name of my function is getTile.py. I am trying to use the argparse function in python to parse stuff from the command line. However, the program can't get past the second line of my script. It keeps coming back in the command line with this: ./getTile.py: line 19: syntax error near unexpected token `(' ./getTile.py: line 19: `parser = argparse.ArgumentParser() I am following the argparse gentle tutorial on python.org. Also, this is my program. import argparse parser = argparse.ArgumentParser() parser.add_argument("X-coordinate", help="Please put in the X-coordinate of your point.", type=float) xCoordinate=float(parser.X-coordinate) def aFunction(var1): var1 = var1+5 print(a) afunction(xCoordinate)
favorite count: 0
has title: Syntax Error while using parse
tagged with: argparse
tagged with: python
has comment: http://stackoverflow.com/comment/89940343
tagged with: command-line
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89941859
has comment: http://stackoverflow.com/comment/89940347
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/89941042
type: Question
has comment: http://stackoverflow.com/comment/89942118
has answer: http://stackoverflow.com/a/53998062
score: 1
has answer: http://stackoverflow.com/a/51486400

http://stackoverflow.com/comment/90198527
score: 0
type: AnswerComment
has text: I don´t know exactly, why you want to inverse transfrom the data. Regarding the validation, yes right.
type: Comment
comment on: http://stackoverflow.com/a/51608754

http://stackoverflow.com/q/51500509
downvote count: 0
accepted answer: http://stackoverflow.com/a/51501070
has comment: http://stackoverflow.com/comment/90056407
answer count: 1
has title: How to cluster multiple rows with at least one same value in python?
has body: I have a pandas dataframe (150,000 rows and 9 columns) like: user|phone1|phone2|phone3 ----+------+------+------ A| 123| 1111|66 B| 456| 1111|77 C| 123| 2222|77 D| 456| 2222|88 E| 789| 5555|0 User A has the same phone1 number with user C so A and C is a group. User B has the same phone2 number with C, so B and C is a group. Thus A,B,C is a group. The logic is same for all the users. In this example, [A,B,C,D] is a group, because they have at least one same value by any two of them. [E] is another group. How can I get final result like: {group1:[A,B,C,D], group2:[E]} This is my try: First, group by each columns with same value,any put user as a group, like list_1 (phone1) = [[A,C],[B,D],[E]] list_2 (phone2) = [[A,B],[C,D],[E]] For each item in list_1 search in list_2. If two items have same value, then add items from list_2 on items from list_1, eg, [A,C]+[A,B] and at last,pop [A,B] in list_2 This is my code: for m in range(0,len(list_1)): drop_list = [] for n in range(0,len(list_2)): if if_common(list_1[m], list_2[n]) == True: list_1[m] = list(set(list_1[m]+list_2[n])) drop_list.append(n) for i in drop_list: list_2.pop(i) but its too slow, I have nearly 100000 groups in each columns. Is there any quick way to realize this?
favorite count: 0
tagged with: machine-learning
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/9110837
has answer: http://stackoverflow.com/a/51501070
type: Question
has comment: http://stackoverflow.com/comment/89969514
tagged with: algorithm

http://stackoverflow.com/comment/90176803
has text: @ArpitAcharya yes
comment on: http://stackoverflow.com/a/51605642
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51505464
answer count: 2
has answer: http://stackoverflow.com/a/63206466
tagged with: pyqt4
score: -1
has comment: http://stackoverflow.com/comment/89986675
tagged with: pyqt
has body: I am trying to display a loading gif while other code executes. I am very unfamiliar with PyQt and have tried following the code at this link, which seems to be the standard way of executing a gif. I only want the gif playing and do not want a button. Here is the code I am currently at, but it is very poor. self.movie = QMovie(coffeeloading.gif, self) size = self.movie.scaledSize() self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.movie_screen.setAlignment(Qt.AlignCenter) self.movie_screen = QLabel() main_layout = QVBoxLayout() main_layout.addWidget(self.movie_screen) self.setLayout(main_layout) self.movie.setCacheMode(QMovie.CacheAll) self.movie.setSpeed(100) self.movie_screen.setMovie(self.movie) self.movie.start() This is supposed to execute after a button press and fill up the whole screen of 240x320, but I dont have any idea how to do it. I have already read through many of the other stackoverflow and other links, but none of them seem to address how to complete this.
has answer: http://stackoverflow.com/a/51567365
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
linked to: http://stackoverflow.com/q/48441863
upvote count: 0
has title: Displaying Gif Loading in PyQt4
type: Question
has comment: http://stackoverflow.com/comment/90014548

http://stackoverflow.com/comment/89972877
has text: Your code should work. Are you sure you are not doing `log_df.str` somewhere (instead of `log_df['Product'].str`)? Or maybe you have *duplicated indexes* with this name `Product` (e.g. two columns with same name) ?
score: 4
comment on: http://stackoverflow.com/q/51502263
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51567306
score: 0
has comment: http://stackoverflow.com/comment/90107645
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51567134
accepted answer of: http://stackoverflow.com/q/51567134
has body: You need to import the Add function from foo.py Try if this works: foo.py: def Add(add1, add2): addout = add1 + add2 return addout bar.py: from foo import Add # not sure if you need a file path before foo (Example: folder.foo) # rest of the code result = Add(AN_INTEGER, ANOTHER_INTEGER) print(result) Edit: You might want to use * instead of Add if you want to import the whole foo.py

http://stackoverflow.com/q/51548826
favorite count: 0
tagged with: pandas
tagged with: python
has body: I have a some matrices which resemble a time series and I want to run a a kendall tau regression through each column and row combination. I can do this with the following code: import numpy as np import pandas as pd import scipy as sp import random #make some random data test = [] for i in range(50): m = np.random.random((50, 50)) test.append(m) #copy a matrix to repopulate with the tau value coef = test[0].copy() #copy to repopulate with a p-value p = test[0].copy() stacked = np.dstack(test) #loop through each pixel and run the trend test, output two matrix, one of slope and one of p-value for r in range(test[0].shape[0]): for c in range(test[0].shape[1]): pixel = list(stacked[r: r+1, c:c+1, :].flatten()) df = pd.DataFrame({"Values": pixel}) #reset the index to use as a independent variable df = df.reset_index(drop = True) #run the regression tau, p_value = sp.stats.kendalltau(df.index, df.Values) #update the copied matrices coef[r: r+1, c:c+1] = tau p[r: r+1, c:c+1] = p_value I am wondering if there is maybe a more efficient way to accomplish this task though as looping through every element in the stacked matrix seems like the incorrect way to go. Maybe there is a way to vectorize this even?
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: scipy
type: Question
tagged with: numpy
has title: Faster way to run kendall tau regression on stacked matrices?
score: 2
downvote count: 0

http://stackoverflow.com/comment/90196263
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51615437
score: 1
has text: Gotchu. Working on it

http://stackoverflow.com/q/51620789
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90276472
has body: I'm fairly new in Python and I want to load .mat files into python and plot multiple images that are 2D array. This is the code that I wrote. I was able to plot one image at the time, but when I loaded multiple .mat files (form of structure) into dict the form of array was different and I could not plot. 2D arrays. dataDir ="dir" i=1 mat=dict() sig1=dict() Sig=[] oct_struct=dict() for file in os.listdir( dataDir ) : mat[i]=sio.loadmat( dataDir+file ) oct_struct[i]=mat[i]['Raw_Image'] sig1[i]=oct_struct[i]['sig1matrix'] i+=1 Sig=np.array(sig1[1]-0.) This is how 2D array looks if I plot it from multiple dictionary [array([[array([[579, 519, 496, ..., 640, 699, 656], [550, 536, 505, ..., 633, 684, 616], [548, 549, 492, ..., 622, 630, 690], ..., [594, 532, 534, ..., 613, 527, 567], [574, 564, 535, ..., 565, 601, 644], [507, 534, 543, ..., 606, 614, 638]], dtype=uint16)]], dtype=object)] Error that I received by plotting above array: imgplot=plt.imshow(Sig,cmap='jet') error'Image data cannot be converted to float' This is how array looks if I extract array from one dict. array(array([[579, 519, 496, ..., 640, 699, 656], [550, 536, 505, ..., 633, 684, 616], [548, 549, 492, ..., 622, 630, 690], ..., [594, 532, 534, ..., 613, 527, 567], [574, 564, 535, ..., 565, 601, 644], [507, 534, 543, ..., 606, 614, 638]], dtype=uint16), dtype=object)
score: 0
has title: How to extract correct form of 2D array from dictionary in Python?
has comment: http://stackoverflow.com/comment/90285479
tagged with: python
answer count: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/90163291
score: 0
type: Comment
type: QuestionComment
has text: Are lists `c1`, `c2`, `output_row1`, and `output_row2` necessary? These are going to end up being large lists if `my_list` and `df` are large. If yes, using numpy for some of these should help if they are the same data types.
comment on: http://stackoverflow.com/q/51598605

http://stackoverflow.com/q/51507843
favorite count: 0
has body: I want my Python Flask server to send a GET Request to the GitHub REST API V3, asking for all commits messages in a Pull Request, and perhaps receive it as a single payload. Any suggestions on how I can approach this issue? Edit (additional explanation): The only thing I have tried that was successful was displaying the actual number of commit messages in a pull request. To actually display a listing of all of them is complex. This variable here --> x = jsonRequest["pull_request"]["commits"], would display commit list from /repos/:owner/:repo/pulls/:number/commits in the GitHub developer documentation. If I could display not just the list of commits as a count, but also all the messages included in it, that would be nice. Documentation found here: developer.github.com/v3/pulls/#response-4
has title: Sending a GET Request to GitHub API asking for a list of commit messages in a Pull Request
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89985359
tagged with: python
has comment: http://stackoverflow.com/comment/89986944
has answer: http://stackoverflow.com/a/51524713
upvote count: 1
downvote count: 1
type: Question
tagged with: server
tagged with: flask
score: 0
tagged with: api
has comment: http://stackoverflow.com/comment/89986718
answer count: 1
tagged with: github

http://stackoverflow.com/comment/90129506
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51581838
has text: My pleasuse. If you think that is sufficient, feel free to accept this answer.

http://stackoverflow.com/q/51568743
has comment: http://stackoverflow.com/comment/90107171
tagged with: python-2.7
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: macos
has answer: http://stackoverflow.com/a/51569152
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51569191
has answer: http://stackoverflow.com/a/51569191
type: Question
has body: I have Python 3.7 and I had a Python 2.7. But when I am using Python Launcher it uses 2.7 not 3.7. How to use Python 3.7? OS - Mac OS.
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90103713
has answer: http://stackoverflow.com/a/51568854
answer count: 3
accepted answer: http://stackoverflow.com/a/51568854
has title: Shell is selecting Python 2.7, but not 3.7

http://stackoverflow.com/comment/90081316
comment on: http://stackoverflow.com/q/51549641
score: 1
has text: Is `doc` a single document or a list of documents? `TfidfVectorizer.fit_transform()` expects [a list of documents](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html#sklearn.feature_extraction.text.TfidfVectorizer.fit_transform), not a single document. Maybe try `vectorizer.fit_transform([doc])`?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51623235
type: AcceptedAnswer
downvote count: 0
has body: Thanks to @David Maze for pointing me to the right direction I was checking for python-apt in the controller machine, not in the controlled machine. So I installed the package from the controller into the controlled machine using: $ ansible openvpn -m "apt name=python-apt state=latest" --become-user realtebo You can also use the following form, that does sudo apt-get update and wait for operator to enter the password. The user is the one logged in via ssh; so check your config. In my case, I'm using ssh keys; password login is disabled at all. $ ansible openvpn -m apt -a "update-cache=yes" --become --ask-become-pass Tip 1: To avoid this interaction is available the vault, but I've not tried it yet. Tip 2: Also, --ask-become-pass is not in the doc where you're probably looking for, at letter a; this is because the option is shortened in -K, uppercase, so look more down See the doc After ensuring that remotely the package python-apt is available, then the -C option started to work, exactly because now python-apt is available remotely. ansible openvpn -C -m "apt name=python state=latest" 192.168.1.225 | SUCCESS => { "cache_update_time": 1533077635, "cache_updated": false, "changed": false }
type: Answer
upvote count: 7
answers question: http://stackoverflow.com/q/51622712
score: 7
accepted answer of: http://stackoverflow.com/q/51622712

http://stackoverflow.com/a/51524513
upvote count: 1
downvote count: 0
has body: No, It is not possible with Selenium. The only way to achieve what you want to do is to use any automation tool that actually runs directly in the OS that you use.
type: Answer
answers question: http://stackoverflow.com/q/51524109
score: 1

http://stackoverflow.com/comment/89954986
type: Comment
comment on: http://stackoverflow.com/a/51492968
has text: oh, maybe I didnt understood well what you were asking, do you want to get ONLY the file with today's date ?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51622601
has comment: http://stackoverflow.com/comment/90210874
tagged with: python
has comment: http://stackoverflow.com/comment/90210822
has comment: http://stackoverflow.com/comment/90210580
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51624482
type: Question
tagged with: numpy
has body: I have matrix similar to this: 1 0 0 1 0 0 0 2 0 0 2 0 0 0 3 0 0 3 (Non-zero numbers denote parts that I'm interested in. Actual number inside matrix could be random.) And I need to produce vector like this: [ 1 1 2 2 3 3 ].T I can do this with loop: result = np.zeros([rows]) for y in range(rows): x = y // (rows // cols) # pick index of corresponded column result[y] = mat[y][x] But I can't figure out how to do this in vector form.
has comment: http://stackoverflow.com/comment/90210854
tagged with: vector
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/90210919
accepted answer: http://stackoverflow.com/a/51624482
has comment: http://stackoverflow.com/comment/90210484
has comment: http://stackoverflow.com/comment/90210779
has title: map matrix into specific vector with numpy
has comment: http://stackoverflow.com/comment/90210612

http://stackoverflow.com/comment/90012548
has text: no your code after the `else` is not check for errors
score: 0
comment on: http://stackoverflow.com/q/51521075
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51577056
has body: I have been trying to send the user form data such as date, time, quantity etc to the DB, and I have been getting user data in the DB. But the problem is that code is repeating itself from some point and doing whole procedure twice. Here is App.py file @app.route('/takeOrder') def takeOrder(): return render_template('order.html') @app.route('/takeOrder', methods = ['POST','GET']) def order(): if request.method == 'POST': _userEmail = str(escape(session['email'])) _chefEmail = 'chef@gmail.com' _eventDate = request.form['eventDate'] _eventTime = request.form['eventTime'] _description = request.form['description'] _quantity = request.form['quantity'] _amount = 100 _recipeName = 'aloo parotha' loggerClass.info('&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;' + _userEmail) _customerAddressID = orderDB.getAddressID(_userEmail) loggerClass.info('&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;' + _customerAddressID) _chefAddressID = orderDB.getAddressID(_chefEmail) loggerClass.info('&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;' + _chefEmail) _customerID = orderDB.getCustomerID(_customerAddressID) loggerClass.info('&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;' + _customerID) _chefID = orderDB.getChefID(_chefAddressID) loggerClass.info('&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;' + _chefID) _customerName = orderDB.getCustomerName(int(_customerAddressID)) loggerClass.info('&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;' + _customerName) _chefName = orderDB.getChefName(int(_chefAddressID)) loggerClass.info('&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;' + _chefName) orderFormData = OrderEmailData.OrderFormData(_userEmail, _chefEmail, _customerID, _chefID, _recipeName, _eventDate, _eventTime, _description, _quantity, _amount) orderNameData = OrderEmailData.OrderNamesData(_customerName, _chefName) insertUserOrder = orderDB.insertOrder(orderFormData) loggerClass.info('&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;…
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90119834
score: 1
tagged with: mysql
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90119794
tagged with: database
has title: Flask: data repeating when taking form data from user
tagged with: flask

http://stackoverflow.com/q/51616550
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/90201661
has comment: http://stackoverflow.com/comment/90200469
answer count: 0
has comment: http://stackoverflow.com/comment/90201575
has comment: http://stackoverflow.com/comment/90198880
type: Question
has comment: http://stackoverflow.com/comment/90198715
tagged with: neural-network
has comment: http://stackoverflow.com/comment/90198783
score: 0
has title: Error when checking input: expected lstm_4_input to have 3 dimensions, but got array with shape (8, 23, 1, 16)
has comment: http://stackoverflow.com/comment/90200515
has comment: http://stackoverflow.com/comment/90198752
has comment: http://stackoverflow.com/comment/90200316
type: UnansweredQuestion
has body: I've been running into this error and I am quite unsure how to solve it. I know that my input is expecting 3 dimensions, but I have a shape of 4. Can someone guide me how I can narrow it down? I've read post where there are 3 dimensions, and array shapes less than 3 or so.. But I haven't seen a solution on overflow with a bigger shape and dimension... def generator(batch_size,from_list_x,from_list_y): assert len(from_list_x) == len(from_list_y) total_size = len(from_list_x) while True: #keras generators should be infinite for i in range(0,total_size,batch_size): yield np.array(from_list_x[i:i+batch_size]), np.array(from_list_y[i:i+batch_size]) model = Sequential() model.add(LSTM(1, input_shape=(1,16),return_sequences=True)) model.add(Flatten()) model.add(Dense(1, activation='tanh')) model.compile(loss='mae', optimizer='adam', metrics=['accuracy']) model.summary() # fit network pyplot.figure(figsize=(16, 25)) # for i in range(len(train)): history = model.fit_generator(generator(8, train_X, train_Y), epochs=20, steps_per_epoch = 7, verbose=0, shuffle=True) print('loss ', str(i), history.history['loss'][len(history.history['loss'])-1],'\n') I am getting an error with this line : history = model.fit_generator(generator(8, train_X, train_Y), epochs=20, steps_per_epoch = 7, verbose=0, shuffle=True) Traceback: ValueError Traceback (most recent call last) &lt;ipython-input-41-17bb96b50588&gt; in &lt;module&gt;() 2 pyplot.figure(figsize=(16, 25)) 3 # for i in range(len(train)): ----&gt; 4 history = model.fit_generator(generator(8, train_X, train_Y), epochs=20, steps_per_epoch = 7, verbose=0, shuffle=True) 5 6 # plot history C:\ProgramData\Anaconda3\envs\dh\lib\site-packages\keras\legacy\interfaces.py in wrapper(*args, **kwargs) 89 warnings.warn('Update your `' + object_name + 90 '` call to the Keras 2 API: ' + signature, stacklevel=2) ---&gt; 91 return func(*args, **kwargs) 92 wrapper._original_function = func 93 return wrapper C:\ProgramData\Anaconda3\envs\dh\lib\site-packa…

http://stackoverflow.com/a/51623558
answers question: http://stackoverflow.com/q/51610771
type: Answer
score: 1
upvote count: 1
has body: Put conftest.py file in a location which is at the same level as your test files directory (func) or one of the parent directories of your test case files in your project workspace (tests or root dir of your project in your case). You currently have it in the sibling directory tasks which pytest will not scan.
downvote count: 0

http://stackoverflow.com/a/51493393
accepted answer of: http://stackoverflow.com/q/51493185
has comment: http://stackoverflow.com/comment/89955550
downvote count: 0
has body: I think what you really want here is the elements of L2 that contain any elements in L1. So simply replace if j in i with if i in j: for i in L1: for j in L2: if i in j: print (j) This outputs: marvel comics audi mercedez benz
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51493185
type: Answer
upvote count: 4

http://stackoverflow.com/q/51637646
tagged with: visualization
tagged with: python
has body: Given a set of points in a vtkUnstructuredGrid, whats the easiest way to extract all points for which a specified point data attribute meets a certain condition and discard the rest? In my case I want to remove all points where a field is 0 and extract the others. In Paraview I can do this using the 'Edit > Find Data...' tool and then the 'Extract Selection' Filter, but how can I do this in code in a vtk pipeline?
has answer: http://stackoverflow.com/a/51637704
score: 0
type: UnansweredQuestion
type: Question
tagged with: paraview
answer count: 1
has title: Filter points in vtk unstructured grid by point data attribute
tagged with: vtk

http://stackoverflow.com/q/51483774
has answer: http://stackoverflow.com/a/51484357
favorite count: 0
type: Question
has body: My input data looks like this: cat start target 0 1 2016-09-01 00:00:00 4.370279 1 1 2016-09-01 00:00:00 1.367778 2 1 2016-09-01 00:00:00 0.385834 I want to build out a series using "start" for the Start Date and "target" for the series values. The iterrows() is pulling the correct values for "imp", but when appending to the time_series, only the first value is carried through to all series points. What's the reason for "data=imp" pulling the 0th row every time? t0 = model_input_test['start'][0] # t0 = 2016-09-01 00:00:00 num_ts = len(model_input_test.index) # num_ts = 1348 time_series = [] for i, row in model_input_test.iterrows(): imp = row.loc['target'] print(imp) index = pd.DatetimeIndex(start=t0, freq='H', periods=num_ts) time_series.append(pd.Series(data=imp, index=index)) A screenshot can be seen here. Series "time_series" should look like this: 2016-09-01 00:00:00 4.370279 2016-09-01 01:00:00 1.367778 2016-09-01 02:00:00 0.385834 But ends up looking like this: 2016-09-01 00:00:00 4.370279 2016-09-01 01:00:00 4.370279 2016-09-01 02:00:00 4.370279 I'm using Jupyter conda_python3 on Sagemaker.
tagged with: pandas
score: 3
accepted answer: http://stackoverflow.com/a/51484357
tagged with: python
possible better answer: http://stackoverflow.com/a/51484401
has answer: http://stackoverflow.com/a/51484401
upvote count: 3
answer count: 2
has comment: http://stackoverflow.com/comment/89937505
has title: Pandas: Using iterrows() and pd.Series to Append Values to Series
has comment: http://stackoverflow.com/comment/89936610
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/90060447
has text: Thanks for your help ZJS. I need to create different dataframes and then apply few functions on those dataframes: Essentially the flow is: Yr filter --> Region filter --> Calc an average E score value for that yr and region --> arrange the securities in descending order of average E score --> Pick top 50 securities and put them in a dataframe These dataframes can then be used for backtesting purposes.
comment on: http://stackoverflow.com/a/51546143
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90048487
type: Comment
comment on: http://stackoverflow.com/a/51539766
has text: @computerScience, Well, if you're replacing by the mean, then yes you will have numbers less than 50 (if the mean for a row is less than 50).
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90243786
type: AnswerComment
score: 1
type: Comment
has text: Basically the same thing as my answer. I do have one question thought. Why have `time_start` inside of the `print_time` function. This will not show the real time sense start of the program.
comment on: http://stackoverflow.com/a/51639660

http://stackoverflow.com/q/51571392
tagged with: kodi
type: Question
upvote count: 15
has comment: http://stackoverflow.com/comment/90108878
downvote count: 0
score: 15
has answer: http://stackoverflow.com/a/68511136
has comment: http://stackoverflow.com/comment/90109196
favorite count: 0
has title: No module named googleapiclient.discovery
has answer: http://stackoverflow.com/a/58549686
answer count: 3
has answer: http://stackoverflow.com/a/67313371
has comment: http://stackoverflow.com/comment/90109303
has body: I have been looking to implement the example Python scripts I have found online to allow me to interact with the YouTube API as per the GitHub link found here The problem I am having is with the import statement at the start: import argparse from googleapiclient.discovery import build from googleapiclient.errors import HttpError The online documentation requires the following command to install the googleapiclient library: pip install --upgrade google-api-python-client However, once installed I am still receiving an error that googleapiclient.discovery cannot be found. I have tried reinstalling via pip, with the following command line output generated, suggesting all is well: Requirement already up-to-date: google-api-python-client in g:\python27\lib\site-packages (1.7.4) Requirement not upgraded as not directly required: httplib2&lt;1dev,&gt;=0.9.2 in g:\python27\lib\site-packages (from google-api-python-client) (0.9.2) Requirement not upgraded as not directly required: google-auth&gt;=1.4.1 in g:\python27\lib\site-packages (from google-api-python-client) (1.5.0) Requirement not upgraded as not directly required: google-auth-httplib2&gt;=0.0.3 in g:\python27\lib\site-packages (from google-api-python-client) (0.0.3) Requirement not upgraded as not directly required: six&lt;2dev,&gt;=1.6.1 in g:\python27\lib\site-packages (from google-api-python-client) (1.10.0) Requirement not upgraded as not directly required: uritemplate&lt;4dev,&gt;=3.0.0 in g:\python27\lib\site-packages (from google-api-python-client) (3.0.0) Requirement not upgraded as not directly required: rsa&gt;=3.1.4 in g:\python27\lib\site-packages (from google-auth&gt;=1.4.1-&gt;google-api-python-client) (3.4.2) Requirement not upgraded as not directly required: cachetools&gt;=2.0.0 in g:\python27\lib\site-packages (from google-auth&gt;=1.4.1-&gt;google-api-python-client) (2.1.0) Requirement not upgraded as not directly required: pyasn1-modules&gt;=0.2.1 in g:\python27\lib\site-packages (from google-auth…
type: UnansweredQuestion
tagged with: pip
tagged with: python
tagged with: youtube-api
has comment: http://stackoverflow.com/comment/90109547
has comment: http://stackoverflow.com/comment/90109648
has comment: http://stackoverflow.com/comment/90109485
has comment: http://stackoverflow.com/comment/90108688

http://stackoverflow.com/a/51598006
type: Answer
answers question: http://stackoverflow.com/q/51585732
score: 0
has body: That was a problem about time execution, that was resolved with time.sleep(10) between two executions, after create container and before exec_run

http://stackoverflow.com/a/51817278
score: 2
answers question: http://stackoverflow.com/q/51606613
upvote count: 2
has body: Like this: qemu-img snapshot [-l | -a snapshot | -c snapshot | -d snapshot] filename If you want to take external snapshot, you can specific the path of backing-file. If you want A be the backing-file of B: qemu-img create -b A B
downvote count: 0
type: Answer

http://stackoverflow.com/a/51566711
has comment: http://stackoverflow.com/comment/90100123
has body: DF2_intervals = pd.Series(DF2['idBin'], pd.IntervalIndex.from_arrays(DF2['start'], DF2['end'])) DF1['idBin'] = DF1['Arrival'].map(DF2_intervals) You can also turn that into one line to be more efficient, should you wish to. Let me know if that works.
type: Answer
answers question: http://stackoverflow.com/q/51566566
has comment: http://stackoverflow.com/comment/90155461
score: 0

http://stackoverflow.com/a/55409785
type: Answer
answers question: http://stackoverflow.com/q/51633759
score: 4
upvote count: 4
downvote count: 0
has body: I know this answer is a little late, but in case anyone else needs help. The official Azure documentation, shows parameters which are different to what is actually required: https://learn.microsoft.com/en-us/sql/connect/python/pyodbc/step-3-proof-of-concept-connecting-to-sql-using-pyodbc?view=sql-server-2017 The solution that did work for me was to access the connection string in the database portal in my Azure dashboard. If you navigate to the database instance you're trying to connect to and select Overview: Then on the right hand side you should find Connection strings: And then you should be able to select the ODBC connection string which only requires that you replace your password: I suspect that the thing that catches most people out is selecting the appropriate driver. As you can see in this string and in the pyodbc documentation you have to specify which driver to use based on what your DB is running on: https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Windows This solution worked first time for me, provided that I had added my IP to the DB firewall.

http://stackoverflow.com/comment/90196232
has text: I tested this solution now and it seems to be working just fine. I have a server that manages state machines for each "black box" that are starting or changing state. I had the server run as a standalone module, not to interfere with the main program such that I can continue with other stuff while the tests are running. The main program has a client that requests all active state machines and their states. Thank you for the idea :)
comment on: http://stackoverflow.com/a/51600991
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/51529805
upvote count: 0
type: Answer
score: -1
downvote count: 1
answers question: http://stackoverflow.com/q/51529554
has body: The important distinction in Python is not pass-by-value or -reference, but rather between mutable and immutable objects. Everything is basically passed by reference but if the object does not allow you to modify it (it is immutable) you cannot change the original object which reference was passed. For example Python ints are immutable, thus even the int is passed by reference you can never modify the original obect. If you want to do this, you have to wrap the object in a mutable object, for example a list. Lists can be modified (append, pop, etc.) So you "could" say that Pythons attribute access . is similar to C++s -&gt; but that is kind of weird terminology for Python. In your example you pass a mutable object (list). So the append will modify the original object. The output of your code is thus [0, 1]. (You should include that in your question probably.)

http://stackoverflow.com/a/51534648
upvote count: 1
score: 1
downvote count: 0
has body: Do list(set(...)) insted of set(...) because only lists have an method called extend: ... stop_words = list(set(stopwords.words('french'))) ...
answers question: http://stackoverflow.com/q/51534586
type: Answer

http://stackoverflow.com/q/51596966
answer count: 1
linked to: http://stackoverflow.com/q/51569099
type: UnansweredQuestion
tagged with: python
has title: Calculating correlations and its statistical significance with scipy.stats and pandas
tagged with: correlation
has answer: http://stackoverflow.com/a/51597878
tagged with: scipy
type: Question
has body: I am using the Pandas library for some data analysis. I am testing correlations between attributes. So I calculated the correlations using the .corr() function of the Pandas library. I also want to calculate the statistical significance of this correlations. I already asked a question here. The Pandas library seems to not have this function. I was advised to use scipy.stats. from scipy.stats import pearsonr pearsonr is the function to compute pearson correlation, which is exactly what .corr() except that it also returns the significance, which is what I am after for. The pearsonr cannot deal with Na/null values. So I get rid of them using .dropna() . This removes more examples then it should. In my original csv file there is more words for NA/ null values, I account for this when I open the file: data = pd.read_csv(player, sep=',', na_values=['Did Not Dress','Did Not Play','Inactive','Not With Team'], index_col=0) .corr() deals with missing the missing values itself. The question is why does the .dropna() remove too many examples. Some values are 0 or 0.00(percentage), but that should not be excluded for my purpose. A few lines from the .csv file: Rk,G,Date,Age,Tm,,Opp,,GS,MP,FG,FGA,FG%,3P,3PA,3P%,FT,FTA,FT%,ORB,DRB,TRB,AST,STL,BLK,TOV,PF,PTS,GmSc,+/- 1,1,2017-10-18,32-091,SAS,,MIN,W (+8),1,38:49,9,21,.429,1,2,.500,6,7,.857,5,5,10,4,0,2,3,2,25,18.9,+15 2,2,2017-10-21,32-094,SAS,@,CHI,W (+10),1,32:46,12,24,.500,0,2,.000,4,4,1.000,5,5,10,3,1,2,1,2,28,23.7,+13 3,3,2017-10-23,32-096,SAS,,TOR,W (+4),1,36:17,7,16,.438,0,1,.000,6,7,.857,3,5,8,3,1,1,2,3,20,15.4,+10 4,4,2017-10-25,32-098,SAS,@,MIA,W (+17),1,38:09,12,20,.600,1,1,1.000,6,7,.857,1,6,7,1,2,1,2,4,31,23.7,+16 5,5,2017-10-27,32-100,SAS,@,ORL,L (-27),1,29:30,9,14,.643,1,2,.500,5,5,1.000,4,7,11,0,0,1,1,0,24,22.4,-20 6,6,2017-10-29,32-102,SAS,@,IND,L (-3),1,36:24,10,21,.476,1,2,.500,5,7,.714,3,5,8,0,0,1,1,3,26,16.6,-15 7,7,2017-10-30,32-103,SAS,@,BOS,L (-14),1,26:00,5,13,.385,0,2,.000,1,5,.200,3,2,5,2,1,1,1,1,11,6.7,-…
score: 0
tagged with: pandas
tagged with: significance

http://stackoverflow.com/a/51628688
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51628437
score: 1
has body: axis=2 (third axis) directs to sum the color components: B = image[:,:,0]; G = image[:,:,1]; R = image[:,:,2]

http://stackoverflow.com/q/51560777
answer count: 1
has title: Loading multiple files with bobobo-etl
favorite count: 0
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51720680
has body: I'm new to bonobo-etl and I'm trying to write a job that loads multiple files at once but I can't get the CsvReader to work with the @use_context_processor annotation. A snippet of my code: def input_file(self, context): yield 'test1.csv' yield 'test2.csv' yield 'test3.csv' @use_context_processor(input_file) def extract(f): return bonobo.CsvReader(path=f,delimiter='|') def load(*args): print(*args) def get_graph(**options): graph = bonobo.Graph() graph.add_chain(extract,load) return graph When I run the job I get something like &lt;bonobo.nodes.io.csv.CsvReader object at 0x7f849678dc88&gt; rather than the lines of the CSV. If I hardcode the reader like graph.add_chain(bonobo.CsvReader(path='test1.csv',delimiter='|'),load), it works. Any help would be appreciated. Thank you.
downvote count: 0
score: 1
type: Question
upvote count: 1
tagged with: bonobo-etl

http://stackoverflow.com/comment/90160857
type: Comment
type: QuestionComment
has text: My old answer [here](https://stackoverflow.com/a/32098399/4014959) shows how to modify the contents of a text file. It uses Python 2, but it's easy to convert it to Python 3. Note that this is _not_ recommended. It's generally better to create a new copy of the file. And if you want to work on a binary file see [here](https://stackoverflow.com/a/33715812/4014959).
comment on: http://stackoverflow.com/q/51597222
score: 0

http://stackoverflow.com/q/51579478
has comment: http://stackoverflow.com/comment/90124290
score: 0
has comment: http://stackoverflow.com/comment/90125770
has comment: http://stackoverflow.com/comment/90124269
has title: Python: Adding element to list of a file without read and write each time
has comment: http://stackoverflow.com/comment/90124527
duplicate of: http://stackoverflow.com/q/12994442
has comment: http://stackoverflow.com/comment/90124311
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90124288
tagged with: python
has comment: http://stackoverflow.com/comment/90124294
tagged with: list
answer count: 0
tagged with: file
has body: import json # define list with values basicList = [1, 2, 3, ..., 10000000] # open output file for writing with open('listfile.txt', 'w') as filehandle: json.dump(basicList, filehandle) I created a very long list and wrote it to a file. How can I now add a single element to the file without reading and rewriting the whole file?
type: Question
linked to: http://stackoverflow.com/q/12994442

http://stackoverflow.com/a/51551044
score: 1
has comment: http://stackoverflow.com/comment/90069508
has comment: http://stackoverflow.com/comment/90069385
has body: I believe need indexing with str which handle NaN and Nones too: df = pd.DataFrame({ 'x' : ['abcdef','av', 'a', None, np.nan]}) df['y'] = df['x'].str[1:4] print (df) x y 0 abcdef bcd 1 av v 2 a 3 None None 4 NaN NaN EDIT: I suggest first indexing by str[1:], then split by sparator and then str[0] for seelct first splitted lists: df = pd.DataFrame({ 'x' : ['abc|etf','av|ee', 'ayty|s', None, np.nan]}) df['y'] = df['x'].str[1:].str.split('|').str[0] print (df) x y 0 abc|etf bc 1 av|ee v 2 ayty|s yty 3 None None 4 NaN NaN EDIT: df = pd.DataFrame({ 'x' : ['abc|Ttf','av|Re', 'ayty|s','ayty|','ayty', None, np.nan]}) def f(x): #find position pos = x.find('|') #if no match return same value if pos == -1: return x #else procees code - split else: return x[:pos+2] mask = df['x'].notnull() df.loc[mask, 'y'] = df.loc[mask, 'x'].apply(f) print (df) x y 0 abc|Ttf abc|T 1 av|Re av|R 2 ayty|s ayty|s 3 ayty| ayty| 4 ayty ayty 5 None NaN 6 NaN NaN
has comment: http://stackoverflow.com/comment/90078219
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51551031
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90081891
has comment: http://stackoverflow.com/comment/90069347
answers question: http://stackoverflow.com/q/51551031
type: Answer
downvote count: 0

http://stackoverflow.com/q/51589769
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51590656
upvote count: 1
has answer: http://stackoverflow.com/a/51590367
type: Question
accepted answer: http://stackoverflow.com/a/51590656
score: 1
possible better answer: http://stackoverflow.com/a/51589975
has answer: http://stackoverflow.com/a/51589854
has answer: http://stackoverflow.com/a/51589975
has body: I have file with information like this: id : 1234567890 1)client_name : Abcd 2)family_name : Efgh 5)phon_number : 9876543210 6)address : street number data : [42|63] [42|62] id : 14785236984 1)client_name : Abcd 2)family_name : Efgh 5)phon_number : 987555555555 6)address : street number data : [44|67] [21|1024] id : 987456321 1)client_name : Abcd 2)family_name : Efgh 5)phon_number : 98744444444 6)address : street number data : [26|1089] [21|1524] i want to divide this information by regex, because not all the blocks are separate with new line('\n') so it will be hard for me to do so with split I tried to do with regular expression: ^[\s]id[\w\W\s\S\t]+(\[\d{1,}\|\d{1,}\]{,2})$ but it take all of the blocks i want the result should be: group one id : 1234567890 1)client_name : Abcd 2)family_name : Efgh 5)phon_number : 9876543210 6)address : street number data : [42|63] [42|62] group two id : 14785236984 1)client_name : Abcd 2)family_name : Efgh 5)phon_number : 987555555555 6)address : street number data : [44|67] [21|1024] group three id : 987456321 1)client_name : Abcd 2)family_name : Efgh 5)phon_number : 98744444444 6)address : street number data : [26|1089] [21|1524]
downvote count: 0
has title: Python regex cut pattern string
favorite count: 0
tagged with: python
tagged with: regex-group
tagged with: regex
answer count: 4

http://stackoverflow.com/q/51521626
downvote count: 0
has comment: http://stackoverflow.com/comment/90012632
has answer: http://stackoverflow.com/a/51522997
has comment: http://stackoverflow.com/comment/90012158
accepted answer: http://stackoverflow.com/a/51522997
favorite count: 0
has body: I have a dataframe, and I would like to highlight the cells red, where the word "BBC" appears. Looking at this SO thread and this one I tried the below: df.style.apply(lambda x: ["background-color: red" if x == "BBC News" else "background-color: green"]) or df.style.apply(lambda x: ["background-color: red" if v == "BBC News" else "background-color: green" for v in x], axis=None) But this doesn't color anything. FWIW, I don't know what the x or v are in the examples I used. I assume x is a cell, and v would be a part of the cell? How can I conditinally format cells? I'd also be adding others, i.e. if "CNN" appears in a cell, color yellow, etc. Edit: I tried simply df.style.apply(lambda x: ["background-color: green"]) and nothing happened (same if I used #ff0000 or rgb(0,0,255)). To be explicit, I'm doing: df.style.apply(lambda x: ["background-color: #ff0000" if v['newsSource'] == "BBC News" else "background-color: #ffff00"], axis=None) df.to_html("styletest.html") So I want the coloring visible in the HTML DOCUMENT not the dataframe itself necessarily.
tagged with: pandas
has comment: http://stackoverflow.com/comment/90012386
tagged with: python
linked to: http://stackoverflow.com/q/41203959
has comment: http://stackoverflow.com/comment/90012518
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51522497
has comment: http://stackoverflow.com/comment/90012857
has comment: http://stackoverflow.com/comment/90012599
score: 1
linked to: http://stackoverflow.com/q/38994408
has comment: http://stackoverflow.com/comment/90012221
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90012645
has answer: http://stackoverflow.com/a/51522776
type: Question
answer count: 3
possible better answer: http://stackoverflow.com/a/51522497
upvote count: 1
has title: How to use lambda to apply style to Pandas DataFrame

http://stackoverflow.com/comment/90192968
type: QuestionComment
has text: How will you represent your torus in 2D space? Do you imagine a 3D plot, or will you calculate each particles path along its "torus space" and then somehow project this movement to a square 2D window?
comment on: http://stackoverflow.com/q/51613756
score: 0
type: Comment

http://stackoverflow.com/a/51539766
score: 1
has comment: http://stackoverflow.com/comment/90048487
has comment: http://stackoverflow.com/comment/90047555
answers question: http://stackoverflow.com/q/51539617
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90047602
has comment: http://stackoverflow.com/comment/90048142
downvote count: 0
has body: You need axis=0 to set a value for all columns. You also need pd.DataFrame.mask instead of pd.DataFrame.where to change values where the specified criterion is True. df = pd.DataFrame([[75, 100, 65], [25, 25, 30], [55, 90, 45], [55, 90, 75]]) df.mask((df &lt; 50).any(axis=1), df.mean(axis=1), axis=0, inplace=True) print(df) 0 1 2 0 75.000000 100.000000 65.000000 1 26.666667 26.666667 26.666667 2 63.333333 63.333333 63.333333 3 55.000000 90.000000 75.000000

http://stackoverflow.com/q/51609791
has title: How to compare list A and list B containing integers and print the missing integers?
has comment: http://stackoverflow.com/comment/90184368
type: AnsweredQuestion
score: 3
tagged with: list
type: Question
has answer: http://stackoverflow.com/a/51609858
has comment: http://stackoverflow.com/comment/90184319
has answer: http://stackoverflow.com/a/51610013
accepted answer: http://stackoverflow.com/a/51609835
upvote count: 3
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51609835
favorite count: 0
has body: I wish to print the values that are missing by comparing A and B lists. For example, when I print(a) it will show me that [1,2,5,7,8,9,11,12] are missing and different from A. A = ['0', '0', '3', '4', '6', '6', '6', '6', '6', '6', '10', '10', '10'] B = ['1', '10', '2', '5', '0', '3', '4', '7', '8', '9', '6', '11', '12'] I tried this but it wont work. a = [] for x in A: for y in B: if y != u: a.append(y) Is there an easy way to do so? I have been trying to learn more now. Hopefully, someone could help.
possible better answer: http://stackoverflow.com/a/51609858
tagged with: python

http://stackoverflow.com/a/51549936
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/90094908
score: 1
accepted answer of: http://stackoverflow.com/q/51549719
answers question: http://stackoverflow.com/q/51549719
has comment: http://stackoverflow.com/comment/90067657
has comment: http://stackoverflow.com/comment/90095349
has comment: http://stackoverflow.com/comment/90067352
has body: However, when I put a time.sleep(1) statement after the client does an fd.send() to the server, the TCP server code intermittently pauses while the client is sleeping. AFAICT from running the provided code (nice self-contained example, btw), the server is behaving as intended. In particular, the semantics of the select() call are that select() shouldn't return until there is something for the thread to do. Having the thread block inside select() is a good thing when there is nothing that the thread can do right now anyway, since it prevents the thread from spinning the CPU for no reason. So in this case, your server program has told select() that it wants select() to return only when at least one of the following conditions is true: serv_sock is ready-for-read (which is to say, a new client wants to connect to the server now) serv_sock is ready-for-write (I don't believe this ever actually happens on a listening-socket, so this criterion can probably be ignored) clientsock is ready-for-read (that is, the client has sent some bytes to the server and they are waiting in clientsock's buffer for the server thread to recv() them) clientsock is ready-for-write (that is, clientsock has some room in its outgoing-data-buffer that the server could send() data into if it wants to send some data back to the client) Five seconds have passed since the call to select() started blocking. I see (via print-debugging) that when your server program blocks, it is blocking inside select(), which indicates that none of the 5 conditions above are being met during the blocking-period. Why is that? Well, let's go down the list. Not met because no other clients are trying to connect Not met because this never happens Not met because the server has read all of the data that the connected client has sent (and since the connected client is itself sleeping, it's not sending any more data) Not met because the server has filled up the outgoing-data buffer of its clientsock (because the client progr…
has comment: http://stackoverflow.com/comment/90094824
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90090374
has comment: http://stackoverflow.com/comment/90072324
has comment: http://stackoverflow.com/comment/90095325
has comment: http://stackoverflow.com/comment/90094306
has comment: http://stackoverflow.com/comment/90084430

http://stackoverflow.com/a/70541849
has body: If your are using Ubuntu 20.01 (and 18.04) like me, the solution is to Install Oracle JDK 17. Do the following: sudo add-apt-repository ppa:linuxuprising/java sudo apt update sudo apt install oracle-java17-installer Type java -version on the terminal. You should see the following print-out: java version "17.0.1" 2021-10-19 LTS` Java(TM) SE Runtime Environment (build 17.0.1+12-LTS-39)` Java HotSpot(TM) 64-Bit Server VM (build 17.0.1+12-LTS-39, mixed mode, sharing) tika should then be able to extract text from your pdf in python. parser.from_file(<your pdf file>)
answers question: http://stackoverflow.com/q/51514246
type: Answer
score: 0

http://stackoverflow.com/a/51596694
answers question: http://stackoverflow.com/q/51546348
has body: I think it is important to understand what are you actually trying to achieve here. new_list = [old_list.insert(0, "X") for old_list in list_of_old_lists] Case 1: In your code above, are you trying to create a new new_list containing old(!!!) lists updated to include 'X' character as their first element? If that is the case, then list_of_old_lists will be a list of "new lists". For example, list_of_old_lists = [['A'], ['B']] new_list = [] for old_list in list_of_old_lists: old_list.insert(0, 'X') new_list.append(old_list) print(list_of_old_lists) print(new_list) print(list_of_old_lists == new_list) will print: [['X', 'A'], ['X', 'B']] [['X', 'A'], ['X', 'B']] True That is, new_list is a shallow copy of list_of_old_lists containing "updated" lists. If this is what you want, then you can do something like this using list comprehension: [old_list.insert(0, "X") for old_list in list_of_old_lists] new_list = list_of_old_lists[:] instead of the for-loop in my example above. Case 2: Or, are you trying to create a new list containing updated lists while having list_of_old_lists hold the original lists? In this case, you can use list comprehension in the following way: new_list = [['X'] + old_list for old_list in list_of_old_lists] Then: In [14]: list_of_old_lists = [['A'], ['B']] ...: new_list = [['X'] + old_list for old_list in list_of_old_lists] ...: print(list_of_old_lists) ...: print(new_list) ...: print(new_list == list_of_old_lists) ...: [['A'], ['B']] [['X', 'A'], ['X', 'B']] False
score: 0
type: Answer

http://stackoverflow.com/comment/90260063
comment on: http://stackoverflow.com/a/51635061
score: 0
type: Comment
has text: Thanks but that did half the job. Thr issue is abstract itself contains "," character in sentences. This split the sentence into column whenever a "," character comes
type: AnswerComment

http://stackoverflow.com/comment/90080285
score: 0
comment on: http://stackoverflow.com/a/51556542
type: Comment
type: AnswerComment
has text: Just to confirm, where do I have to put this list_=? In place of list_.append(df) or in the beginning where list=[] is written?

http://stackoverflow.com/q/51524909
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90020720
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90019298
answer count: 0
has comment: http://stackoverflow.com/comment/90019208
has comment: http://stackoverflow.com/comment/90021125
has title: Syntax with Passing a function into another function
type: Question
tagged with: numpy
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90020701
score: 0
tagged with: pandas
has body: I'm writing a function that returns a data frame and I'd like to have one of the columns of this data frame to essentially take a column of data, pass it into a predifined function and then set that as a column of the new data frame. So i set the function up to take a set of data, a function which applies logic and the set of data which that function uses. I was able to get it to work if I use .apply in the final line of of my code that is arrowed. bt_data['Position'] = signal_data.apply(trade_logic) but I was advised to use np.select instead of apply b/c it's vectorized and I was wondering since my function is using vectorization is there a better syntax to use to set a column called bt_data['Positions'] to just be the trade_logic function applied on mlr_data['Slope'} Slope 3.98 3.78 -6.67 -17.6 -18.05 -14.48 -12.25 -13.9 -16.89 -13.3 -13.19 -18.63 -26.36 -26.23 -22.94 -23.23 -15.7 -11.01 -12.65 0.33 14.85 14.79 6.8 2.57 Code: def trade_logic(x): conditions = [x.between(0, 10, inclusive=False), x.between(-10, 0, inclusive=False)] values = ['Long', 'Short'] np.select(conditions, values, 'Flat') def slope_test(x): if x &gt;0 and x&lt;20: return 'Long' elif x&lt;0 and x&gt;-20: return 'Short' else: return 'Flat' def backtest_data(data,trade_logic,signal_data): bt_data = pd.DataFrame() bt_data['TickChange'] = bt_data['C']-bt_data['C'].shift(1) bt_data['CumTickChange'] = bt_data['TickChange'].cumsum() bt_data['Position'] = trade_logic(signal_data) &lt; ------ return bt_data results = backtest_data(mlr_data,trade_logic,mlr_data['Slope']) print(results)

http://stackoverflow.com/comment/90291930
has text: Thanks for the response. I am new to python and learning. When you say retrieve the IP from CSV and create a thread, could you please provide me the snippet of code as how would the code look like as this will help me build on that. I have never done threading previously which leads me to more confusion.
comment on: http://stackoverflow.com/a/51618518
type: AnswerComment
score: 0
type: Comment

sqlite
tags question: http://stackoverflow.com/q/51506665
tags question: http://stackoverflow.com/q/51503490
tags question: http://stackoverflow.com/q/51527615
tags question: http://stackoverflow.com/q/51625869
tags question: http://stackoverflow.com/q/51621919
tags question: http://stackoverflow.com/q/51529559
type: Tag
tags question: http://stackoverflow.com/q/51498790
tags question: http://stackoverflow.com/q/51602216
tags question: http://stackoverflow.com/q/51607268
tags question: http://stackoverflow.com/q/51559620
tags question: http://stackoverflow.com/q/51616508
tags question: http://stackoverflow.com/q/51620157
tags question: http://stackoverflow.com/q/51571854
tags question: http://stackoverflow.com/q/51559201
tags question: http://stackoverflow.com/q/51571191
tags question: http://stackoverflow.com/q/51496696
tags question: http://stackoverflow.com/q/51482736
tags question: http://stackoverflow.com/q/51491284
tags question: http://stackoverflow.com/q/51600926
tags question: http://stackoverflow.com/q/51568990
tag name: sqlite
tags question: http://stackoverflow.com/q/51615388

http://stackoverflow.com/comment/90061213
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51541871
score: 0
has text: Onchange could be a nice try

http://stackoverflow.com/q/51567135
score: 1
has comment: http://stackoverflow.com/comment/90100906
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51567187
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51567187
tagged with: python-3.x
has body: I have a CSV data dump that is formated like this: "field1";"{"JSON-KEY": "JSON-VALUE"}";"field3" If I use the CSV Python reader like this... csv.reader(csvfile, delimiter=';', quotechar='"') I'm having two problems: (1) When a JSON-VALUE string contains the delimiter character ';' the Reader considers it as a delimiter and break the VALUE in two fields. (2) When (1) is not a problem, the JSON-VALUE field is misinterpreted to have one quote less at the begining and one more at the end. For instance: ['field1','{JSON-KEY": "JSON-VALUE"}"','field3'] These two problems are probably related, but I can't fix this by using Python documentation and other Questions here. Does anyone have a lead to what am I missing here and how can I configure the Reader to handle this?
has title: How to ignore a CSV delimiter within a quoted field?
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/90100891
type: AnsweredQuestion

http://stackoverflow.com/comment/90183855
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51601946
has text: I think you answered my question right there. So django in this app structure is simply acting as the web server, replacing something like nginx.
type: AnswerComment

http://stackoverflow.com/comment/89977730
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51488454
has text: The dates from repeated additions are projections for purchases. I later want to group each purchase date in a month/quarter/year by company, so that's why I need those specific parameters.
type: Comment

http://stackoverflow.com/comment/89968474
score: 0
type: Comment
has text: did that, `[system@root selectami]$ python latest-ami.py us-west-1` 'None' '{u'Images': [], 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': 'df6de904-1536-4002-b458-d9526c9e84f9', 'HTTPHeaders': {'date': 'Tue, 24 Jul 2018 13:38:09 GMT', 'content-length': '219', 'content-type': 'text/xml;charset=UTF-8', 'server': 'AmazonEC2'}}}`'
comment on: http://stackoverflow.com/a/51497324
type: AnswerComment

http://stackoverflow.com/comment/90002034
comment on: http://stackoverflow.com/q/51513436
has text: When I copy individual tweet from the csv file and then try to apply the `bytes.decode()` to it, then it is able to do that.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89956182
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51493182
has text: @Saad - Sorry, why do you think first row cannot be matched in output from index 9?

http://stackoverflow.com/q/51519912
accepted answer: http://stackoverflow.com/a/51520120
score: 0
answer count: 1
favorite count: 0
has title: How to get progress from copying .zip files
has body: I need to copy zip files and want to get the progress printed. I have everything set so that it starts copying the file and outputs progress. The problem is that it doesn't seem to be stopping at any point. The output goes well beyond 100% and I end up killing the program. Here is my code: def copyfileobjprogress(fsrc, fdst, callback, length=16 * 1024): copied = 0 MAX = os.path.getsize(default_folder) print(MAX) while True: with open(fsrc, 'rb') as s: with open(fdst, 'wb') as d: buf = s.read(length) if not buf: break d.write(buf) copied += len(buf) callback(copied, MAX) def percentage(copied, MAX): print(copied / MAX *100) The first does the copying and the seconds prints the output.
tagged with: python
has answer: http://stackoverflow.com/a/51520120
type: AnsweredQuestion
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90008938
type: Question

http://stackoverflow.com/q/51537340
has comment: http://stackoverflow.com/comment/90043176
has body: I have a DataFrame with some columns, say 'n' columns and some rows, say 'm' row. I want to group DataFrame rows depending on one column(Column:'x') values, Its not the exact match of column 'x' values. I need to group out nearby values. For example my DataFrame would be like this: y yh x xw w Nxt 0 2987 3129 347 2092 1735.0 501 1 2715 2847 501 1725 1224.0 492 2 2419 2716 490 2196 1704.0 492 3 2310 2373 492 794 302.0 886 4 2309 2370 886 1012 126.0 492 5 2198 2261 497 791 299.0 886 6 2197 2258 886 1010 124.0 492 7 1663 2180 375 1092 600.0 1323 In above dataframe difference between column 'x' values is between 20 then i need to group them into a new dataframe and rest of them can be avoided. Here the index=1,2,3,5 rows can be a one group and index=4,6 would be another group, because difference between those rows 'x' column is between 20. My expected output should be three dataframes- df1:one holds all grouped rows and df2:holds another group of rows and 'df3': rest of the rows as follows: df1: y yh x xw w Nxt 1 2715 2847 501 1725 1224.0 492 2 2419 2716 490 2196 1704.0 492 3 2310 2373 492 794 302.0 886 5 2198 2261 497 791 299.0 886 df2: y yh x xw w Nxt 4 2309 2370 886 1012 126.0 492 6 2197 2258 886 1010 124.0 492 df3: y yh x xw w Nxt 0 2987 3129 347 2092 1735.0 501 7 1663 2180 375 1092 600.0 1323 I tried with Groupby-apply and groupby-transform but couldn't succeed. It would be great help if any one can help me to get this expected one, thanks in advance.
accepted answer: http://stackoverflow.com/a/51541718
tagged with: python
has comment: http://stackoverflow.com/comment/90046289
favorite count: 0
score: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90042980
has comment: http://stackoverflow.com/comment/90043046
has comment: http://stackoverflow.com/comment/90042755
upvote count: 2
has comment: http://stackoverflow.com/comment/90046574
has comment: http://stackoverflow.com/comment/90043744
has comment: http://stackoverflow.com/comment/90043154
has title: Group nearby column values in Python Dataframe
type: AnsweredQuestion
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90042733
has answer: http://stackoverflow.com/a/51541718
has comment: http://stackoverflow.com/comment/90044927
has comment: http://stackoverflow.com/comment/90046138
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51540782
downvote count: 0
possible better answer: http://stackoverflow.com/a/51540782
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/comment/90144496
comment on: http://stackoverflow.com/q/51589612
score: 0
type: Comment
type: QuestionComment
has text: Is there anything wrong? Do you get an error? Which?

http://stackoverflow.com/a/51602902
has comment: http://stackoverflow.com/comment/90172279
answers question: http://stackoverflow.com/q/51602708
score: 1
has comment: http://stackoverflow.com/comment/90173297
has comment: http://stackoverflow.com/comment/90172357
upvote count: 1
has body: @jpp answer is elegant but the following solution is more efficient: res = np.empty((nrows, ncols)) res[:, :] = np.arange(ncols) Timing: %timeit a = np.empty((1000,1000)); a[:, :] = np.arange(1000) 445 µs ± 9.08 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit np.tile(range(1000), (1000, 1)) 1.43 ms ± 15.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) Further timing tests: Following @jpp comments I added one more test done in Python interpreter directly (unlike the original test that was run in a Jupyter notebook - because it was up and running at that moment): &gt;&gt;&gt; import sys &gt;&gt;&gt; print(sys.version) 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; print(np.__version__) 1.13.3 &gt;&gt;&gt; import timeit &gt;&gt;&gt; t = timeit.repeat('res = np.empty((nrows, ncols)); res[:, :] = np.arange(ncols)', setup='import numpy as np; nrows=ncols=1000', number=100, repeat=50) &gt;&gt;&gt; print(min(t), max(t), np.mean(t), np.std(t)) 0.04336756598786451 0.053294404002372175 0.0459639201409 0.00240180447219 &gt;&gt;&gt; t = timeit.repeat('res = np.tile(range(ncols), (nrows, 1))', setup='import numpy as np; nrows=ncols=1000', number=100, repeat=50) &gt;&gt;&gt; print(min(t), max(t), np.mean(t), np.std(t)) 0.05032560401014052 0.05859642301220447 0.0530669655403 0.00225117881195 The results with numpy 1.14.5 are virtually identical: &gt;&gt;&gt; import sys &gt;&gt;&gt; print(sys.version) 3.6.6 |Anaconda, Inc.| (default, Jun 28 2018, 11:07:29) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; print(np.__version__) 1.14.5 &gt;&gt;&gt; import timeit &gt;&gt;&gt; t = timeit.repeat('res = np.empty((nrows, ncols)); res[:, :] = np.arange(ncols)', setup='import numpy as np; nrows=ncols=1000', number=100, repeat=50) &gt;&gt;&gt; print(min(t), max(t), np.mean(t), np.std(t)) 0.04360878…
type: Answer
has comment: http://stackoverflow.com/comment/90173358
has comment: http://stackoverflow.com/comment/90171806
downvote count: 0

http://stackoverflow.com/comment/90008855
comment on: http://stackoverflow.com/a/51519959
score: 0
type: AnswerComment
has text: Perfect Thank you!
type: Comment

http://stackoverflow.com/q/51602208
has body: The code I entered (To test if it works) was import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() print(sess.run(hello)) but then it gave me this error in the shell when running it Traceback (most recent call last): File "C:\Users\Obliveater95\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 18, in swig_import_helper fp, pathname, description = imp.find_module('_pywrap_tensorflow', [dirname(file)]) File "C:\Users\Obliveater95\AppData\Local\Programs\Python\Python36-32\lib\imp.py", line 297, in find_module raise ImportError(_ERR_MSG.format(name), name=name) ImportError: No module named '_pywrap_tensorflow' During handling of the above exception, another exception occurred: te-packages\tensorflow\python__init__.py", line 54, in from tensorflow.python import pywrap_tensorflow File "C:\Users\Obliveater95\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 28, in _pywrap_tensorflow = swig_import_helper() File "C:\Users\Obliveater95\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 20, in swig_import_helper import _pywrap_tensorflow ModuleNotFoundError: No module named '_pywrap_tensorflow' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "X:/Programs/My Programs/TensorFlow testing/Testing.py", line 1, in import tensorflow as tf File "C:\Users\Obliveater95\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow__init__.py", line 24, in from tensorflow.python import * File "C:\Users\Obliveater95\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python__init__.py", line 60, in raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\Users\Obliveater95\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 18, in s…
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90175004
type: UnansweredQuestion
answer count: 0
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: compiler-errors
has title: Having an error when importing Tensorflow into Python (Win7, Py3.6)
type: Question
tagged with: python
tagged with: machine-learning
upvote count: 1

http://stackoverflow.com/comment/90051776
type: AnswerComment
comment on: http://stackoverflow.com/a/51542036
type: Comment
score: 2
has text: Surely legends on SO for pandas ( Wen, jezrael, & jpp) :) glad you guys are here, sorry for off-topic comment

http://stackoverflow.com/a/51538159
has body: I discovered what the issue was, I had a conflicting route. There was a higher level endpoint registered before the AccountViewSet. router.register( prefix=r'v1/auth', viewset=UserViewSet, base_name='users', ) router.register( prefix=r'v1/auth/accounts', viewset=AccountViewSet, base_name='accounts', ) Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.. I should have been ordered this way: router.register( prefix=r'v1/auth/accounts', viewset=AccountViewSet, base_name='accounts', ) router.register( prefix=r'v1/auth', viewset=UserViewSet, base_name='users', ) despite the fact that reverse('appname:acccounts-list') worked, the underlying URL router still thought I was calling the UserViewSet.
score: 1
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51526190

http://stackoverflow.com/q/51581516
tagged with: django-views
has comment: http://stackoverflow.com/comment/90128371
tagged with: django-models
tagged with: django-forms
type: Question
has comment: http://stackoverflow.com/comment/90128366
has comment: http://stackoverflow.com/comment/90128208
has comment: http://stackoverflow.com/comment/90128281
has comment: http://stackoverflow.com/comment/90128348
answer count: 1
has title: Django form.is_valid() is returning false everytime
has comment: http://stackoverflow.com/comment/90128190
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90128431
has body: I have created a django application. In that, when I click on update button on index.html page, it has to redirect to a webpage showing the form with 3 fields,(title,user, body). Everytime I click on update, the form is not validating. It is always returning false. Actually if we press on the update button, the user field should show the present user's id. But it is showing default value. The body field is becoming empty every time. forms.py: class ImmediateForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly'}),initial="Immediate",max_length=20) class Meta: model = Immediate fields = ['title','user','body',] widgets = { 'user': TextInput(attrs={'readonly': 'readonly'}) } Models.py: class Immediate(models.Model): title = models.CharField(default="Immediate",max_length=30) user = models.ForeignKey(User, default=1,on_delete=models.CASCADE) body = models.TextField(default="") def __str__(self): return self.title views.py: def update_immediate(request,pk): if not request.user.is_authenticated: return render(request, 'set_goals/index.html') else: print(pk) try: if request.method=='POST' : print('Inside if') immediate = Immediate.objects.get(user_id=pk) form = ImmediateForm(request.POST or None, instance=immediate or None) if form.is_valid(): print("no") immediate = form.save(commit=False) immediate.user = request.user.username immediate.body = form.cleaned_data['body'] immediate.save() return render(request, 'set_goals/detail_immediate.html', {'immediate': immediate}) context = { "form": form, } return render(request, 'set_goals/create_template.html', context) except: if request.method=='POST' : print('Inside if') form = ImmediateForm(request.POST or None) if form.is_valid(): print("yes") immediate = form.save(commit=False) immediate.user = request.user immediate.body = form.cleaned_data['body'] immediate.save() return render(request, 'set_goals/detail_immediate.html', {'immediate': immediate}) context = { "form": form, } ret…
has comment: http://stackoverflow.com/comment/90128341
has comment: http://stackoverflow.com/comment/90128885
has answer: http://stackoverflow.com/a/51581669
has comment: http://stackoverflow.com/comment/90128410
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/90128327

http://stackoverflow.com/comment/90076558
has text: Still not sure what the desired output is. Most probably you want to use `ax.set_xticks(Chemical_elements)` with `ax.set_xticklabels(xticks)`. Or maybe simply `plt.plot(Chemical_elements, Other_values)` in matplotlib > 2.1?
comment on: http://stackoverflow.com/q/51553465
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90162345
type: QuestionComment
comment on: http://stackoverflow.com/q/51598038
type: Comment
has text: It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on his own. A good way to show this effort is to include a [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve). Check the [intro tour](https://stackoverflow.com/tour) you finished before posting, especially [How to Ask](http://stackoverflow.com/help/how-to-ask).
score: 0

http://stackoverflow.com/q/51569086
score: 0
tagged with: consensus
tagged with: python
tagged with: blockchain
has answer: http://stackoverflow.com/a/51963250
has title: pbft implementation in python when f=1
type: UnansweredQuestion
type: Question
tagged with: algorithm
has body: I want to implement pbft algorithm(3f+1 systems;f=1) in python. But what is the channel should use for sending and receiving from replicas. I have tried python multicast but it seems something going wrong while receiving. So please suggest any solution that can put me forward. Thanks in Advance.
answer count: 1

http://stackoverflow.com/a/51556807
type: Answer
has body: dict1 = {"red": [1, 2, 3], "blue": [7, 6, 9], "green": [3, 9, 3, 1]} dict2 = {"red": [2, 1, 3], "blue": [9, 7, 6], "green": [3, 9, 1, 3]} def compare_dicts(a, b): if set(a.keys()) != set(b.keys()): # If the keys do not match, # the dicts can't be equal. return False for key, value in a.items(): if key not in b: # If a key does not exist in `b`, # but exists in `a`, the dicts # can't be equal. return False if sorted(value) != sorted(b[key]): # If the sorted lists of values aren't # equal, the dicts can't be equal. return False # Every other case failed to exit, so the dicts # must be equal. return True print(compare_dicts(dict1, dict2))
has comment: http://stackoverflow.com/comment/90081026
has comment: http://stackoverflow.com/comment/90080942
has comment: http://stackoverflow.com/comment/90080996
has comment: http://stackoverflow.com/comment/90081086
answers question: http://stackoverflow.com/q/51556728
score: 0

http://stackoverflow.com/a/51626131
type: AcceptedAnswer
type: Answer
has body: How about this: import random dis = ['5','6','9','4','7','8'] f = ['Left' , 'Right' , 'Forward'] f_count = len(f) for i in range(0, f_count): x = random.randint(0, len(f)-1) y = random.randint(0, len(dis)-1) dir = f[x] print('You can move ' + dir + " "+ dis[y] + " meters") f.pop(x) dis.pop(y)
accepted answer of: http://stackoverflow.com/q/51625979
answers question: http://stackoverflow.com/q/51625979
score: 0

http://stackoverflow.com/q/51606185
tagged with: python
has comment: http://stackoverflow.com/comment/90178284
has comment: http://stackoverflow.com/comment/90178689
has body: Always scared to post here, but I'm stumped and also not sure what I'm doing wrong here, because I don't receive any errors. It appears the arguments in this function just don't work. I guess it's because it appears the conditions aren't met? question = [f'{name}, what is 1+1', f'{name}, what is 2+2', f'{name}, what is 2+1'] answer = ['2','4','3'] def generateQuestion(): question_show = print(random.choice(question)) answer = input() if question_show == question[0] and answer == answer[0]: score = score + 1 print(f"Correct, your score is now {score}") if question_show == question[1] and answer == answer[1]: score = score + 1 print(f"Correct, your score is now {score}") if question_show == question[2] and answer == answer[2]: score = score + 1 print(f"Correct, your score is now {score}") If I call that generateQuestion() function is shows the question and allows for input but nothing happens after that.
downvote count: 1
type: Question
score: -1
answer count: 2
has answer: http://stackoverflow.com/a/51606694
upvote count: 0
has answer: http://stackoverflow.com/a/51606703
has title: Defined function in python not recognising if and arguments
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51541912
has comment: http://stackoverflow.com/comment/90051562
score: 0
has body: If your numbers are stored as strings you can split the very easily in python. You can split strings using the index of the characters you want. For example if you want to get the first three characters out of a string you could do key[:3] This would give you everything up to but not including the character in the 3 position. To pull characters out of the middle you could use key[1:6] This would give you all the numbers starting at the 1 spot until the 6 spot. (remember that the index starts at 0) If you wanted to check the middle of the string to see if it is equal to something try something like this: if key[1:6] == "00000": #do something This will compare the part of the string between 1 and 6 to see if it is equal to "00000".
answers question: http://stackoverflow.com/q/51541042
has comment: http://stackoverflow.com/comment/90052039
type: Answer
has comment: http://stackoverflow.com/comment/90051693

http://stackoverflow.com/q/51557640
accepted answer: http://stackoverflow.com/a/51566582
tagged with: graph
tagged with: null
answer count: 1
score: 0
has title: Cannot load graphs. Loading graph to igraph (from arbitrary source) "returned NULL"
has body: I am working with igraph and networkx and I try to convert my nx graph to an igraph graph via nx.write_graphml(nx_graph,filepath) # Export NX graph to file ig_graph = ig.read(filepath,format="graphml") # Create new IG graph from file This works perfectly fine on one machiene, but on another one I get the error SystemError: built-in method Read_GraphML of type object at 0x000002488D3FEE58 returned NULL without setting an error I run Windows10 and Python 3.5. Interestingly, on the working machine the python-igraph version is specified as '0.7.1' while on the faulty system it is '0.7.1+5.3b99dbf6' although I am rather sure to have done the same install procedure via the files from Christoph Gohlke. The error also occurs in a simple test setting like this: import igraph as ig g = ig.Graph.Famous("zachary") g.save("zachary.graphml") g=ig.load("zachary.graphml") Thus, I am pretty sure is has nothing to do with the file that was produced by networkx but rather it has to be something wrong with my igraph configuration. I really do not know where the difference on the systems may be, so please let me know if you have any ideas. Thank you! :) Edit: I did also run the test suite import igraph.test igraph.test.run_tests() and it worked well on both setups - even the faulty one.
tagged with: python
tagged with: load
has comment: http://stackoverflow.com/comment/90160933
has comment: http://stackoverflow.com/comment/90112048
tagged with: igraph
has answer: http://stackoverflow.com/a/51566582
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/51594546
type: Answer
has comment: http://stackoverflow.com/comment/90165881
has comment: http://stackoverflow.com/comment/90164712
has comment: http://stackoverflow.com/comment/90165019
score: 0
has comment: http://stackoverflow.com/comment/90166111
answers question: http://stackoverflow.com/q/51585303
has comment: http://stackoverflow.com/comment/90164663
has comment: http://stackoverflow.com/comment/90163209
has body: I don't think setting up static (css,js,etc..) or media (images, videos) to be stored on S3 has anything to do with Heroku or where you deploy. Rather, its just making sure Django knows where to save the files, and where to fetch them. I would definitely not follow that link, because it seems confusing and not helpful when working with Django. This tutorial has really helped me, as it will show you how to set all of that up. I have gone through these steps and can confirm it does the trick. https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html

http://stackoverflow.com/comment/90280076
has text: Then how do you explain the size=16 of the elements of l2 when [None] is not identically replicated?
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51619941

http://stackoverflow.com/a/51494481
type: Answer
upvote count: 3
score: 3
has body: Your error occurs because SeqIO.write accepts a SeqRecord or a list/iterator of SeqRecords but you are feeding it just a list like [name, sequence]. Instead I suggest you just modify the SeqRecord .id and .description (note, if there is whitepace in the header line, you'll need to handle this too). Also it is most efficient (across Biopython versions) to write all the records at once, rather than calling .write each iteration: from Bio import SeqIO def yield_records(): with open('lots_of_fasta_in_file.fasta') as f: for seq_record in SeqIO.parse(f, 'fasta'): seq_record.id = seq_record.description = seq_record.id.replace('.seq','') yield seq_record SeqIO.write(yield_records(), 'new.fasta', 'fasta')
answers question: http://stackoverflow.com/q/51488228
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51488228

http://stackoverflow.com/comment/90384766
type: AnswerComment
type: Comment
score: 0
has text: btw thank you for your effort to help me. I have solved my problems
comment on: http://stackoverflow.com/a/51624703

http://stackoverflow.com/comment/90221393
has text: @iamanigeeit Sorry for not bring clear. I have edited my question.
comment on: http://stackoverflow.com/q/51628437
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90116169
has text: `set_position` is not expected to work with 3D coordinates. But there are several solutions in the linked question. Why not use one of them?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51574060

http://stackoverflow.com/comment/90026801
comment on: http://stackoverflow.com/q/51528185
score: 0
type: Comment
type: QuestionComment
has text: When plotting this function I know it should start at 1 but rather it starts at ~8000. Might be something wrong with the data itself.

http://stackoverflow.com/comment/90059067
score: 0
type: AnswerComment
type: Comment
has text: Note that if the value you're converting is calculated within the same script, you can also use a `bytearray(4)` to contain the value. That's likely to be hardware specific, since it will depend on the value of `sys.byteorder`, but may be simpler.
comment on: http://stackoverflow.com/a/51545627

http://stackoverflow.com/comment/90114759
comment on: http://stackoverflow.com/a/51574479
type: AnswerComment
type: Comment
has text: @AlexChadwick you can have files with or without an extension, just make sure that you load them with the same exact name, including extension. The extension can be anything, not just `.save`.
score: 0

http://stackoverflow.com/q/51544101
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90064720
upvote count: 1
accepted answer: http://stackoverflow.com/a/51548072
has comment: http://stackoverflow.com/comment/90056182
type: Question
has body: Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name. After Django goes to 2.0.7, I set up some url rules. It works locally at 127.0.0.1 on my computer, but not remotely on the machine (ubuntu 1604). code: post_list.html: {% for post in posts %} published: {{ post.published_date }} {{ post.title }} {% endfor %} blog.urls: urlpatterns = [ path('', views.home_page, name='home_page'), path('posts', views.post_list, name='post_list'), path('post/<pk>/', views.post_detail, name='post_detail'), ] blog.views: def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) mysite.urls: urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ] Solved. I need to add 'blog' as my app_name in blog.url and add 'blog' as my namespace in mysite.url Thanks guy! In 2.0.7, I need to add an app_name (blog) in blog.url and add a namespace in mysite.url (blog). Only adding a namespace in mysite.url without adding an app_name in blog.url -> django will tell me to add an app name. Only adding an app_name in blog.url without adding a namespace in mysite.url -> django will tell me blog is a not registered namespace. Also remember to refresh gunicorn.
tagged with: ubuntu-16.04
has comment: http://stackoverflow.com/comment/90058682
has title: django 2.0.7 NoReverseMatch at /posts
downvote count: 0
tagged with: amazon-ec2
answer count: 1
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51548072
has comment: http://stackoverflow.com/comment/90056533
tagged with: django

http://stackoverflow.com/q/51484869
has comment: http://stackoverflow.com/comment/89938947
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/89938680
has title: Python debug logger doesn't appear in console
has body: This is driving me insane, I have the following script: #!/usr/bin/env python3 import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) print(logger.getEffectiveLevel()) print(logger.isEnabledFor(logging.DEBUG)) logger.debug("test") #??? which, when run, outputs the following: 10 True why doesn't my logger.debug statement do anything???
upvote count: 1
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51484896
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51484896

http://stackoverflow.com/q/51629763
has body: I have a python script which I run on my old quad-core laptop through multiprocessing. The simulation cannot be parallelised, I just run different instances of it on the different cores. I was considering renting some more powerful cpus on google compute engine. Will I be able to use the same python multiprocessing script just with more cores available? the script just calls a pool and then apply_async many times
has comment: http://stackoverflow.com/comment/90230830
tagged with: multiprocessing
type: Question
upvote count: 2
answer count: 2
accepted answer: http://stackoverflow.com/a/51756373
favorite count: 0
has answer: http://stackoverflow.com/a/51756195
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51756373
possible better answer: http://stackoverflow.com/a/51756195
score: 2
has title: python multiprocessing google compute engine
downvote count: 0
tagged with: google-compute-engine
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51513150
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51514879
has title: how to plot a pie chart row wise?
upvote count: 1
accepted answer: http://stackoverflow.com/a/51514879
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89997440
downvote count: 3
has comment: http://stackoverflow.com/comment/89996739
has body: If the data is like: one two 123456 98765 456767 45678 123454 87654 Then how a pie chart can be formed for say 1st row values ie values 123456 ,98765in pandas ? I tried codes which are given on internet as: df.T.plot.pie(subplots=True, figsize=(9, 3)) and import matplotlib.pyplot as plt df.Data.plot(kind='pie') fig = plt.figure(figsize=(6,6), dpi=200) ax = plt.subplot(111) df.Data.plot(kind='pie', ax=ax, autopct='%1.1f%%', startangle=270, fontsize=17) but these codes don't plot row values instead giving a cloumn result.
type: Question
tagged with: pie-chart
score: -2
answer count: 1
favorite count: 0

http://stackoverflow.com/a/71314298
answers question: http://stackoverflow.com/q/51547551
has body: try changing : ani = animation.FuncAnimation(fig, animate, interval = 15000) to : ani = animation.FuncAnimation(fig, animate, interval = 15000, repeat = False)
score: 0
type: Answer

http://stackoverflow.com/q/51518153
upvote count: 2
has comment: http://stackoverflow.com/comment/90006195
has body: I wrote a code to find peaks in a time-series and I want it to plot the local baselines too. At the moment I am using a test time-series built from two cosinusoids. The code goes as this, where p_times are the times of the center of the peaks: step = 0.1 time = np.arange(0, 10.1, step) #Does stuff to find peaks p_times = [0.9, 1., 1.1, 1.9, 2., 2.1, 2.9, 3., 3.1, 3.9, 4., 4.1, 4.9, 5., 5.1, 5.9, 6., 6.1, 6.9, 7., 7.1, 7.9, 8., 8.1, 8.9, 9., 9.1] idx = np.array([np.where(time == x)[0][0] for x in p_times]) The last instruction should give an array with the indices of the elements of time corresponding to the peaks, but instead I get: IndexError: index 0 is out of bounds for axis 0 with size 0 What makes the case curious is that changing the cosinusoids parameters to what appears to be some "lucky" values, the positions of peaks change as well, and the code works: p_times = [0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5., 5.5, 6., 6.5, 7., 7.5, 8., 8.5, 9., 9.5] # result: idx = [ 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95] UPDATE: Using again the "unlucky" time-series, I have this array of peak times: p_times = [0.3, 1.8, 1.9, 2., 2.1, 2.2, 3.7, 3.8, 3.9, 4., 4.1, 4.2, 4.3, 5.8, 5.9, 6., 6.1, 6.2, 7.7, 7.8, 7.9, 8., 8.1, 8.2, 8.3] And the instruction : idx_c = np.array([np.where(np.isclose(time, x))[0][0] for x in p_times]) fails again with: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-1-4c7f86bac90c&gt; in &lt;module&gt;() 53 #Baseline extremes (x,y), left and right 54 #idx_c = np.array([np.where(time == x)[0][0] for x in O[:,0]]) #Cannot manage to vectorize this ---&gt; 55 idx_c = np.array([np.where(np.isclose(time, x))[0][0] for x in p_times]) 56 print("idx_c = ", idx_c) 57 idx_l = np.array(idx_c - k) #Left extreme is at index of center (peak) minus k positions. &lt;ipython-input-1-4c7f86bac90c&gt; in &lt;listcomp&gt;(.0) 53 #Baseline extremes (x,y), left and rig…
has comment: http://stackoverflow.com/comment/90006966
type: Question
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90005132
has title: Python: A curious case of Index out of Bounds
has answer: http://stackoverflow.com/a/51518975
tagged with: numpy
has comment: http://stackoverflow.com/comment/90005861
has comment: http://stackoverflow.com/comment/90005363
downvote count: 0
has comment: http://stackoverflow.com/comment/90004968
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90005096
accepted answer: http://stackoverflow.com/a/51518975
tagged with: python

http://stackoverflow.com/q/51506863
score: 3
has comment: http://stackoverflow.com/comment/90009601
has answer: http://stackoverflow.com/a/51520949
upvote count: 3
tagged with: amazon-dynamodb
has comment: http://stackoverflow.com/comment/90011000
type: Question
has comment: http://stackoverflow.com/comment/90010188
has comment: http://stackoverflow.com/comment/90010367
has comment: http://stackoverflow.com/comment/90010711
has comment: http://stackoverflow.com/comment/90010866
has comment: http://stackoverflow.com/comment/90010325
tagged with: boto3
accepted answer: http://stackoverflow.com/a/51520949
has comment: http://stackoverflow.com/comment/90010051
has comment: http://stackoverflow.com/comment/90009981
has comment: http://stackoverflow.com/comment/90010204
answer count: 1
linked to: http://stackoverflow.com/q/325933
downvote count: 0
has comment: http://stackoverflow.com/comment/89994878
has comment: http://stackoverflow.com/comment/90010128
favorite count: 0
has body: I am trying to search my database to see if a date range I am about to add overlaps with a date range that already exists in the database. Using this question: Determine Whether Two Date Ranges Overlap I came up with firstDay &lt;= :end and lastDay &gt;= :start for my FilterExpression. def create(self, start=None, days=30): # Create the start/end times if start is None: start = datetime.utcnow() elif isinstance(start, datetime) is False: raise ValueError('Start time must either be "None" or a "datetime"') end = start + timedelta(days=days) # Format the start and end string "YYYYMMDD" start = str(start.year) + str('%02d' % start.month) + str('%02d' % start.day) end = str(end.year) + str('%02d' % end.month) + str('%02d' % end.day) # Search the database for overlap days = self.connection.select( filter='firstDay &lt;= :end and lastDay &gt;= :start', attributes={ ':start': {'N': start}, ':end': {'N': end} } ) # if we get one or more days then there is overlap if len(days) &gt; 0: raise ValueError('There looks to be a time overlap') # Add the item to the database self.connection.insert({ "firstDay": {"N": start}, "lastDay": {"N": end} }) I am then calling the function like this: seasons = dynamodb.Seasons() seasons.create(start=datetime.utcnow() + timedelta(days=50)) As requested, the method looks like this: def select(self, conditions='', filter='', attributes={}, names={}, limit=1, select='ALL_ATTRIBUTES'): """ Select one or more items from dynamodb """ # Create the condition, it should contain the datatype hash conditions = self.hashKey + ' = :hash and ' + conditions if len(conditions) &gt; 0 else self.hashKey + ' = :hash' attributes[':hash'] = {"S": self.hashValue} limit = max(1, limit) args = { 'TableName': self.table, 'Select': select, 'ScanIndexForward': True, 'Limit': limit, 'KeyConditionExpression': conditions, 'ExpressionAttributeValues': attributes } if len(names) &gt; 0: args['ExpressionAttributeNames'] = names if len(filter) &gt; 0: args['FilterExpression'] …
has comment: http://stackoverflow.com/comment/90010849
has comment: http://stackoverflow.com/comment/90010464
has comment: http://stackoverflow.com/comment/90010290
tagged with: python
has title: Dynamodb isn't finding overlap between two date ranges
has comment: http://stackoverflow.com/comment/90009879
type: AnsweredQuestion

http://stackoverflow.com/q/51583756
score: 0
has body: If I have a serializer thus: class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) then the dictionary returned by serializer.data will have keys "email" and "content". But I need to include fields whose names are not valid Python identifiers: "type" "@context" Is there an idiomatic way of doing this?
has comment: http://stackoverflow.com/comment/90134533
accepted answer: http://stackoverflow.com/a/51587190
has comment: http://stackoverflow.com/comment/90136009
has title: django-rest-framework ModelSerializer fields whose names are invalid Python identifiers
type: AnsweredQuestion
tagged with: django-rest-framework
type: Question
has answer: http://stackoverflow.com/a/51587190
tagged with: django
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/90151580

http://stackoverflow.com/a/51515920
has comment: http://stackoverflow.com/comment/90002304
has comment: http://stackoverflow.com/comment/90001030
has comment: http://stackoverflow.com/comment/90001257
has comment: http://stackoverflow.com/comment/90002030
has comment: http://stackoverflow.com/comment/90000776
has comment: http://stackoverflow.com/comment/90000523
has comment: http://stackoverflow.com/comment/90001622
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90000862
answers question: http://stackoverflow.com/q/51515720
has comment: http://stackoverflow.com/comment/90003671
accepted answer of: http://stackoverflow.com/q/51515720
has comment: http://stackoverflow.com/comment/90002122
has comment: http://stackoverflow.com/comment/90002060
type: Answer
has comment: http://stackoverflow.com/comment/90000620
has comment: http://stackoverflow.com/comment/90026731
has body: If I understand your problem correctly, you want to add 'label' to dict in Argument where there is no label. You could do it like so - for i in x[0]['Next']['seed'][0]['Argument']: if not 'label' in i.keys(): i['label'] = [] Where x is your dict. But what's x[0]['Next']['seed'][0]['Argument']:? Let's simplify your dict - x = [{'Next': {'Next': 'he,get', 'seed': [{'Argument': [{these}, {are}, {your}, {dicts}]}], 'time': ''}}] How did we reach here? Let's see- x = [{'Next'(parent dict): {'Next'(child of previous 'Next'):{}, 'seed(child of previous 'Next')':[{these}, {are}, {your}, {dicts}](a list of dicts)}] I hope that makes sense. And to add more dictionaries in Argument # create a function that returns a dict import random # I don't know how you want ids, so this def create_dicts(): return {"id": random.randint(1, 10), "label": ""} for i in range(3): # 3 is how many dicts you want to push in Argument x[0]['Next']['seed'][0]['Argument'].append(create_dicts()) Now your dict will become - [{'Next': {'Next': 'he,get', 'seed': [{'Argument': [{'id': 4, 'label': 'org'}, {'id': 'I'}, {'id': 3, 'label': 'object', 'seed': 2, 'word': 'He'}, {'id': 2, 'label': 'verb', 'seed': 9, 'word': 'Gets'}, {'id': 1, 'label': ''}, {'id': 4, 'label': ''}, {'id': 4, 'label': ''}]}], 'time': ''}}]

http://stackoverflow.com/q/51578636
has answer: http://stackoverflow.com/a/51578716
type: Question
has answer: http://stackoverflow.com/a/67902127
tagged with: http://stackoverflow.com/tag/json
answer count: 3
score: 5
tagged with: django-rest-framework
has title: delete object through Django REST API
favorite count: 0
has body: I'm trying to delete "Product" object using Django REST API but don't know how to do this. serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'product_name', 'measure', 'barcode') I can create product using this function def create_product(request): data = request.POST serializer = ProductSerializer(data=data) if serializer.is_valid(): serializer.save() But I don't know how to delete There is no serializer.delete() method.
upvote count: 5
tagged with: rest
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90122622
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/51578697
tagged with: django

http://stackoverflow.com/a/51576099
answers question: http://stackoverflow.com/q/51575927
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90117965
downvote count: 0
has comment: http://stackoverflow.com/comment/90118446
type: Answer
accepted answer of: http://stackoverflow.com/q/51575927
has body: Regression can't take datetime objects, must convert to number type: import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np from datetime import datetime import pandas as pd pd.core.common.is_list_like = pd.api.types.is_list_like from sklearn.linear_model import LinearRegression import pandas_datareader.data as web start = datetime(2017, 8, 1) end = datetime(2018, 7, 30) data_SP = web.DataReader('JPM', 'iex', start, end) dates = list(map(lambda x: datetime.strptime(x,"%Y-%m-%d"),list(data_SP.index))) days_since = list(map(lambda x: (x-start).days,dates)) model = LinearRegression(fit_intercept=True) model.fit(np.array(days_since)[:, np.newaxis],data_SP['close']) yfit = model.predict(np.array(days_since)[:, np.newaxis]) plt.figure() plt.scatter(dates, yfit) plt.scatter(dates, data_SP['close']) plt.xlabel('date') plt.ylabel('close') plt.show() If percentage change is used, then a nagging NaN needs to be accounted for. import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np from datetime import datetime import pandas as pd pd.core.common.is_list_like = pd.api.types.is_list_like from sklearn.linear_model import LinearRegression import pandas_datareader.data as web start = datetime(2017, 8, 1) end = datetime(2018, 7, 30) data_SP = web.DataReader('JPM', 'iex', start, end) dates = list(map(lambda x: datetime.strptime(x,"%Y-%m-%d"),list(data_SP.index))) days_since = list(map(lambda x: (x-start).days,dates)) model = LinearRegression(fit_intercept=True) model.fit(np.array(days_since)[1:][:, np.newaxis],data_SP['close'].pct_change(1)[1:]) # &lt;------------ yfit = model.predict(np.array(days_since)[:, np.newaxis]) plt.figure() plt.scatter(dates, yfit) plt.scatter(dates, data_SP['close'].pct_change(1)) plt.xlabel('date') plt.ylabel('close') plt.show()
upvote count: 1
score: 1

http://stackoverflow.com/q/51498355
upvote count: 1
duplicate of: http://stackoverflow.com/q/9452108
downvote count: 1
type: Question
answer count: 2
duplicate of: http://stackoverflow.com/q/17648999
has body: I have specific pattern at the beginning of each line. I want to delete that particular pattern not the complete line in python. My data looks like after retrieving from the actual file &gt;homo_seg-Val-abc-1-1 &gt;homo_seg-Beg-cdf-2-1 &gt;homo_seg-Try-gfh-3-2 &gt;homo_seg-Fuss-cdh-3-1 Here I want to delete the ">homo_seg-" from the dataset and retains only following Val-abc-1-1 Beg-cdf-2-1 Try-gfh-3-2 Fuss-cdh-3-1 I can do this in perl $new =~s/homo_seg-//g; My code is: import sys inFile = sys.argv[1] with open(inFile) as fasta: for line in fasta: if line.startswith('&gt;'): header = line.split() t = header[0] import re # from below answer regex = r"&gt;homo_seg-" subst = "" result = re.sub(regex, subst, t, 0, re.MULTILINE) print(result) This code just giving output of last line. I know its some minor error but not able to pick it up.
linked to: http://stackoverflow.com/q/9452108
has title: Search the specific pattern and delete the pattern in a line in Python
has answer: http://stackoverflow.com/a/51498405
tagged with: str-replace
score: 0
tagged with: python
favorite count: 0
tagged with: pattern-matching
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51498393

http://stackoverflow.com/a/51528962
type: AcceptedAnswer
downvote count: 0
has body: Here is a working example of what you are wanting: NOTE: This was tested using Chrome build 67 with chromedriver 2.40 driver.get('https://www.capterra.com/p/14890/Fastreact/') # this will go directly to the check-list item you are wanting vendor_details = driver.find_element_by_xpath('.//ul[@class="check-list"][2]') print(vendor_details.text) # this will go directly to the link you are wanting vendor_link= driver.find_element_by_xpath('.//ul[@class="check-list"][2]/li[2]') print(vendor_link.text) The print statements will display the text values of the elements in your console.
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/51528556
upvote count: 1
answers question: http://stackoverflow.com/q/51528556

http://stackoverflow.com/comment/90208967
type: QuestionComment
has text: @E.Serra duuuuuuude. spelling error. Thank you. If you post this as an answer i'll give you credit.
comment on: http://stackoverflow.com/q/51620641
score: 0
type: Comment

http://stackoverflow.com/q/51584430
type: Question
has body: I"m on Python 3.6.6, Jupyter console 5.2.0, Ipython 6.4.0, Ubuntu 18.04. When in ipdb, arrows keys produce escape sequences instead of moving the cursor. I have readline installed and libncurses5-dev installed. What's the issue? More data: this is only true in jupyter console, everything works fine when running ipython directly.
has comment: http://stackoverflow.com/comment/90134888
tagged with: jupyter
tagged with: jupyter-notebook
tagged with: python-3.x
tagged with: ipdb
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/90134366
has title: ipdb arrows keys produce escape sequences

http://stackoverflow.com/q/51595370
has body: examples: 0.28 --> 2 0.1234 --> 4 0.01345000 --> 5 My answer: len(str(k)[str(k).index('.')+1:]) It works but it is also super ugly. Anything more pythonic?
type: Question
linked to: http://stackoverflow.com/q/6189956
score: 0
has comment: http://stackoverflow.com/comment/90156749
tagged with: string
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/6189956
has comment: http://stackoverflow.com/comment/90157068
answer count: 0
has title: Python: Given a float, return number of decimals

http://stackoverflow.com/q/51598999
favorite count: 0
tagged with: dot-product
tagged with: python
has comment: http://stackoverflow.com/comment/97692288
answer count: 0
downvote count: 0
type: UnansweredQuestion
has title: How to re-implement matmul in Tensorflow
tagged with: tensorflow
type: Question
score: 2
has body: I have two matrixes A and B that I would like to dot-multiply (using tf.matmul). How can I re-implement the standard 'matmul' so i can play with it and change functionality? I'm trying something like this tf.reduce_sum(tf.multiply(tf.tile(A), tf.tile(B))) So in the future i can test stuff like reduce_mean etc... Any clue?
tagged with: matrix-multiplication
upvote count: 2

http://stackoverflow.com/comment/90013669
score: 0
type: Comment
has text: Thank you. It seems that there is no content in the response from this URL. 'for chunk in ...' prints nothing.
type: AnswerComment
comment on: http://stackoverflow.com/a/51521887

http://stackoverflow.com/comment/90050046
has text: Flag all days with less than most frequent value for each district
score: 0
comment on: http://stackoverflow.com/q/51539827
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51584343
score: 2
type: AnsweredQuestion
has title: Why some elements of the response object are missing? Requests module
accepted answer: http://stackoverflow.com/a/51661899
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/90223557
answer count: 1
has comment: http://stackoverflow.com/comment/90134170
has comment: http://stackoverflow.com/comment/90171072
favorite count: 0
tagged with: parsing
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51661899
has body: As I've recently started learning web scraping, I thought I would try to parse an HTML table from this site using requests and bs4 modules. I know I need to access td class from tbody -- this is how a web page looks like at least: When I try, though, it doesn't seem to work properly as it only captures td class from thead and not from tbody. Hence, I cannot capture anything but the headers of the table. I assume it has something to do with requests module. url = 'https://vstup.edbo.gov.ua/statistics/requests-by-university/? qualification=1&education-base=40' r = requests.get(url) print(r.text) The result is as follows (pasting table-related part): Регіон Назва закладу Спеціальність (спеціалізація) СКБ Усього заяв Заяв на бюджет So the tbody elements are missing in my response object, while they are present in the code of the web page. What am I doing wrong?
upvote count: 2
tagged with: python
tagged with: python-requests
tagged with: html-parsing

http://stackoverflow.com/a/51611206
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51611027
score: 4
type: AcceptedAnswer
has body: You can use list comprehension with a dict mapping: l = ["150M", "360M", "2.6B", "3.7B"] m = {'K': 3, 'M': 6, 'B': 9, 'T': 12} print([int(float(i[:-1]) * 10 ** m[i[-1]] / 1000) for i in l]) This outputs: [150000, 360000, 2600000, 3700000]
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51611027

http://stackoverflow.com/q/51619889
has answer: http://stackoverflow.com/a/51619932
has comment: http://stackoverflow.com/comment/90205477
type: Question
score: 0
has answer: http://stackoverflow.com/a/51619920
has answer: http://stackoverflow.com/a/51619916
answer count: 3
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/51619916
accepted answer: http://stackoverflow.com/a/51619920
has title: python regex for slicing string
has comment: http://stackoverflow.com/comment/90205446
type: AnsweredQuestion
has body: Is there any way to use regex for the following? str_ = 'start_sampleString_data_2018-11-18' new_str = str_[6:-16] // basically new_str -&gt; "sampleString" and remove everything else Is there any way to do this via regex? The string is format will always be like... 'start_' + 'someSampleString' + '_data_' + 'someDateIn(yyyy-mm-dd) Only need to be able to extract 'someSampleString' from it. Thanks!

http://stackoverflow.com/comment/90223581
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51629651
has text: But I don't want to convert the values into `NaN`s, since the values are all legitimate longitudes and latitudes. How about just converting them from `str` to `int` instead?

http://stackoverflow.com/comment/90090216
score: 0
type: Comment
type: QuestionComment
has text: why are you clicking again on drop down after selecting `15. Kizilirmak Havzasi` from drop down ?
comment on: http://stackoverflow.com/q/51561450

http://stackoverflow.com/a/51533752
answers question: http://stackoverflow.com/q/51533442
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51533442
has body: The formula for Euclidean distance is the following: dist((x, y), (a, b)) = √((x - a)² + (y - b)²) Which gives: = √((11 - 2)² + (3 - 3)²) = √(9)² = 9

http://stackoverflow.com/comment/89975086
type: Comment
type: QuestionComment
has text: I missed my predict_generator just now, I edited the code inside. Besides this, do you have any suggestions I can do to increase my validation accuracy? Thank you so much for reply me.
comment on: http://stackoverflow.com/q/51502835
score: 0

http://stackoverflow.com/q/51532359
accepted answer: http://stackoverflow.com/a/52393629
has body: I have a set of 1D data saved in a python. I can get the probability density function using gaussian_kde function from scipy. I want to know whether the returned distribution matches with a theoretical distribution such as Normal distribution. For that can I use KL divergence? If so how can I use python to do that? This is my python code to get the probability density function. array = np.array(values) KDEpdf = gaussian_kde(array) x = np.linspace(0, 50, 1500) kdepdf = KDEpdf.evaluate(x) plt.plot(x, kdepdf, label="", color="blue") plt.legend() plt.show()
tagged with: python
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90032617
has title: How to get probability density function using Kullback-Leibler Divergence in Python
answer count: 1
tagged with: statistics
score: 0
has answer: http://stackoverflow.com/a/52393629

http://stackoverflow.com/comment/89993127
type: Comment
has text: yes thats problem , can you give me a pointer , Because of cout =0 value is overwriting, when I call another file. I like to take the value from different file and write it to Excell . But due to count=0 it write everytime in (0,3) . i want when another file compare it has to write in (1,3) ,(2,3)......(10,3) .
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51504034

http://stackoverflow.com/comment/90118412
comment on: http://stackoverflow.com/a/51489341
type: AnswerComment
score: 0
type: Comment
has text: didn't you have to install python again?

http://stackoverflow.com/q/51621082
type: Question
tagged with: time-series
has title: Dealing with Duplicate Dates in Pandas
tagged with: duplicates
tagged with: date
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51621166
tagged with: python
accepted answer: http://stackoverflow.com/a/51621166
type: AnsweredQuestion
score: 3
upvote count: 3
has body: The problem is that I have a large data set with missing date entries and also duplicates. I can't drop any of them so, I need to add the missing dates and have the corresponding columns be NaN. Here's a sample code of it. df = pd.DataFrame({ 'timestamps': pd.to_datetime( ['2016-11-15 1:00','2016-11-16 2:00','2016-11-16 3:00','2016-11-18 4:00']), 'values':['a','b','c','d']}) df.index = pd.DatetimeIndex(df['timestamps']).floor('D') all_days = pd.date_range(df.index.min(), df.index.max(), freq='D') While searching I found that we shouldn't go with df.reindex() as it can't handle duplicates. So the other solution is to use df.loc[all_days] but, everytime I use it as df.loc[all_days] = [0,0] all it says is that my missing date, which I need to add to the dataframe, is not in the index. It should go from this: timestamps values 2016-11-15 "2016-11-15 01:00:00" a 2016-11-16 "2016-11-16 02:00:00" b 2016-11-16 "2016-11-16 03:00:00" c 2016-11-18 "2016-11-18 04:00:00" d` To this: timestamps values 2016-11-15 "2016-11-15 01:00:00" a 2016-11-16 "2016-11-16 02:00:00" b 2016-11-16 "2016-11-16 03:00:00" c 2016-11-17 NaN NaN 2016-11-18 "2016-11-18 04:00:00" d

http://stackoverflow.com/comment/90030010
has text: Could you post the code as text? And did you redefine f to be anything else?
comment on: http://stackoverflow.com/q/51531061
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51575090
type: Question
has answer: http://stackoverflow.com/a/67496900
tagged with: indexing
has answer: http://stackoverflow.com/a/51575197
has answer: http://stackoverflow.com/a/51585177
has comment: http://stackoverflow.com/comment/90115916
downvote count: 0
favorite count: 0
tagged with: multidimensional-array
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51575319
has title: Indexing nested list by a list
has body: given a nested list like &gt;&gt;&gt; m= [[3, 1], [2, 7]] I can get an element like this &gt;&gt;&gt; m[1][0] 2 How can i get the same value if the index is given in a list, i.e. as [1, 0]? I am looking for something that the Q programming language offers with dot like in code below q) m: (3 1; 2 7) q) m[1][0] 2 q) m . 1 0 2
answer count: 4
score: 2
tagged with: nested-lists
upvote count: 2

http://stackoverflow.com/a/51579058
downvote count: 0
type: Answer
upvote count: 1
has body: Just call proc.kill() then proc.communicate() to finish reading.
accepted answer of: http://stackoverflow.com/q/51579002
score: 1
answers question: http://stackoverflow.com/q/51579002
has comment: http://stackoverflow.com/comment/90124077
type: AcceptedAnswer

http://stackoverflow.com/a/51591357
has comment: http://stackoverflow.com/comment/90151636
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51590818
answers question: http://stackoverflow.com/q/51590818
type: Answer
has body: Consider closing files when you're finished (or use with-as). Also not sure why you calculate position to truncate (on 'a' mode) at the end of appending. import csv import json fieldnames = ("CustomerNo", "SalesOrder", "Brand", "Item", "Qty", "Month", "time") # Handle the case when there is no newline at the end. Format a file before appending. with open('daily.csv', 'r') as csvfile1: with open('test3.json', 'a') as jsonfile1: for row in csv.DictReader(csvfile1, fieldnames): json.dump(row, jsonfile1) jsonfile1.write('\n')
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90148423

http://stackoverflow.com/comment/90207870
has text: It is a very long tree and I am struggling to export it to anything other than the terminal. What to do ? :-( Could I send you the zip file?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51606413
type: Comment

http://stackoverflow.com/a/51617712
has comment: http://stackoverflow.com/comment/90201071
type: Answer
answers question: http://stackoverflow.com/q/51617406
has comment: http://stackoverflow.com/comment/90201140
has comment: http://stackoverflow.com/comment/90201495
score: 0
type: AcceptedAnswer
has body: If you don't mind the extra work, you can step through the range of values: z = [t for t in range(min(x), max(x)+1) if t in x and t in y] This iterates over the range of one list, considering each value exactly once.
accepted answer of: http://stackoverflow.com/q/51617406

http://stackoverflow.com/q/51500621
has body: I have a dataframe with 4 columns: 'age_1', 'name_1', 'age_2' and 'name_2'. df = pd.DataFrame(index=[0, 4, 6, 9], data={'age_1': [18, np.nan, 12, np.nan], 'name_1': ['Fred', np.nan, 'Harry', np.nan], 'age_2': [np.nan, 34, np.nan, 45], 'name_2': [np.nan, 'Jim', np.nan, 'Fred']}) Output age_1 name_1 age_2 name_2 0 18.0 Fred NaN NaN 4 NaN NaN 34.0 Jim 6 12.0 Harry NaN NaN 9 NaN NaN 45.0 Fred All names appear twice (once in name_1 and once in name_2) I want to put the rows together where name_1 and name_2 have the same item in. For example from the snippet above, i want it to put the first and last row together like this: age_1 name_1 age_2 name_2 0 18.0 Fred 45.0 Fred Any help would be great
has answer: http://stackoverflow.com/a/51501021
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/51501289
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51501021
type: Question
has title: Pandas - How to match up rows if they contain the same value
has answer: http://stackoverflow.com/a/51500856
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51500856
score: 2
downvote count: 0

http://stackoverflow.com/q/51544427
tagged with: pandas
has title: Trying to us str.contains and boolean mask but for only two instances of single value in Pandas
downvote count: 0
tagged with: string
favorite count: 0
has body: What I am trying to do is keep all rows with the same unique ID IF any of those rows contain only two instances of “ – “ in the Yurt column. I'm thinking of using a str.contains and a boolean mask by doing the following: df[df['ID'].isin(df.loc[df.Yurt.str.contains('-'), 'ID'].unique())] ...but unsure of how I'd only keep rows with only two instances with no value. Example df: ID % Yurt abc123 0.833 Bodega abc123 0.87 - abc123 0.867 - abc123 0.812 - lmn789 0.837 Mickey's lmn789 0.856 Chopped Cheese lmn789 0.813 - lmn789 0.812 - xyz456 0.111 - xyz456 0.222 - xyz456 0.333 - xyz456 0.444 - Result df: ID % Yurt lmn789 0.837 Mickey's lmn789 0.856 Chopped Cheese lmn789 0.813 - lmn789 0.812 -
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51544531
score: 2
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51544615
tagged with: boolean
answer count: 2
tagged with: pandas-groupby

http://stackoverflow.com/q/51484600
tagged with: python
answer count: 0
linked to: http://stackoverflow.com/q/48976523
type: Question
has comment: http://stackoverflow.com/comment/89940037
has comment: http://stackoverflow.com/comment/89944139
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/89939349
has body: Looking to index a (N, M) array by taking a certain rows (indicated by an array of row index values) and take a slice from the columns with a fixed start and varying stop indices. population = np.full((N,M), 0) #population of N guys with genome length M #Choose some guys and change parts of their genome (cols) rows_indices = [0,1,5,6] #four guys 0,1,5,6 will be changed #all selected guys will have a start of 10 #the ends will be difference for each guy slice_lengths = np.random.geometric(p=0.8, size = 4) #vector of 4 What I imagine is something like: population[0, 10: 10+ slice_length[0]] = 100 population[1, 10: 10+ slice_length[1]] = 100 population[2, 10: 10+ slice_length[2]] = 100 population[3, 10: 10+ slice_length[3]] = 100 Except vectorized without hardcoding each value #false code population[rows_indices, start: start + slice_length]
has comment: http://stackoverflow.com/comment/89952375
has title: Numpy Dynamic Indexing With Both Slicing and Advanced Indexing
type: UnansweredQuestion

http://stackoverflow.com/q/51618228
has answer: http://stackoverflow.com/a/51618423
type: Question
tagged with: if-statement
has body: I am trying to loop through a pandas dataframe column and based on if the next row down does not include "Property Address" add the information from that next row down to the previous row. For example, if I have a column that goes from top to bottom ["Property Address", "Alternate Address", "Property Address"] I would like to take the information from "Alternate Address" and add that information to the column above it ("Property Address"). I have already double checked that there are no trailing or leading spaces and that everything is lower case so that all comparisons will work. However, I still get this error: if i == "Property Address" and df.loc[i+1, :] != "Property Address": TypeError: must be str, not int Does anyone have ideas on what I can do so that this will work? I am new to Python, and I am really lost. Please let me know if there is any more information that I should provide to make answering this question easier. Thanks Here is my code so far: import pandas as pd import time df = pd.read_excel('BRH.xls') # Reads the Excel File and creates a dataframe # Column Headers df = df'street', 'state', 'zip', 'Address Type', 'mStreet', 'mState', 'mZip' propertyAddress = "Property Address" # iterates thru column and replaces the current row with info from next row down for i in df['Address Type']: if i == "Property Address" and df.loc[i+1, :] != "Property Address": df['mStreet'] == df.loc[i + 1, 'street'] df['mState'] == df.loc[i + 1, 'state'] df['mZip'] = df.loc[i + 1, 'zip'] df.to_excel('BRHOut.xls') print('operation complete in:', time.process_time(), 'ms')
tagged with: dataframe
score: 0
answer count: 2
tagged with: for-loop
tagged with: pandas
has title: How to iterate through pandas columns and replace cells with information with the next row down
has comment: http://stackoverflow.com/comment/90202269
has answer: http://stackoverflow.com/a/51619286
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51537746
has title: Sockets server and client in the same python script
has body: The below code does not work, when I keep both socket server and client code in the same script file where I run server in the main thread and the client in a separate thread using start_new_thread import socket, sys from thread import * host = socket.gethostname() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((host, 8888)) except socket.error as msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() s.listen(10) def clientthread(conn): conn.send('Welcome to the server. Type something and hit enter\n') while True: data = conn.recv(1024) reply = 'OK...' + data if not data: break conn.sendall(reply) conn.close() while 1: conn, addr = s.accept() print 'Connected with ' + addr[0] + ':' + str(addr[1]) start_new_thread(clientthread ,(conn,)) s.close()
favorite count: 0
type: Question
tagged with: sockets
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/51539541
has comment: http://stackoverflow.com/comment/90046541
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90043346
type: UnansweredQuestion
upvote count: 0

http://stackoverflow.com/comment/90054254
comment on: http://stackoverflow.com/q/51543218
type: Comment
type: QuestionComment
has text: `response_data = response.get('reports', [])[0] ` This is probably not a dataframe, but a dict. Thus the error "dict" object has no attribute to_csv.
score: 2

http://stackoverflow.com/comment/90096448
comment on: http://stackoverflow.com/q/51564738
type: Comment
type: QuestionComment
has text: Because the bitwise operators are distinct from the boolean logical operators, I don't know why you *expected* them to be the same. Also, your output is incorrect for the union. The logical operator should be first
score: 0

http://stackoverflow.com/a/54197184
upvote count: 1
has comment: http://stackoverflow.com/comment/135983962
has body: I have been using sharepy library as an alternative solution in connecting to Sharepoint. Use pip install sharepy to install the module. import sharepy from sharepy import connect from sharepy import SharePointSession server='youraccount.sharepoint.com' user='username@domain.com' password='password' s = sharepy.connect(server,user,password) # Example request to Sharepoint headers = {'accept': 'application/atom+json'} #json can be changed to xml r = s.get("https://youraccount.sharepoint.com/_api/web/GetFolderByServerRelativeUrl('path_to_your_folder/')/Files", headers=headers) It should print out the following on successful authentication: Requesting security token...Requesting access cookie... Authentication successful
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/126251847
answers question: http://stackoverflow.com/q/51500420
score: 1
has comment: http://stackoverflow.com/comment/131294914
has comment: http://stackoverflow.com/comment/135969734

http://stackoverflow.com/comment/90028241
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51529615
has text: Does it work on Linux, e.g. `curl 127.0.0.1:8000`?
type: Comment

http://stackoverflow.com/a/51609649
has body: I my opinion here is necessary another groupby with bfill for avoid replace NaNs for only NaNs group from another one. For performance is used this code: In [205]: %timeit df1[some_cols] = df1.groupby(group_key)[some_cols].transform(ffbf) 443 ms ± 7.26 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [206]: %timeit df[[group_key] + some_cols] = df[[group_key] + some_cols].groupby(group_key).ffill().groupby(group_key).bfill() 5.69 ms ± 31.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) np.random.seed(785) N = 10000 df = pd.DataFrame({'key':np.random.randint(1000, size=N), 'A':np.random.choice([1,2,np.nan], size=N), 'B':np.random.choice([1,4,np.nan], size=N), 'C':np.random.choice([7,0,np.nan], size=N), 'D':np.random.choice([7,0,8], size=N)}) df = df.sort_values('key') print (df) def ffbf(x): return x.ffill().bfill() group_key = 'key' some_cols = ['A','B','C'] df1 = df.copy() df1[some_cols] = df1.groupby(group_key)[some_cols].transform(ffbf) #a bit chamgef solution for working in pandas 0.23.1 df[[group_key] + some_cols] = df[[group_key] + some_cols].groupby(group_key).ffill().groupby(group_key).bfill() print (df.equals(df1)) True EDIT: In next pandas versions (test pandas 1.1.1) is possible use: df[[group_key] + some_cols] = df[[group_key] + some_cols].groupby(df[group_key]).ffill().groupby(df[group_key]).bfill()
accepted answer of: http://stackoverflow.com/q/51604819
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/113248764
has comment: http://stackoverflow.com/comment/90184154
has comment: http://stackoverflow.com/comment/90215421
has comment: http://stackoverflow.com/comment/113249151
answers question: http://stackoverflow.com/q/51604819
has comment: http://stackoverflow.com/comment/90197333
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/90184283

http://stackoverflow.com/q/51501579
tagged with: python
tagged with: http://stackoverflow.com/tag/png
upvote count: 0
has title: How do I convert a .png file to a multi-part file?
tagged with: python-requests
type: Question
type: AnsweredQuestion
has body: I have a .png file that I am pulling from a server, and I want to post that file to another server using an API which calls for a multi-part file as its parameter. Are .png files already considered multi-part, or do I need to manipulate the response data in some way?
score: -2
has comment: http://stackoverflow.com/comment/89972485
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/51501680
accepted answer: http://stackoverflow.com/a/51501680
favorite count: 0

http://stackoverflow.com/comment/90001098
comment on: http://stackoverflow.com/a/51515893
type: AnswerComment
has text: I wish to do this. those "label" with values should take back its own values while at the same time I wish to include 2-3 more "label" with empty list. string 1 {"label": "new"}, string2{"label":[]} , string 3 {"label": []}
type: Comment
score: 0

http://stackoverflow.com/comment/90226282
comment on: http://stackoverflow.com/q/51631105
type: Comment
type: QuestionComment
has text: Please provide code, so we can see where you can fix it. Probably a minimal GUI with two buttons extracted from you code should be enough.
score: 1

http://stackoverflow.com/comment/90186556
has text: Your accuracy formula looks right to me please provide more code
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51503851

http://stackoverflow.com/q/51559974
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/51560306
has body: I'm trying to split a Series into sections where each section is contiguous and has the same index. So for this input: df = pd.Series([1,2,3,4,5,6,7], index=[1,1,1,2,2,1,1]) The desired result would be three chunks like: [[1,2,3], [4,5], [6,7]] I was attempting to use groupby but that groups the [1,2,3] and the [6,7] into one section which is not desired since they aren't contiguous: &gt;&gt;&gt; groups = list(df.groupby(df.index, sort=False)) &gt;&gt;&gt; len(groups) 2 Can this be done in Pandas (or Numpy)?
downvote count: 0
type: Question
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51560113
accepted answer: http://stackoverflow.com/a/51560113
has comment: http://stackoverflow.com/comment/90087275
tagged with: numpy
has answer: http://stackoverflow.com/a/51560306
answer count: 2
has title: Split pandas Series into contiguous chunks by index value
favorite count: 0
upvote count: 3
tagged with: pandas-groupby

http://stackoverflow.com/q/51504789
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89979152
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89979221
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89979400
tagged with: python
tagged with: dictionary
has body: I have a excel worksheet as shown in figure It has 3 classes C1,C2 and C3 where C1 is the main class and here its only one as Cars but it could be multiple. C2 is the category of C1 and C3 is the sub-category of C1. Is there any way I can convert this data into some good readable format something like nested dictionaries so I iterate over these classes using for loop? I have tried to convert it using: from xlrd import open_workbook auto_cars=[] def parse_xlsx(): workbook = open_workbook('C:/Users/Downloads/TAXONOMY.xlsx') sheets = workbook.sheet_names() active_sheet = workbook.sheet_by_name(sheets[1]) num_rows = active_sheet.nrows num_cols = active_sheet.ncols header = [active_sheet.cell_value(0, cell).lower() for cell in range(num_cols)] for row_idx in range(1, num_rows): row_cell = [active_sheet.cell_value(row_idx, col_idx) for col_idx in range(num_cols)] yield dict(zip(header, row_cell)) for row in parse_xlsx(): auto_cars.append(row) Which gives confusing output as: [{'c1': 'Cars ', 'c2': 'Class', 'c3': 'muv'}, {'c1': '', 'c2': '', 'c3': 'hatchback'}, {'c1': '', 'c2': '', 'c3': 'suv'}, {'c1': '', 'c2': '', 'c3': 'sedan'}, {'c1': '', 'c2': '', 'c3': 'coupe'}, {'c1': '', 'c2': '', 'c3': 'convertible'}, {'c1': '', 'c2': 'Fuel Type', 'c3': 'electric'}, {'c1': '', 'c2': '', 'c3': 'diesel'}, {'c1': '', 'c2': '', 'c3': 'cng'}, {'c1': '', 'c2': '', 'c3': 'petrol'}, {'c1': '', 'c2': '', 'c3': 'lpg'}, {'c1': '', 'c2': '', 'c3': 'hybrid'}, {'c1': '', 'c2': 'Brand', 'c3': 'ashok leyland'}, {'c1': '', 'c2': '', 'c3': 'audi'}, {'c1': '', 'c2': '', 'c3': 'bmw'}, {'c1': '', 'c2': '', 'c3': 'bentley'} .................................. .................................
has comment: http://stackoverflow.com/comment/89979031
answer count: 0
score: 1
upvote count: 1
has title: Creating a python nested dictionaries from excel multiple columns
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/89978648
tagged with: xlrd

http://stackoverflow.com/comment/90051701
type: QuestionComment
has text: https://stackoverflow.com/help/how-to-ask
comment on: http://stackoverflow.com/q/51541895
score: 0
type: Comment

http://stackoverflow.com/a/51571916
has body: You should read the docs for Merge. Basically MERGE INTO TargetTable USING SourceTable ON TargetTable.id = SourceTable.id .... Then you can read the docs about using When not marched by Target etc. So your Python would maybe swap out the table names and joins using params
score: 0
answers question: http://stackoverflow.com/q/51562033
type: Answer

http://stackoverflow.com/a/51626665
has comment: http://stackoverflow.com/comment/90218124
has body: There are three type of File operation mode can happen on file like read, write and append. Read Mode: In this you only able to read the file like #content in file.txt "Hi I am Python Developer" with open('file.txt', 'r') as f: data = f.read() print(data) #output as : Hi I am Python Developer Write Mode: In this you are able to write information into files, but it will always overwrite the content of the file like for example. data = input('Enter string to insert into file:') with open('file.txt', 'w') as f: f.write(data) with open('file.txt', 'r') as f: data = f.read() print('out_data:', data) # Output : Enter string to insert into file: Hi, I am developer # out_data: Hi, I am developer When you open file for next time and do same write operation, it will overwrite whole information into file. Append Mode: In this you will able to write into file but the contents is append into this files. Like for example: data = input('Enter string to insert into file:') with open('file.txt', 'a') as f: f.write(data) with open('file.txt', 'r') as f: data = f.read() print('out_data:', data) # Output : Enter string to insert into file: Hi, I am developer # out_data: Hi, I am developer # Now perform same operation: data = input('Enter string to insert into file:') with open('file.txt', 'a') as f: f.write(data) with open('file.txt', 'r') as f: data = f.read() print('out_data:', data) # Output : Enter string to insert into file: Hi, I am Python developer # out_data: Hi, I am developer Hi, I am Python Developer
score: 0
answers question: http://stackoverflow.com/q/51626372
type: Answer

http://stackoverflow.com/q/51503345
downvote count: 1
has answer: http://stackoverflow.com/a/51503449
has comment: http://stackoverflow.com/comment/89975366
favorite count: 0
linked to: http://stackoverflow.com/q/37232008
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51503459
has body: I have a .txt file that looks like this: 08/19/93 UW ARCHIVE 100.0 1962 W IEEE 14 Bus Test Case BUS DATA FOLLOWS 14 ITEMS 1 Bus 1 HV 1 1 3 1.060 0.0 0.0 0.0 232.4 -16.9 0.0 1.060 0.0 0.0 0.0 0.0 0 2 Bus 2 HV 1 1 2 1.045 -4.98 21.7 12.7 40.0 42.4 0.0 1.045 50.0 -40.0 0.0 0.0 0 3 Bus 3 HV 1 1 2 1.010 -12.72 94.2 19.0 0.0 23.4 0.0 1.010 40.0 0.0 0.0 0.0 0 4 Bus 4 HV 1 1 0 1.019 -10.33 47.8 -3.9 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 5 Bus 5 HV 1 1 0 1.020 -8.78 7.6 1.6 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 6 Bus 6 LV 1 1 2 1.070 -14.22 11.2 7.5 0.0 12.2 0.0 1.070 24.0 -6.0 0.0 0.0 0 7 Bus 7 ZV 1 1 0 1.062 -13.37 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 8 Bus 8 TV 1 1 2 1.090 -13.36 0.0 0.0 0.0 17.4 0.0 1.090 24.0 -6.0 0.0 0.0 0 9 Bus 9 LV 1 1 0 1.056 -14.94 29.5 16.6 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.19 0 10 Bus 10 LV 1 1 0 1.051 -15.10 9.0 5.8 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 11 Bus 11 LV 1 1 0 1.057 -14.79 3.5 1.8 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 12 Bus 12 LV 1 1 0 1.055 -15.07 6.1 1.6 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 13 Bus 13 LV 1 1 0 1.050 -15.16 13.5 5.8 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 14 Bus 14 LV 1 1 0 1.036 -16.04 14.9 5.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 I need to remove the characters from this file and need only the numerical data in a matrix form. I am relatively new to python, so any kind of help will be really appreciated. Thank you.
upvote count: 0
has comment: http://stackoverflow.com/comment/89981953
linked to: http://stackoverflow.com/q/40987210
has title: Separating strings from numerical data in a .txt file by python
type: Question
tagged with: cdf
duplicate of: http://stackoverflow.com/q/37232008
has comment: http://stackoverflow.com/comment/89975319
score: -1
has comment: http://stackoverflow.com/comment/89975313
answer count: 2
has comment: http://stackoverflow.com/comment/89975497

http://stackoverflow.com/q/51524365
has body: My Python script updates Oracle passwords regularly using the command alter user my_user identified by "new_password" replace "old_password" Now I need to update these passwords in the SQL Developer connection definitions. I have looked all over my Windows 7 machine but nowhere can I find Connections.xml, nor IDEConnections.xml. And if so, the passwords would be encrypted. Can anybody automate password updates for SQL Developer?
type: Question
tagged with: passwords
has answer: http://stackoverflow.com/a/51544618
has answer: http://stackoverflow.com/a/51528199
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/1032721
type: UnansweredQuestion
tagged with: oracle-database
tagged with: python
tagged with: oracle-sqldeveloper
has title: Can Python update Passwords for Oracle SQL Developer Connections

http://stackoverflow.com/q/51501927
has body: I'm a relative beginner in web dev and javascript and I've made a flask app that takes in a user form and puts the data in a table. However, when I reload the template containing the table, the form resubmits. I know that I have to implement a post/redirect/get system and I understand the logic behind it, but in terms of code, I just don't know what I should do. #New Order Page @app.route('/new-cad-order', methods=['GET', 'POST']) def CAD_order(): if request.method == 'POST': Order_ID = request.form['Order_ID'] Order_Date = request.form['Order_Date'] Customer_Name = request.form['Customer_Name'] Order_Balance_Without_Tax = request.form['Order_Balance_Without_Tax'] Delivery_Date = request.form['Delivery_Date'] Final_Order_Balance_With_Tax = request.form['Final_Order_Balance_With_Tax'] Payment_Date = request.form['Payment_Date'] Check_Number = request.form['Check_Number'] Deposit_Date = request.form['Deposit_Date'] Verification_Date = request.form['Verification_Date'] key = 'Allow' #Processing the data return render_template('tracking.html', ID=Order_ID, OrderDate=Order_Date, CustomerName=Customer_Name, OrderBalance=Order_Balance_Without_Tax, Downpayment=Downpayment_Balance, Delivery=Order_Delivered, DeliveryDate=Delivery_Date, FinalOrderBalance=Final_Order_Balance_With_Tax, RCheck=Revenue_Check, PReceival=Payment_Received, PaymentDate=Payment_Date, CheckNum=Check_Number, Deposit=Bank_Deposit, DepositDate=Deposit_Date, Ver=Verification, VerDate=Verification_Date, key=key) return render_template('CAD_order.html')
answer count: 1
has answer: http://stackoverflow.com/a/51502471
type: UnansweredQuestion
tagged with: python
tagged with: post-redirect-get
has title: Implementing POST/REDIRECT/GET on flask backend
type: Question
tagged with: flask
score: 0

http://stackoverflow.com/q/51506656
tagged with: python
tagged with: regex
score: 1
has answer: http://stackoverflow.com/a/51507653
linked to: http://stackoverflow.com/q/7293750
has answer: http://stackoverflow.com/a/51511740
upvote count: 2
has comment: http://stackoverflow.com/comment/90019847
accepted answer: http://stackoverflow.com/a/51507653
has body: test_str = '**Amount** : $25k **Name** : James' expected output: output: Amount: $25k, Name: James I can only use re.sub function to remove/replace delimiters **words** but cannot get the expected result. Also, is it possible to generalize the code to implement on all delimiters (**xx**, &lt; xx>, etc)?
downvote count: 1
has comment: http://stackoverflow.com/comment/89985994
has title: Python Regex: words between two delimiters - replace leading delimiters with punctuation, but removing ending ones
has comment: http://stackoverflow.com/comment/89983346
answer count: 4
has comment: http://stackoverflow.com/comment/89983928
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51506779
has answer: http://stackoverflow.com/a/51506779
favorite count: 0
has answer: http://stackoverflow.com/a/51506832
type: Question
has comment: http://stackoverflow.com/comment/89982365
has comment: http://stackoverflow.com/comment/89983518

http://stackoverflow.com/comment/89998665
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51515164
has text: Do you know the variables in the expression, or do you have to find those out first? Also, can the expression be "trusted", i.e. could you just `eval` it?

http://stackoverflow.com/a/51577539
has body: You are not calling the function, you need to call the function using result = minutes_to_hours(name) . Also, it will not print out hours because it is after the return statement. These should be the other way round. Note: you can remove the parameter name from the function as you do not use it in the function.
has comment: http://stackoverflow.com/comment/90156716
answers question: http://stackoverflow.com/q/51577524
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/51484983
has comment: http://stackoverflow.com/comment/89939162
has comment: http://stackoverflow.com/comment/89939495
type: Question
has comment: http://stackoverflow.com/comment/89938913
has comment: http://stackoverflow.com/comment/89939198
has comment: http://stackoverflow.com/comment/89939097
has comment: http://stackoverflow.com/comment/89939265
has comment: http://stackoverflow.com/comment/89939073
has title: Defining variables as start and end times WITHOUT dates-Python
has comment: http://stackoverflow.com/comment/89939471
has comment: http://stackoverflow.com/comment/89939308
has answer: http://stackoverflow.com/a/51485034
has comment: http://stackoverflow.com/comment/89939218
has comment: http://stackoverflow.com/comment/89939072
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89939119
has comment: http://stackoverflow.com/comment/89938982
favorite count: 0
tagged with: time
has comment: http://stackoverflow.com/comment/89938935
has body: I'm attempting to define two variables (StartTime, and EndTime) as fixed times WITHOUT dates. They will be used to start and stop a loop. I have had a difficult time formatting these variables due to issues with datetime versus strings etc. Here is a rough idea of my code and what I have tried: Version 1.0: strptime import time import datetime as dt currenttime=dt.datetime.now() StartTime=dt.datetime.strptime('8:00:00 AM','%I:%M:%S %p') EndTime=dt.datetime.strptime('5:00:00 PM','%I:%M:%S %p') timemargin = dt.timedelta(seconds=60) if(StartTime-timemargin)&lt;currenttime&lt;(StartTime+timemargin) AND(EndTime- timemargin)&lt;currenttime&lt;(EndTime+timemargin): 'do something' V1.0 Outputs: StartTime datetime.datetime(1900, 1, 1, 8, 0) EndTime datetime.datetime(1900, 1, 1, 17, 0) Now this is not ideal because I only want to compare the time NOT the date. How can I declare a variable ONLY as time and not as a date and time? This also applies for currenttime. I know strftime is an option, but I am not sure if it will apply here. I have also seen other methods involving something along the lines of: StartTime.minute to call the minute, but I'm not sure how to use this for my application. Any recommendations?
tagged with: datetime
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51485034
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/51621459
upvote count: 1
has body: If I understand your question, you want to dynamically recalculate the content of the plot (the coordinates) based on the current axis pan / zoom. Doing so requires using event handling to detect a change in axis limits, then recalculate the coordinates with a predefined number of points between these limits, and finally updating the plot accordingly import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np def my_func(x): return (2 * x) ** 2 + 2 * x + 4 def on_lims_change(axes): xmin, xmax = axes.get_xlim() new_x = np.linspace(xmin, xmax, 1000) new_y = my_func(new_x) l.set_data(new_x, new_y) fig, ax = plt.subplots() xcoord = np.linspace(0, 10, 1000) ycoord = my_func(xcoord) l, = ax.plot(xcoord, ycoord, 'r-') ax.callbacks.connect('xlim_changed', on_lims_change) ax.callbacks.connect('ylim_changed', on_lims_change) on_lims_change(ax) plt.show() Credits go to @ImportanceOfBeingErnest for showing how to connect an event handler on changes to the axes limits in this answer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51620286
score: 1

http://stackoverflow.com/q/51503848
has title: Need Moving Average Height in OHLC data without creating additional column
tagged with: python
tagged with: python-3.x
type: AnsweredQuestion
has body: I need to find the Moving Average Height (abs(Close-Open)) for last 5 days. I have daily OHLC data. An easy solution would be to first create a column Height and then calculate 5 days moving average using the rolling function. But this makes my code inefficient. I need to find the Moving average height without creating a new column. My data looks like below and expected output is in column 'Average Height': Date Open High Low Close Average Height 01-01-2018 1763.95 1763.95 1725 1731.35 02-01-2018 1736.2 1745.8 1725 1743.2 03-01-2018 1741.1 1780 1740.1 1774.6 04-01-2018 1779.95 1808 1770 1801.35 05-01-2018 1801.1 1820.4 1795.6 1809.95 20.67 08-01-2018 1816 1827.95 1800 1825 15.95 09-01-2018 1823 1835 1793.9 1812.05 16.74 10-01-2018 1812.05 1823 1801.4 1816.55 10.94 11-01-2018 1825 1825.05 1798.55 1802.1 11.24 12-01-2018 1805 1820 1794 1804.95 9.48 15-01-2018 1809.9 1834.45 1792.45 1830 11.7 16-01-2018 1835 1857.45 1826.1 1850.25 12.56 17-01-2018 1850 1852.45 1826.2 1840.5 13.56 18-01-2018 1840.5 1852 1823.5 1839 9.28 19-01-2018 1828.25 1836.35 1811 1829.5 9.52 The current code I am using is as below snippet: df['Avg Height'] = df[abs(df['Close'] - df['Open'])].rolling(window = 5).mean() But of course, it looks incorrect since I am getting an error.
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/51504058
answer count: 1
has comment: http://stackoverflow.com/comment/89976473
score: 0
has answer: http://stackoverflow.com/a/51504058
tagged with: pandas
has comment: http://stackoverflow.com/comment/89976652

http://stackoverflow.com/comment/90210608
score: 0
type: QuestionComment
type: Comment
has text: In the upper right hand corner of PyCharm it will show `[file name].py`, click on that. It will pop open a window whose title is `Run/Debug Configurations`. In the Configuration tab, it should have a section called `Python Interpreter`. Is it using Anaconda, Python, or your virtual environment?
comment on: http://stackoverflow.com/q/51622423

http://stackoverflow.com/comment/90156292
score: 1
has text: Very nice answer!
comment on: http://stackoverflow.com/a/51595245
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51517626
tagged with: python
has title: Python Vlookup to return one value only - similar to excel
tagged with: jinja2
downvote count: 1
has answer: http://stackoverflow.com/a/72099434
type: AnsweredQuestion
score: -1
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51556838
upvote count: 0
has body: I'm trying to replicate an Excel Vlookup in Python, using Flask. I've an excel sheet, set out like this: (Item is column A, Price is column B). Item: Price: Keyboard £10 Mouse £5 Mousemat £5 Beer £4 Now in Excel, if I had want to know the Price of Mouse, and that was typed in on cell C1, I'd do: =VLOOKUP(C1,A2:B5,2,FALSE) That'd return me £5. This is exactly what I want to do, but in Python. I've read some tutorials online, that points me in the direction of Pandas and xlrd, but this appears to be merging two columns together. This isn't what I want. I want it to only display the result, as i've done in my excel example above This is because I want to display this result in a Jinja template. FYI, the value "Mouse" will be input by a user, and the list will be massive. Hence my involvement of an Excel spreadsheet.
tagged with: flask
favorite count: 0
possible better answer: http://stackoverflow.com/a/72099434
has answer: http://stackoverflow.com/a/51556838

http://stackoverflow.com/q/51617284
has answer: http://stackoverflow.com/a/54797115
has answer: http://stackoverflow.com/a/51638553
has answer: http://stackoverflow.com/a/66934224
has answer: http://stackoverflow.com/a/54737235
type: Question
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/54664780
has title: Could not install packages due to an EnvironmentError: [Errno 2]
has body: I`ve recently started having problems with pip installs. Every time I run this kind of command in Terminal, I get an error: Could not install packages due to: EnvironmentError: [Errno 2] No such file or directory: '/'me'/'me'/anaconda3/lib/python3.6/site-packages/tqdm-4.11.2.dist-info/METADATA' Does anyone know what's wrong? Didn't have this issue a month ago. Please help! Just in case: the error above popped up when i wrote pip install gender-guesser.
has answer: http://stackoverflow.com/a/55566403
accepted answer: http://stackoverflow.com/a/51638553
score: 14
tagged with: python
possible better answer: http://stackoverflow.com/a/53571785
has answer: http://stackoverflow.com/a/53571785
upvote count: 14
has answer: http://stackoverflow.com/a/69344379
tagged with: installation
tagged with: pip
has comment: http://stackoverflow.com/comment/90207971
answer count: 8
type: AnsweredQuestion

http://stackoverflow.com/comment/89973643
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51502562
type: AnswerComment
has text: Put differently: **you can do what the OP wants, trivially**, but the OP shouldn't.

http://stackoverflow.com/q/51554733
answer count: 3
has comment: http://stackoverflow.com/comment/90077041
has title: How to assign values to a numpy array as a function of index?
tagged with: arrays
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51554902
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/90076899
tagged with: python
linked to: http://stackoverflow.com/q/41900738
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51554900
type: Question
has answer: http://stackoverflow.com/a/51558625
tagged with: performance
has answer: http://stackoverflow.com/a/51554902
score: 4
has body: I can only find results that use tuples of coordinates to assign certain values, like this one. I want to assign values to a 2-dimensional array as a function of their coordinates. The simplest case would be to set the value of each element to their second index (e.g. x-coordinate). Such that, x[0][0] = 0 x[1][0] = 0 ... x[2][0] = 0 x[0][1] = 1 x[0][2] = 2 ... More complex case would be to set these values to the Euclidean distance to a certain point (x, y). My current solution is to use a for-loop, which is definitely not efficient. A vectorized implementation would be nice. My current implementation: x_mask = np.zeros((256, 256)) for i in range(256): for j in range(256): x_mask[i][j] = j
possible better answer: http://stackoverflow.com/a/51558625
upvote count: 4
tagged with: numpy

http://stackoverflow.com/comment/90126488
has text: @ggdx in the (venv) ?
comment on: http://stackoverflow.com/q/51580577
score: 0
type: Comment
type: QuestionComment

azure
tags question: http://stackoverflow.com/q/51576894
tags question: http://stackoverflow.com/q/51559555
tags question: http://stackoverflow.com/q/51633759
tags question: http://stackoverflow.com/q/51599828
tags question: http://stackoverflow.com/q/51573241
tags question: http://stackoverflow.com/q/51488457
tags question: http://stackoverflow.com/q/51546073
tags question: http://stackoverflow.com/q/51564708
type: Tag
tags question: http://stackoverflow.com/q/51617438
tags question: http://stackoverflow.com/q/51541328
tags question: http://stackoverflow.com/q/51578921
tags question: http://stackoverflow.com/q/51619559
tags question: http://stackoverflow.com/q/51515925
tags question: http://stackoverflow.com/q/51590388
tags question: http://stackoverflow.com/q/51603606
tags question: http://stackoverflow.com/q/51566175
tag name: azure
tags question: http://stackoverflow.com/q/51507268

http://stackoverflow.com/q/51498789
type: Question
tagged with: mongodb
answer count: 2
score: 4
has title: Create mongodb user from python
favorite count: 0
accepted answer: http://stackoverflow.com/a/51501481
tagged with: python
upvote count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51498935
has answer: http://stackoverflow.com/a/51501481
downvote count: 0
has answer: http://stackoverflow.com/a/51498935
has body: I am trying to create a db user from Python with pymongo. But I keep getting pymongo.errors.OperationFailure: CMD_NOT_ALLOWED: createUser error client = MongoClient("mongodb+srv://username:password@mycluster-mogiz.mongodb.net/admin") db = client["testDB"] db.command("createUser", "user", pwd="password") am I missing something? Thanks. Note: my db is on Mongo Atlas don't know if this changes anything.
tagged with: pymongo

http://stackoverflow.com/a/51550604
has comment: http://stackoverflow.com/comment/90070112
has comment: http://stackoverflow.com/comment/90075677
upvote count: 1
has body: The reason why your code isn't doing what you want it to is here: if chance == 1: game1_running == True break if chance == 2: game2_running == True break if chance == 3: game3_running == True break == is used to test for equality, but you want to assign a value, so you should be using = instead. More generally, though, a while loop is better used in cases where you potentially want to repeat a set of actions numerous times until some condition is true. If you only want to repeat an action once, using if/else is more appropriate. The first while loop could be eliminated entirely as you have set it up so that it will only execute once. The main body of your game could thus be rewritten as follows: game1_running = False game2_running = False game3_running = False chance = random.randint(1, 3) if chance == 1: game1_running = True elif chance == 2: game2_running = True elif chance == 3: game3_running = True if game1_running == True: print(name1 + " Game 1 Active" + verb1 + noun1 + noun2 + adjective + verb2) game1_running = False elif game2_running == True: print(name1 + " Game 2 Active" + verb1 + noun1 + noun2 + adjective + verb2) game2_running = False elif game3_running == True: print(name1 + "Game 3 Active" + verb1 + noun1 + noun2 + adjective + verb2) game3_running = False Setting a condition (gameX_running) and then testing for it a moment later also represents an unneeded extra step, so you could combine these sets of if/else conditions: chance = random.randint(1, 3) if chance == 1: print(name1 + " Game 1 Active" + verb1 + noun1 + noun2 + adjective + verb2) # do other game 1 runtime stuff here elif chance == 2: print(name1 + " Game 2 Active" + verb1 + noun1 + noun2 + adjective + verb2) # game 2 runtime stuff elif chance == 3: print(name1 + "Game 3 Active" + verb1 + noun1 + noun2 + adjective + verb2) # game 3 runtime stuff An appropriate use for a while loop in a game situation like this might be to execute a number of games in a row, for example: n = 0 while n &lt; 1…
accepted answer of: http://stackoverflow.com/q/51550130
type: AcceptedAnswer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51550130
type: Answer

http://stackoverflow.com/q/51592546
tagged with: python
has comment: http://stackoverflow.com/comment/90150412
has title: System registry for python
downvote count: 2
type: Question
upvote count: 0
score: -2
has body: I got this code from Stack overflow but when I try to execute the command I get an error. The code and the error is given below. I would be grateful if someone could help: import sys from _winreg import * # tweak as necessary version = sys.version[:3] installpath = sys.prefix regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version) installkey = "InstallPath" pythonkey = "PythonPath" pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % ( installpath, installpath, installpath ) def RegisterPy(): try: reg = OpenKey(HKEY_CURRENT_USER, regpath) except EnvironmentError as e: try: reg = CreateKey(HKEY_CURRENT_USER, regpath) SetValue(reg, installkey, REG_SZ, installpath) SetValue(reg, pythonkey, REG_SZ, pythonpath) CloseKey(reg) except: print ("*** Unable to register!") return print ("--- Python", version, "is now registered!") return if (QueryValue(reg, installkey) == installpath and QueryValue(reg, pythonkey) == pythonpath): CloseKey(reg) print ("=== Python", version, "is already registered!") return CloseKey(reg) print ("*** Unable to register!") print ("*** You probably have another Python installation!") if __name__ == "__main__": RegisterPy() I get the following error: from __winreg import * Traceback (most recent call last): File "&lt;ipython-input-35-f6f8c1a0ffdd&gt;", line 1, in &lt;module&gt; from __winreg import * ModuleNotFoundError: No module named '__winreg'
answer count: 1
has answer: http://stackoverflow.com/a/51592594
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90008473
score: 1
comment on: http://stackoverflow.com/a/51518975
type: AnswerComment
type: Comment
has text: Thanks @Andras Deak, that works great - and I was looking for a way to avoid list comprehension with its `for` loop.

http://stackoverflow.com/q/51634008
duplicate of: http://stackoverflow.com/q/1623039
tagged with: pytmx
score: 0
tagged with: typeerror
has comment: http://stackoverflow.com/comment/90527737
upvote count: 1
downvote count: 1
has body: I am trying to use pyGame and pyTMX in pyCharm; however, I am getting an annoying error message whenever I try to run the program. The following code was def get_tile_properties(self, x, y, layer): """ Return the tile image GID for this location :param x: x coordinate :param y: y coordinate :param layer: layer number :rtype: python dict if found, otherwise None """ try: assert (x &gt;= 0 and y &gt;= 0 and layer &gt;= 0) except AssertionError: raise ValueError try: gid = self.layers[int(layer)].data[int(y)][int(x)] except (IndexError, ValueError): msg = "Coords: ({0},{1}) in layer {2} is invalid." logger.debug(msg.format(x, y, layer)) raise Exception else: try: return self.tile_properties[gid] except (IndexError, ValueError): msg = "Coords: ({0},{1}) in layer {2} has invalid GID: {3}" logger.debug(msg.format(x, y, layer, gid)) raise Exception except KeyError: return None Traceback (most recent call last): File "C:/Users/tett/Documents/Vietnam/test.py", line 16, in &lt;module&gt; properties = tmxdata.get_tile_properties(x, y, layer) File "C:\Users\tett\PycharmProjects\untitled\venv\lib\site- packages\pytmx\pytmx.py", line 568, in get_tile_properties assert (x &gt;= 0 and y &gt;= 0 and layer &gt;= 0) TypeError: '&gt;=' not supported between instances of 'TiledTileLayer' and 'int' I started learning pyGame two weeks before posting this so I know how tiled maps are way above my skill level. because of that, I copied this and some other code off of the pyTMX website. I believe tiled maps is the next most important thing I need to learn for my game before I move on. The code doesn't seem to work (for me at least) and that is why I am on here to see if anybody has a solution. I looked on Youtube, those tiled map tutorial videos didn't work and my solutions to fix this issue didn't work. The code I copied to call the pyTMX file looks like this. m1w1.tmx is the file I am trying to load. tmxdata = pytmx.TiledMap("m1w1.tmx") tiled_map = pytmx.TiledMap('m1w1.tmx') for layer in t…
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/90454651
type: UnansweredQuestion
tagged with: python
tagged with: pygame
has title: TypeError when running pyTMX in pycharm (pygame)
type: Question
linked to: http://stackoverflow.com/q/1623039
has comment: http://stackoverflow.com/comment/90532015

http://stackoverflow.com/a/51665902
has body: One approach I can suggest is using Google's NLP API. This API have feature of identifying Part of Speech as part of Syntax Analysis. Please refer to documentation here - Google's NLP API - Syntax Analysis Another option is Stanford's NLP API. Here are reference docs - Stanford's NLP API
score: 0
answers question: http://stackoverflow.com/q/51558862
has comment: http://stackoverflow.com/comment/90330234
type: Answer

http://stackoverflow.com/a/51629766
type: Answer
accepted answer of: http://stackoverflow.com/q/51629675
score: 0
has comment: http://stackoverflow.com/comment/90224932
answers question: http://stackoverflow.com/q/51629675
has body: I think this is what you want but you weren't very clear. You just need some nested for loops: iterate through the list, then the dictionaries and then the values list: lst = [{'abc.txt': ['abc', 'F']}, {'xyz.txt': ['xyz', 'F']}] for item in lst: for key, values in item.items(): print('key: {!r}'.format(key)) for index, value in enumerate(values): print('values[{}]: {!r}'.format(index, value)) outputs: key: 'abc.txt' values[0]: 'abc' values[1]: 'F' key: 'xyz.txt' values[0]: 'xyz' values[1]: 'F'
type: AcceptedAnswer

http://stackoverflow.com/comment/90236640
comment on: http://stackoverflow.com/q/51636107
type: Comment
has text: what if i want to pass an integer as an argument
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90072450
comment on: http://stackoverflow.com/q/51552706
type: Comment
type: QuestionComment
has text: *“can user in some way (doesn't need to be easy) access that Python code?”* Yes, and it’s easy, too.
score: 2

http://stackoverflow.com/q/51625090
score: 5
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90216403
favorite count: 0
tagged with: python-3.x
upvote count: 5
type: UnansweredQuestion
tagged with: python
has body: In "def same_child_values". I am trying to compare two trees to see if the other tree has same value nodes to the primary tree.children. In this case I am using a set to compare them. But in my code when the tree depth is greater than 1 then my code cannot add the nodes into the set correctly. Can anyone help me? class Tree: '''Tree ADT; nodes may have any number of children''' def __init__(self: 'Tree', item: object =None, children: list =None): '''Create a node with item and any number of children''' self.item = item if not children: self.children = [] else: self.children = children[:] def __repr__(self: 'Tree') -&gt; str: '''Return representation of Tree as a string''' if self.children: return 'Tree({0}, {1})'.format(repr(self.item), repr(self.children)) else: return 'Tree({})'.format(repr(self.item)) def is_leaf(self: 'Tree') -&gt; bool: '''Return True iff this Tree node is a leaf (has no children).''' return self.children == [] def remove_equal(self: 'Tree') -&gt; None: '''Remove every child that has the same item as its parent; any children of a removed node n become children of an ancestor of n. &gt;&gt;&gt; t = Tree(1, [Tree(2, [Tree(1), Tree(2)]), Tree(1)]) &gt;&gt;&gt; t.remove_equal() &gt;&gt;&gt; repr(t) 'Tree(1, [Tree(2, [Tree(1)])])' &gt;&gt;&gt; t = Tree(4, [Tree(4, [Tree(6)])]) &gt;&gt;&gt; t.remove_equal() &gt;&gt;&gt; repr(t) 'Tree(4, [Tree(6)])' &gt;&gt;&gt; t = Tree(4, [Tree(4, [Tree(4, [Tree(4)])])]) &gt;&gt;&gt; t.remove_equal() &gt;&gt;&gt; repr(t) 'Tree(4)' &gt;&gt;&gt; t = Tree(4, [Tree(4, [Tree(4, [Tree(6), Tree(7)]), Tree(8)]), Tree(9)]) &gt;&gt;&gt; t.remove_equal() &gt;&gt;&gt; repr(t) 'Tree(4, [Tree(6), Tree(7), Tree(8), Tree(9)])' ''' new_children = [] for c in self.children: c.remove_equal() if not c.item == self.item: new_children.append(c) else: new_children.extend(c.children) self.children = new_children # Q1: Complete this method (This was the last part of last week's lab. # If you did not have a chance to finish it last week, wor…
has title: Using set to count if two Tree have same values nodes
type: Question
has answer: http://stackoverflow.com/a/55348384

http://stackoverflow.com/q/51537682
type: Question
downvote count: 0
has title: How do I export an Estimator, tf.estimator.DNNClassifier
tagged with: tensorflow-estimator
has answer: http://stackoverflow.com/a/51539450
answer count: 3
has body: Hello guys this is my code, am still a beginner using tensorflow, this is my code am trying to run a text classification DNN until now everything is fine. I want to save my model and import it so i can use it to predict new values but I don't have any idea how to do it. To give you a genral idea on what am trying to do. I have 2 folders (training &amp; test) each folder has (4 folders (classification categories)) import tensorflow as tf import tensorflow_hub as hub import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import re import seaborn as sns import logging print("Loading all files from directory ...") # Load all files from a directory in a DataFrame. def load_directory_data(directory): data = {} data["sentence"] = [] data["tnemitnes"] = [] print("getting in a loop") for file_path in os.listdir(directory): with tf.gfile.GFile(os.path.join(directory, file_path), "r") as f: print("directory : ",directory) print("file path : ",file_path) data["sentence"].append(f.read()) data["tnemitnes"].append(re.match("(\d+)\.txt", file_path).group(1)) return pd.DataFrame.from_dict(data) print("merging all files in the training set ...") # Merge all type of emails examples, add a polarity column and shuffle. def load_dataset(directory): pos_df = load_directory_data(os.path.join("train/br")) neg_df = load_directory_data(os.path.join(directory, "train/mi")) dos_df = load_directory_data(os.path.join(directory, "train/Brouillons")) #dsd nos_df = load_directory_data(os.path.join(directory, "train/favoris")) #dsd pos_df["polarity"] = 3 neg_df["polarity"] = 2 dos_df["polarity"] = 1 nos_df["polarity"] = 0 return pd.concat([pos_df, neg_df, dos_df , nos_df]).sample(frac=1).reset_index(drop=True) print("Getting the data from files ...") # Download and process the dataset files. def download_and_load_datasets(): train_df = load_dataset(os.path.dirname("train")) test_df = load_dataset(os.path.dirname("test")) return train_df, test_df print("configurring all logg…
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51540810
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51977746
tagged with: tensorflow
score: 1
linked to: http://stackoverflow.com/q/33759623
tagged with: tensorflow-serving

http://stackoverflow.com/q/51486081
favorite count: 0
linked to: http://stackoverflow.com/q/30921570
has comment: http://stackoverflow.com/comment/90055326
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53375405
upvote count: 10
has title: Install and use RPy2 (using conda) so that it uses default R installation in /usr/lib/R R
tagged with: python
has comment: http://stackoverflow.com/comment/90282852
linked to: http://stackoverflow.com/q/1641477
downvote count: 0
has comment: http://stackoverflow.com/comment/90023043
has comment: http://stackoverflow.com/comment/89941617
has comment: http://stackoverflow.com/comment/90245563
type: Question
score: 10
tagged with: rpy2
tagged with: conda
tagged with: http://stackoverflow.com/tag/r
has body: I want to call functions from my R packages in Python using RPy2. I installed RPy2 using conda and realized it installed a fresh copy of R inside conda... I don't want that. I just want to have and use one R, the default one in /usr/lib/R. How to do that? How to force conda and Python and RPy2 to use default R installed in /usr/lib/R?
linked to: http://stackoverflow.com/q/2698269
answer count: 1

http://stackoverflow.com/comment/90179010
type: Comment
comment on: http://stackoverflow.com/q/51606518
type: QuestionComment
has text: Oh and who ever put the 'this has been answered before' message up there should go read it. It is specifically about ix and also has deprecated functions in it such as 'is_copy'
score: 0

http://stackoverflow.com/q/51497423
has comment: http://stackoverflow.com/comment/89962826
type: Question
has comment: http://stackoverflow.com/comment/89962877
has comment: http://stackoverflow.com/comment/89963029
has comment: http://stackoverflow.com/comment/89962839
score: -2
has comment: http://stackoverflow.com/comment/89962831
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/89962937
upvote count: 1
has comment: http://stackoverflow.com/comment/89962817
favorite count: 0
has answer: http://stackoverflow.com/a/51497594
has answer: http://stackoverflow.com/a/51497684
type: UnansweredQuestion
has body: I have a text file called "PERFORMANCE" which includes lists of tests and their running time. example: 274x_reinput_raw_data run 9 sec B-03507_add_pad_stack_with_rotation.csh run 8 sec B-04869_board_copper.csh run 1 sec I want to create a function name "get running time" that returns the running time of a given test. I have created this function: def get_running_time(test): running_time = 0 line = PERFORMANCE_FILE.readline() while line != "": line_split = line.split() if test in line_split: running_time = line_split[-2] else: line = PERFORMANCE_FILE.readline() return running_time but when i call: for test in failed_tests: file.write(str(get_running_time(test))+",") it writes None. Using prints in the middle i saw that the function takes one test name, searches for it but then does not move on to the next test. I dont know where my mistake is. I tried many different things to no avail. I would love to get some help. Thanks. EDIT- I have used prints to show an example: def get_running_time(test): print(test) running_time = 0 line = PERFORMANCE_FILE.readline() print(line) while line != "": line_split = line.split() print(line_split) if test in line_split: running_time = line_split[-2] print(running_time) else: line = PERFORMANCE_FILE.readline() print(line) return running_time and the output in the console is: DrillCleanup_unit_test.csh 274x_reinput_raw_data run 9 sec ['274x_reinput_raw_data', 'run', '9', 'sec'] B-03507_add_pad_stack_with_rotation.csh run 8 sec ['B-03507_add_pad_stack_with_rotation.csh', 'run', '8', 'sec'] B-04869_board_copper.csh run 1 sec ['B-04869_board_copper.csh', 'run', '1', 'sec'] B-04877_selftest_slot_histogram.csh run 0 sec ['B-04877_selftest_slot_histogram.csh', 'run', '0', 'sec'] B-06589_clipAreaRegressionTest run 8 sec Nomenclature_unit_test.csh PlaneClearance_unit_test.csh SurfaceAnalyzer_unit_test.csh 274x_reinput_raw_data B-03507_add_pad_stack_with_rotation.csh Process finished with exit code 0
tagged with: python
has comment: http://stackoverflow.com/comment/89962908
has comment: http://stackoverflow.com/comment/89962857
has comment: http://stackoverflow.com/comment/89963048
has comment: http://stackoverflow.com/comment/89963174
has title: weird function behavious python

http://stackoverflow.com/a/52148349
type: Answer
upvote count: 13
answers question: http://stackoverflow.com/q/51564841
score: 13
has body: Instead of writing a new decorator I came up with a function modifying all fields of type dataclass after the actual dataclass is initialized. def dicts_to_dataclasses(instance): """Convert all fields of type `dataclass` into an instance of the specified data class if the current value is of type dict.""" cls = type(instance) for f in dataclasses.fields(cls): if not dataclasses.is_dataclass(f.type): continue value = getattr(instance, f.name) if not isinstance(value, dict): continue new_value = f.type(**value) setattr(instance, f.name, new_value) The function could be called manually or in __post_init__. This way the @dataclass decorator can be used in all its glory. The example from above with a call to __post_init__: @dataclass class One: f_one: int f_two: str @dataclass class Two: def __post_init__(self): dicts_to_dataclasses(self) f_three: str f_four: One data = {'f_three': 'three', 'f_four': {'f_one': 1, 'f_two': 'two'}} two = Two(**data) # Two(f_three='three', f_four=One(f_one=1, f_two='two'))
downvote count: 0

http://stackoverflow.com/a/51504036
downvote count: 2
has body: $ pip install --user httplib2 The packages base64, sys and os are installed by default
answers question: http://stackoverflow.com/q/51503974
upvote count: 0
type: Answer
score: -2

http://stackoverflow.com/q/51610053
type: Question
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/90192025
has body: Numba offers compilation in two modes - nopython and object . Nopython mode is the faster one with certain limitations and it does not accesses python C API while the object mode does. What exactly is the difference between both the modes and why is nopython mode faster ? Thanks in advance.
type: UnansweredQuestion
has title: difference between object mode and nopython mode
tagged with: numba
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90198630
has comment: http://stackoverflow.com/comment/90191424

http://stackoverflow.com/comment/90107877
has text: updated as per your request
comment on: http://stackoverflow.com/q/51570812
score: 0
type: Comment
type: QuestionComment

excel
tags question: http://stackoverflow.com/q/51510669
tags question: http://stackoverflow.com/q/51601446
tags question: http://stackoverflow.com/q/51631138
tags question: http://stackoverflow.com/q/51541985
tags question: http://stackoverflow.com/q/51549853
tags question: http://stackoverflow.com/q/51567092
tags question: http://stackoverflow.com/q/51545746
tags question: http://stackoverflow.com/q/51544241
tag name: excel
tags question: http://stackoverflow.com/q/51582786
tags question: http://stackoverflow.com/q/51491241
tags question: http://stackoverflow.com/q/51546036
tags question: http://stackoverflow.com/q/51547935
tags question: http://stackoverflow.com/q/51530515
tags question: http://stackoverflow.com/q/51598421
tags question: http://stackoverflow.com/q/51531715
tags question: http://stackoverflow.com/q/51539797
tags question: http://stackoverflow.com/q/51494185
tags question: http://stackoverflow.com/q/51620641
tags question: http://stackoverflow.com/q/51614726
tags question: http://stackoverflow.com/q/51591943
tags question: http://stackoverflow.com/q/51579423
tags question: http://stackoverflow.com/q/51620138
tags question: http://stackoverflow.com/q/51600421
tags question: http://stackoverflow.com/q/51602796
tags question: http://stackoverflow.com/q/51530814
tags question: http://stackoverflow.com/q/51503471
tags question: http://stackoverflow.com/q/51567516
tags question: http://stackoverflow.com/q/51632848
tags question: http://stackoverflow.com/q/51491782
tags question: http://stackoverflow.com/q/51500501
tags question: http://stackoverflow.com/q/51504534
tags question: http://stackoverflow.com/q/51537016
tags question: http://stackoverflow.com/q/51601031
tags question: http://stackoverflow.com/q/51602694
tags question: http://stackoverflow.com/q/51484142
tags question: http://stackoverflow.com/q/51557701
tags question: http://stackoverflow.com/q/51552636
tags question: http://stackoverflow.com/q/51556281
tags question: http://stackoverflow.com/q/51623539
tags question: http://stackoverflow.com/q/51537583
type: Tag
tags question: http://stackoverflow.com/q/51603722
tags question: http://stackoverflow.com/q/51504789
tags question: http://stackoverflow.com/q/51525385
tags question: http://stackoverflow.com/q/51554503
tags question: http://stackoverflow.com/q/51603288
tags question: http://stackoverflow.com/q/51571026
tags question: http://stackoverflow.com/q/51620536
tags question: http://stackoverflow.com/q/51626502
tags question: http://stackoverflow.com/q/51524911
tags question: http://stackoverflow.com/q/51581888
tags question: http://stackoverflow.com/q/51591634
tags question: http://stackoverflow.com/q/51542959
tags question: http://stackoverflow.com/q/51557646
tags question: http://stackoverflow.com/q/51509313
tags question: http://stackoverflow.com/q/51515902
tags question: http://stackoverflow.com/q/51626356

http://stackoverflow.com/comment/90108940
type: Comment
has text: yeah this ->Traceback (most recent call last): File "C:/Users/PycharmProjects/learnpython/get_sqltable.py", line 25, in <module> app.getoneresult('pokemon') File "C:/Users/PycharmProjects/learnpython/get_sqltable.py", line 18, in getoneresult self.row1 = row[0] TypeError: 'int' object is not subscriptable
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51571275

http://stackoverflow.com/comment/90200995
score: 0
type: Comment
type: QuestionComment
has text: Personally, I think simple cases are better handled with native comprehensions than with dpath wildcards, and complicated cases usually need some kind of custom logic (at least error handling) within the search, so the window at which these libraries are useful is pretty small. But some people seem to find it much easier to think in terms of nested wildcards than me, or much harder to think in terms of loops, or whatever.
comment on: http://stackoverflow.com/q/51616686

http://stackoverflow.com/comment/90208537
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51621428
has text: Shouldn't the first example end at `[0]`? `[3, 2, 1]` -> `[1, 1]` -> `[0]`
score: 0

http://stackoverflow.com/comment/89951088
comment on: http://stackoverflow.com/q/51491246
score: 0
has text: What happens when you supply any of the recognized (true, false, null) tokens as a param? I also don't think you need to dump the `datam` dict. You should be able to pass it along the way it is.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89960447
type: QuestionComment
has text: This is heavily dependent on the use case. Generally I'd say that if the api is public let the client make the calls. It is faster (saves the round-trip between your server and the client) and saves load on your server. If it is a restricted api that requires authentication, e.g. through an API token, this needs to be done by the server. Of course you do not want to leak your private token to all your clients.
type: Comment
comment on: http://stackoverflow.com/q/51495315
score: 3

http://stackoverflow.com/comment/89988640
type: Comment
type: QuestionComment
has text: @IljaEverilä would there then be a check you could perform at the start of each request to see if the session is fresh?
score: 0
comment on: http://stackoverflow.com/q/51505589

http://stackoverflow.com/comment/90215588
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51588959
type: AnswerComment
has text: You need to pass a queryset to the serializer and set `many=True` ie. `SentenceListSerializer(data=queryset, many=True)`

http://stackoverflow.com/a/51606934
type: AcceptedAnswer
downvote count: 0
has body: To create a dynamic form with wtforms use the following template def DynamicForm(*args, **kwargs): class StaticForm(FlaskForm): pass if args[0] == True: StaticForm.class_attrib1 = StringField(...) else: StaticForm.class_attrib2 = StringField(...) return StaticForm() This establishes a StaticForm within the local scope of the function, attaches all of the relevant items based on programming logic from the function arguments and returns an instantiated form: form = DynamicForm(True) # form has attribute: class_attrib1 This is explained in the docs somewhere, but I cant find the link right now
score: 4
type: Answer
answers question: http://stackoverflow.com/q/51599936
accepted answer of: http://stackoverflow.com/q/51599936
upvote count: 4

http://stackoverflow.com/q/51513130
has answer: http://stackoverflow.com/a/51513438
score: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51513233
type: UnansweredQuestion
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51513343
has answer: http://stackoverflow.com/a/51513461
has body: This is part of the code I am making, I am trying to make the user input a number to choose which level they want to do from 1-100 but when they put a number it tells them which overall level that they are in. I have used this code but I can't seem to make it work. The conditions are that it can't break if a number below, above or text is entered, it should just re-ask the question. #Ask for level Level = "" #make code for it def number(): while True: try: Level = int(input("What is the level in the game? ")) except ValueError: print("Please enter a valid number") else: break return Level while True: if number &lt;=25: print ("Beginner" ) if number &gt;=26 and number &lt;=75: print ("Intermediate") if number &gt;=76 and number &lt;=100: print ("expert") break
has title: How to input a number between two numbers that allow for text to be written after
type: Question

http://stackoverflow.com/comment/90006966
score: 1
type: QuestionComment
has text: The only way I'm able to recreate your issue is if I set the `time = np.arange(0, 10.1, step, dtype=np.float16)`
comment on: http://stackoverflow.com/q/51518153
type: Comment

http://stackoverflow.com/comment/90329368
comment on: http://stackoverflow.com/a/51584791
has text: few month ago, this code works well (i used python 2.7.9 i think....and i download data from yahoo, until the API blocked. now, i am using python 2.7.15, with alphavantage API). i think something wrong with adj(A) and i don't understand where, i tried to change locations...nothing.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90236802
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51633456
has text: Thanks! Yes I agree that there are other ways to set env vars. I was just trying to provide a real world example of a use for the preload.

http://stackoverflow.com/q/51591550
has answer: http://stackoverflow.com/a/64826830
has answer: http://stackoverflow.com/a/51850113
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/75516202
score: 24
tagged with: recurrent-neural-network
upvote count: 24
tagged with: tensorflow
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/67707956
has answer: http://stackoverflow.com/a/71575176
has answer: http://stackoverflow.com/a/63152887
tagged with: deep-learning
has title: logits and labels must be broadcastable error in Tensorflow RNN
downvote count: 0
has answer: http://stackoverflow.com/a/67846499
favorite count: 0
has body: I am new to Tensorflow and deep leaning. I am trying to see how the loss decreases over 10 epochs in my RNN model that I created to read a dataset from kaggle which contains credit card fraud data. I am trying to classify the transactions as fraud(1) and not fraud(0). When I try to run the below code I keep getting the below error: > 2018-07-30 14:59:33.237749: W > tensorflow/core/kernels/queue_base.cc:277] > _1_shuffle_batch/random_shuffle_queue: Skipping cancelled enqueue attempt with queue not closed Traceback (most recent call last): > File > "/home/suleka/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", > line 1322, in _do_call > return fn(*args) File "/home/suleka/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", > line 1307, in _run_fn > options, feed_dict, fetch_list, target_list, run_metadata) File "/home/suleka/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", > line 1409, in _call_tf_sessionrun > run_metadata) tensorflow.python.framework.errors_impl.InvalidArgumentError: logits > and labels must be broadcastable: logits_size=[1,2] labels_size=[1,24] > [[Node: softmax_cross_entropy_with_logits_sg = > SoftmaxCrossEntropyWithLogits[T=DT_FLOAT, > _device="/job:localhost/replica:0/task:0/device:CPU:0"](add, softmax_cross_entropy_with_logits_sg/Reshape_1)]] > > During handling of the above exception, another exception occurred: > > Traceback (most recent call last): File > "/home/suleka/Documents/untitled1/RNN_CrediCard.py", line 96, in > <module> > train_neural_network(x) File "/home/suleka/Documents/untitled1/RNN_CrediCard.py", line 79, in > train_neural_network > _, c = sess.run([optimizer, cost], feed_dict={x: feature_batch, y: label_batch}) File > "/home/suleka/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", > line 900, in run > run_metadata_ptr) File "/home/suleka/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", > line 1135…
has answer: http://stackoverflow.com/a/66618469
linked to: http://stackoverflow.com/q/46465925

http://stackoverflow.com/a/51639734
type: Answer
score: 1
has body: Yes, very large values of F-statistic indicate high significance, as witnessed by p being reported as 0. Mathematically, F comes up as infinity if there is no in-group variability, e.g., &gt;&gt;&gt; stats.f_oneway([2, 2, 2], [1, 1, 1]) F_onewayResult(statistic=inf, pvalue=0.0) This result is also possible if there is very little in-group variability compared to between-group variability, resulting in numerical overflow. &gt;&gt;&gt; stats.f_oneway([2, 2, 2], [1, 1, 1.00000001]) F_onewayResult(statistic=inf, pvalue=0.0)
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51637757
answers question: http://stackoverflow.com/q/51637757

http://stackoverflow.com/q/51633787
has comment: http://stackoverflow.com/comment/90304294
has title: Fetch permanent address of your email message
has comment: http://stackoverflow.com/comment/90231802
type: Question
linked to: http://stackoverflow.com/q/1687445
tagged with: imap
score: 0
has body: I want to open particular mail(gmail) directly. gmail provide permanent address to each mail. for example https://mail.google.com/mail/u/0/#inbox/164f55ec5fdbb840 here 164f55ec5fdbb840 is unique id. The link will redirecting to specific mail. Is it possible to fetch this unique link using python. I have used IMAP, poplib modules of python and debug the same, but hard luck
type: UnansweredQuestion
tagged with: python
tagged with: gmail
tagged with: poplib
answer count: 0

http://stackoverflow.com/a/51561788
answers question: http://stackoverflow.com/q/51561242
score: 0
has comment: http://stackoverflow.com/comment/90092207
has body: Your approach seems to be too complicated. Just convert the list of chars to list of nums using map and ord, then enumerate the resulting list to find the first missing number, convert it back to char using chr &gt;&gt;&gt; l = ['a', 'b', 'c', 'd', 'f'] chr(next(i for i,j in enumerate(map(ord, l), ord(l[0])) if i!=j)) 'e'
type: Answer

http://stackoverflow.com/a/51588676
answers question: http://stackoverflow.com/q/51588479
type: Answer
upvote count: 1
has body: ScipyOpimizerInterface is a wrapper allowing scipy.optimize.minimize to operate in a tensorflow Session. It accepts a method kwarg to which you can pass any of the methods outlined in the docs. optimizer = ScipyOptimizerInterface(loss, ..., method='L-BGFS-B') You should understand that the applicability of a method depends on the constraints used. Consult the docs for more information.
downvote count: 0
score: 1

http://stackoverflow.com/comment/90193070
comment on: http://stackoverflow.com/q/51613315
type: Comment
type: QuestionComment
has text: ga:productName and ga:date is taken from dimensions - '"dimensions": ["ga:productName", "ga:date"],' , the rest of heading is from 'metricHeaderEntries'.
score: 0

http://stackoverflow.com/a/51553608
has body: To access the post-id in your view, you must ensure that it is provided as a parameter in your POST request. You can do this through AJAX or a HTML form. Via Ajax: $.ajax({ url: '/yourformviewurl', data: { 'post-id': $("#yourh1id").attr('data-post-id') }, method: 'POST', dataType: 'json', success: function (data) { console.log('it worked!', data) } }); Via HTML Form: Post id: Please see the Django form docs: https://docs.djangoproject.com/en/2.0/topics/forms/
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51552622
downvote count: 0
answers question: http://stackoverflow.com/q/51552622
type: Answer

http://stackoverflow.com/comment/90017891
comment on: http://stackoverflow.com/a/51523242
has text: When I do this, I still get the original row count. No change
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89967412
has text: Try to check out this doc https://docs.djangoproject.com/en/2.0/ref/forms/fields/#fields-which-handle-relationships in your case you need ```ModelChoiceField``` to handle one object.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51498881

http://stackoverflow.com/q/51625388
has comment: http://stackoverflow.com/comment/90215583
tagged with: terminal
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/31635140
has answer: http://stackoverflow.com/a/51625989
tagged with: python-3.x
tagged with: pycharm
has title: PYTHON: How do you run your programs from the terminal?
upvote count: 2
score: 0
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/51625535
accepted answer: http://stackoverflow.com/a/51625989
possible better answer: http://stackoverflow.com/a/51625420
has comment: http://stackoverflow.com/comment/90215563
has answer: http://stackoverflow.com/a/51625420
type: AnsweredQuestion
has body: I wrote this program that controls your computer to collect data from a website in the PyCharm IDE with python 3.7. In my program I imported different libraries like pyautogui. import pyautogui, time, re, os def process(): # The rest of the code Auto is the project name I have all the files in. I want to run the program from my terminal without having to run it from PyCharm but I'm getting these errors in it: laptop:auto user$ python ./test.py Traceback (most recent call last): File "./test.py", line 1, in &lt;module&gt; import pyautogui, time, re, os ImportError: No module named pyautogui I downloaded Pyautogui onto my laptop using pip but I don't know how to make it so that the terminal can use the library. Any suggestions on what I should do to solve this problem?
has comment: http://stackoverflow.com/comment/90215599
has comment: http://stackoverflow.com/comment/90215597
favorite count: 0

http://stackoverflow.com/a/51620127
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/51618170
type: AcceptedAnswer
has body: I was able to reproduce your "segmentation fault" issue under Xubuntu 16.04 using FreeTDS 1.00.94 and unixODBC 2.3.6. fast_executemany = True uses an ODBC feature called "parameter arrays" and that feature is not supported by all ODBC drivers. Apparenty FreeTDS ODBC is one of those drivers that does not support it. If you really need to use fast_executemany = True you can use Microsoft's ODBC Driver for SQL Server. It does support ODBC parameter arrays.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51618170
type: Answer

http://stackoverflow.com/q/51522685
answer count: 2
has body: I have list of tuples like bottles = [(1234, 'ICED', 'MOC12', 3), (1234, 'ICED', 'MOC12', 2), (3456, 'HOT', 'CAR23', 1), (3456, 'HOT', 'YUP23', 2)] I want the tuple corresponding to the max of the last field for each groups. The groups are defined by the first three values. Output: result = [(1234, 'ICED', 'MOC12', 3),(3456, 'HOT', 'CAR23', 1),(3456, 'HOT','YUP23', 2)]
has title: How to group a list of tuples based on similar fields and then keep the maximum based on another field? (without using Pandas)
favorite count: 0
tagged with: tuples
tagged with: python
type: AnsweredQuestion
upvote count: 0
tagged with: list
has comment: http://stackoverflow.com/comment/90015404
downvote count: 1
possible better answer: http://stackoverflow.com/a/51523073
has answer: http://stackoverflow.com/a/51523328
type: Question
accepted answer: http://stackoverflow.com/a/51523328
has comment: http://stackoverflow.com/comment/90014794
has comment: http://stackoverflow.com/comment/90015121
tagged with: sorting
score: -1
has answer: http://stackoverflow.com/a/51523073
has comment: http://stackoverflow.com/comment/90014864

http://stackoverflow.com/comment/90092153
score: 4
type: Comment
type: QuestionComment
has text: Then your question is too broad for SO
comment on: http://stackoverflow.com/q/51562600

http://stackoverflow.com/comment/89984832
comment on: http://stackoverflow.com/q/51494124
type: QuestionComment
has text: I remember there being a similar (not the same) error in a previous version of matplotlib when saving many (>1000) frames via ffmpeg. Are you using matplotlib 2.2.2?
type: Comment
score: 2

http://stackoverflow.com/q/51587306
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/51589096
accepted answer: http://stackoverflow.com/a/51589096
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has body: I'm currently trying to find an easy way to do the following operation to an N dimensional array in Python. For simplicity let's start with a 1 dimensional array of size 4. X = np.array([1,2,3,4]) What I want to do is create a new array, call it Y, such that: Y = np.array([1,2,3,4],[2,3,4,1],[3,4,1,2],[4,1,2,3]) So what I'm trying to do is create an array Y such that: Y[:,i] = np.roll(X[:],-i, axis = 0) I know how to do this using for loops, but I'm looking for a faster method of doing so. The actual array I'm trying to do this to is a 3 dimensional array, call it X. What I'm looking for is a way to find an array Y, such that: Y[:,:,:,i,j,k] = np.roll(X[:,:,:],(-i,-j,-k),axis = (0,1,2)) I can do this using the itertools.product class using for loops, but this is quite slow. If anyone has a better way of doing this, please let me know. I also have CUPY installed with a GTX-970, so if there's a way of using CUDA to do this faster please let me know. If anyone wants some more context please let me know. Here is my original code for computing the position space two point correlation function. The array x0 is an n by n by n real valued array representing a real scalar field. The function iterate(j,s) runs j iterations. Each iteration consists of generating a random float between -s and s for each lattice site. It then computes the change in the action dS and accepts the change with a probability of min(1,exp^(-dS)) def momentum(k,j,s): global Gxa Gx = numpy.zeros((n,n,t)) for i1 in range(0,k): iterate(j,s) for i2,i3,i4 in itertools.product(range(0,n),range(0,n),range(0,n)): x1 = numpy.roll(numpy.roll(numpy.roll(x0, -i2, axis = 0),-i3, axis = 1),-i4,axis = 2) x2 = numpy.mean(numpy.multiply(x0,x1)) Gx[i2,i3,i4] = x2 Gxa = Gxa + Gx Gxa = Gxa/k
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/43735034
type: Question
tagged with: numpy
has title: Rolling/Increasing dimensionality of a NumPy array
tagged with: numpy-ndarray
tagged with: arrays

http://stackoverflow.com/a/51511328
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51511295
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51511295
has body: You're not calling your functions inside the slice. To call the functions you need to put () after the function names. i = line[firstposition():secondposition()] Just using the function name is passing the function by name, sometimes called a "function pointer". It lets you pass functions into other functions so they can be called within. However, passing a function does not call that function. Meanwhile, when you call a function with (), you're essentially replacing that spot where you called the function with the value that was returned from said function.
type: Answer

http://stackoverflow.com/comment/90170684
type: Comment
score: 1
type: AnswerComment
has text: Thank you so much. Also, can I add this function again to make more levels (like 10 more?)
comment on: http://stackoverflow.com/a/51602318

http://stackoverflow.com/q/51549997
tagged with: python
has title: Python difference between statement and function
has answer: http://stackoverflow.com/a/51550019
tagged with: performance
has comment: http://stackoverflow.com/comment/90067505
score: 1
upvote count: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90068025
downvote count: 0
has answer: http://stackoverflow.com/a/51550526
has body: I am currently using python to work with tons of data, and I got a bit curious... Since it's a lot of data, code speed really matters, so is there a difference between a few statements and a function that do so? is there a difference between def my_function(var1): var2 = var1 + 1 var3 = var1 - 1 var4 = str(var1) print(var2, var3, var4) for i in range(100000): my_function(i) and for i in range(100000): var1 = i var2 = var1 + 1 var3 = var1 - 1 var4 = str(var1) print(var2, var3, var4) when talking about how fast the code is?
has comment: http://stackoverflow.com/comment/90067451
favorite count: 0
has comment: http://stackoverflow.com/comment/90067455
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90067582

http://stackoverflow.com/q/51578119
linked to: http://stackoverflow.com/q/50563546
has comment: http://stackoverflow.com/comment/90121647
has answer: http://stackoverflow.com/a/51578293
has comment: http://stackoverflow.com/comment/90121731
tagged with: typing
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/90121723
type: AnsweredQuestion
has title: Check if type is a list
accepted answer: http://stackoverflow.com/a/51578293
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90121653
answer count: 1
score: 0
has body: I have some types (coming from inspect.signature -> inspect.Parameter) and I'd like to check if they are lists or not. My current solution works but is very ugly, see minimal example below: from typing import Dict, List, Type, TypeVar IntList = List[int] StrList = List[str] IntStrDict = Dict[int, str] TypeT = TypeVar('TypeT') # todo: Solve without using string representation of type def is_list_type(the_type: Type[TypeT]) -&gt; bool: return str(the_type)[:11] == 'typing.List' assert not is_list_type(IntStrDict) assert not is_list_type(int) assert not is_list_type(str) assert is_list_type(IntList) assert is_list_type(StrList) What would be the correct way to check if a type is a List? (I'm using Python 3.6 and the code should survive a check with mypy --strict.)
has comment: http://stackoverflow.com/comment/90121616

http://stackoverflow.com/comment/90027636
has text: This does not work, because the query does not return `[None, None]` it returns `[]`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51529697
type: Comment

http://stackoverflow.com/comment/89975542
score: 0
comment on: http://stackoverflow.com/q/51503407
has text: @AdamSmith I need trailing backslash to detect before removing it... `line.strip()`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90105454
type: QuestionComment
comment on: http://stackoverflow.com/q/51569414
has text: @joaquin i have added the actual url for trial. Try using dictionary functions on the "result" variable ( this stores the response from API )
score: 0
type: Comment

http://stackoverflow.com/q/51505410
answer count: 1
downvote count: 0
score: 4
favorite count: 0
tagged with: python
tagged with: bottle
has answer: http://stackoverflow.com/a/51505615
tagged with: request
has body: I am trying to create a query form that allows me to query my mongo database and show the results up on a web page. I am using python with the bottle framework for this. Here a sample of my code import bottle import pymongo @bottle.route('/') def home_page(): #connect to mongodb connection = pymongo.MongoClient('localhost', 27017) #connect to mydb database db = connection.TestCollection #connect to collection data = db.TestData #finding all data mydata = data.find() result = [] for i in mydata: result.append([i['User'],i['Email'],i['Title']]) output = bottle.template('results.tpl', rows=result) return output This prints out all the data in my mongo database to a web page using a bottle template, results.tpl Results enter query: User Email Title %for row in rows: %for col in row: {{col}} %end %end My problem is I don't want all the data showing only the data that is searched for. I want to be able to use the form to make a request that will get the data from mongo based on the keyword that was submitted. If this type of query web app can be done with other frameworks please let me know. If you have any good links to help me get an understanding of using request I'd love that too. Thank you.
type: Question
type: AnsweredQuestion
has title: How to Query mongo database using python bottle framework
accepted answer: http://stackoverflow.com/a/51505615
upvote count: 4
tagged with: mongodb

http://stackoverflow.com/q/51514481
has comment: http://stackoverflow.com/comment/89997716
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51515628
accepted answer: http://stackoverflow.com/a/51515628
tagged with: file
has comment: http://stackoverflow.com/comment/89997634
type: Question
upvote count: 6
possible better answer: http://stackoverflow.com/a/65926490
has comment: http://stackoverflow.com/comment/89997483
has comment: http://stackoverflow.com/comment/89997336
answer count: 2
downvote count: 3
has title: TypeError: expected str, bytes or os.PathLike object, not ImageFieldFile
has comment: http://stackoverflow.com/comment/89998034
favorite count: 0
has body: I am trying to upload a file to an another server. I am trying to do it like that: package = Package.objects.get(id=package_id) with open(package.logo_image.image, 'rb') as image_handle: image_data = bytes(image_handle.read()) image = { 'type': 'IMAGE', 'data': image_data, 'xsi_type': 'Image' } logo_image = media_service.upload(image)[0] Field in a model: image = models.ImageField(upload_to=generate_file_path, null=True, blank=True) After trying to run this code I get: with open(package.logo_image.image, 'rb') as image_handle: TypeError: expected str, bytes or os.PathLike object, not ImageFieldFile Converting to str() does not help. Is is possoble to open this file i binary mode? Thank you!
tagged with: binary
has answer: http://stackoverflow.com/a/65926490
tagged with: django
tagged with: python

http://stackoverflow.com/a/51574014
score: 1
type: Answer
answers question: http://stackoverflow.com/q/51573969
upvote count: 1
has body: Using pd.concat Ex: import pandas as pd df1 = pd.DataFrame({"name": ['a', 'a'], "date":['2018-07-28', '2018-07-29'], "value": [0, 1]}) df2 = pd.DataFrame({"name": ['b', 'b'], "date":['2018-07-28', '2018-07-29'], "value": [2, 3]}) print(pd.concat([df1, df2]).sort_values(by=['date'])) Output: date name value 0 2018-07-28 a 0 0 2018-07-28 b 2 1 2018-07-29 a 1 1 2018-07-29 b 3
downvote count: 0

http://stackoverflow.com/comment/90067916
score: 2
comment on: http://stackoverflow.com/q/51550211
has text: @JoranBeasley: `nonlocal` lets you assign to closure variables in Python 3.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90211246
comment on: http://stackoverflow.com/a/51622816
type: Comment
has text: Great, appreciated!
score: 0
type: AnswerComment

http://stackoverflow.com/q/51589017
answer count: 1
tagged with: flask
has title: Everytime restart required for flask to work
score: 0
has comment: http://stackoverflow.com/comment/90149581
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/90149657
linked to: http://stackoverflow.com/q/30328586
has comment: http://stackoverflow.com/comment/90149818
has body: I have a flask app which will read some dataframes and displays some output in front end. I have two routes. One will accept user input and is send to second route. Second route make use of this input and process some dataframe and provides some output. Issue is, if go to user input page again and if I try submitting another input, it gives me page not working error. Is it because of any memory issue? If I restart my sever, then I repeat it once(every time I need to restart). from flask import flash, redirect, render_template, url_for, request, jsonify import math import os import glob import pandas as pd from . import fa from database import connection UPLOAD_DIRECTORY = './uploads' if not os.path.exists(UPLOAD_DIRECTORY): os.makedirs(UPLOAD_DIRECTORY) @fa.route('/fc', methods=['GET', 'POST']) def index(): return render_template('fc.html',flag=0) @fa.route('/fc/s', methods=['GET', 'POST']) def start(): if request.method == 'POST': material_number = request.form['ma'] path = UPLOAD_DIRECTORY extension = 'xlsx' os.chdir(path) result = [i for i in glob.glob('*.{}'.format(extension))] allFiles = result frame = pd.DataFrame() list_ = [] for file_ in allFiles: df = pd.read_excel(file_) list_.append(df) frame = pd.concat(list_) frame = frame.reset_index(drop=True) df1 = frame[frame['Ma'].str.contains(ma,regex=True)] pr = df1['Pr'].unique().tolist() pro = pd.read_excel(r'~pathhiddn~\dtrvsproj.xlsx') return render_template('fc.html',flag=1,ma=ma,prs=pr) return redirect(url_for('fa.index'))
has answer: http://stackoverflow.com/a/51606847
duplicate of: http://stackoverflow.com/q/30328586
has comment: http://stackoverflow.com/comment/90150561
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51606847
tagged with: dataframe
tagged with: flask-restful
type: Question
has comment: http://stackoverflow.com/comment/90151895

http://stackoverflow.com/comment/90195330
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51609917
has text: I would suggest to post a minimal code that shows your problem. Your current example code is way too long.

http://stackoverflow.com/a/51573025
has body: Sounds like you're looking for something along the lines of [sum(t) for t in itertools.product(l1, l2, l3)] which results in [16, 20, 26, 19, 24, 28, 34, 27, 22, 26, 32, 25, 13, 17, 23, 16, 21, 25, 31, 24, 19, 23, 29, 22, 12, 16, 22, 15, 20, 24, 30, 23, 18, 22, 28, 21] Here itertools.product generates the Cartesian product of the input iterables. If you had some unknown number of iterables in a list you could do iterables = [l1, l2, l3, ...] [sum(t) for t in itertools.product(*iterables)] to unpack them into arguments A recursive solution would looks something like this. Warning: it is going to be worse in every way compared to the itertools solution. def summations(*iterables, sums=()): if not iterables: return list(sums) head, *tail = iterables if not sums: return summations(*tail, sums=head) sums = (x+y for y in sums for x in head) return summations(*tail, sums=sums) summations(l1, l2, 3) # [16, 20, 26, 19, 24, 28, 34, 27, 22, 26, 32, 25, 13, 17, 23, 16, 21, 25, 31, 24, 19, 23, 29, # 22, 12, 16, 22, 15, 20, 24, 30, 23, 18, 22, 28, 21]
upvote count: 2
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51572986
has comment: http://stackoverflow.com/comment/90111937
has comment: http://stackoverflow.com/comment/90112194

http://stackoverflow.com/comment/90145838
comment on: http://stackoverflow.com/a/51587231
has text: You cannot not pass str as threshold. It must be int e.g `np.set_printoptions(threshold=5000)`
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89941911
has text: But my final `bb` is not a "list of lists", but a single flat list. I'm not sure I understand this answer, sorry.
type: Comment
comment on: http://stackoverflow.com/a/51486433
score: 1
type: AnswerComment

http://stackoverflow.com/q/51635417
possible better answer: http://stackoverflow.com/a/51647782
accepted answer: http://stackoverflow.com/a/51668682
has answer: http://stackoverflow.com/a/51647782
type: Question
downvote count: 0
has body: I am reading a tab separated text file into pandas dataframe.I am getting a runtime error while reading this.I have gone through the posts related to this error and all of them are alluding to the rule that one should not modify dicts while iterating over them.In my case all I am doing is reading a file.How is this problem connected to an error of iterating and changing dicts ? &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df=pd.read_csv("dummy_data.txt",header=None,chunksize=10000,error_bad_lines=False,warn_bad_lines=True,engine='c',sep="\t",encoding="latin-1") Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; df=pd.read_csv("dummy_data.txt",header=None,chunksize=10000,error_bad_lines=False,warn_bad_lines=True,engine='c',sep="\t",encoding="latin-1") File "/home/avadhut/.virtualenvs/avadhut_virtual/lib/python3.5/site-packages/pandas/io/parsers.py", line 709, in parser_f return _read(filepath_or_buffer, kwds) File "/home/avadhut/.virtualenvs/avadhut_virtual/lib/python3.5/site-packages/pandas/io/parsers.py", line 431, in _read compression = _infer_compression(filepath_or_buffer, compression) File "/home/avadhut/.virtualenvs/avadhut_virtual/lib/python3.5/site-packages/pandas/io/common.py", line 270, in _infer_compression filepath_or_buffer = _stringify_path(filepath_or_buffer) File "/home/avadhut/.virtualenvs/avadhut_virtual/lib/python3.5/site-packages/pandas/io/common.py", line 157, in _stringify_path from py.path import local as LocalPath File "/home/avadhut/.virtualenvs/avadhut_virtual/lib/python3.5/site-packages/py/__init__.py", line 148, in &lt;module&gt; 'Syslog' : '._log.log:Syslog', File "/home/avadhut/.virtualenvs/avadhut_virtual/lib/python3.5/site-packages/py/_vendored_packages/apipkg.py", line 63, in initpkg for module in sys.modules.values(): RuntimeError: dictionary changed size during iteration Edit 1: While reading the file via the interactive mode I encounter the same error twice while trying to read the file.On the 3rd …
has answer: http://stackoverflow.com/a/56774120
tagged with: runtime-error
answer count: 3
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90299936
favorite count: 0
has answer: http://stackoverflow.com/a/51668682
has comment: http://stackoverflow.com/comment/90299768
upvote count: 2
has comment: http://stackoverflow.com/comment/90299902
tagged with: python
linked to: http://stackoverflow.com/q/20062470
has title: RunTimeError while reading tab separated text file into Pandas dataframe
score: 2
type: AnsweredQuestion

beautifulsoup
tags question: http://stackoverflow.com/q/51557902
tags question: http://stackoverflow.com/q/51516306
tags question: http://stackoverflow.com/q/51582031
tags question: http://stackoverflow.com/q/51611915
tags question: http://stackoverflow.com/q/51609620
tags question: http://stackoverflow.com/q/51483171
tags question: http://stackoverflow.com/q/51608626
tags question: http://stackoverflow.com/q/51605307
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/51533619
tags question: http://stackoverflow.com/q/51625776
tags question: http://stackoverflow.com/q/51621095
tags question: http://stackoverflow.com/q/51573673
tags question: http://stackoverflow.com/q/51626088
tags question: http://stackoverflow.com/q/51586003
tags question: http://stackoverflow.com/q/51567402
tags question: http://stackoverflow.com/q/51624237
tags question: http://stackoverflow.com/q/51568732
tags question: http://stackoverflow.com/q/51493468
tags question: http://stackoverflow.com/q/51580030
tags question: http://stackoverflow.com/q/51623320
tags question: http://stackoverflow.com/q/51490114
tags question: http://stackoverflow.com/q/51496381
tags question: http://stackoverflow.com/q/51571609
tags question: http://stackoverflow.com/q/51527566
tags question: http://stackoverflow.com/q/51544103
type: Tag
tags question: http://stackoverflow.com/q/51592631
tags question: http://stackoverflow.com/q/51577228
tags question: http://stackoverflow.com/q/51534651
tags question: http://stackoverflow.com/q/51576163
tags question: http://stackoverflow.com/q/51580190
tags question: http://stackoverflow.com/q/51525331
tags question: http://stackoverflow.com/q/51538718
tags question: http://stackoverflow.com/q/51604174
tags question: http://stackoverflow.com/q/51533363
tags question: http://stackoverflow.com/q/51555209
tags question: http://stackoverflow.com/q/51553467
tags question: http://stackoverflow.com/q/51623984
tags question: http://stackoverflow.com/q/51546730
tags question: http://stackoverflow.com/q/51494140
tags question: http://stackoverflow.com/q/51638468
tags question: http://stackoverflow.com/q/51580869
tags question: http://stackoverflow.com/q/51621802
tags question: http://stackoverflow.com/q/51563910
tags question: http://stackoverflow.com/q/51557819
tags question: http://stackoverflow.com/q/51529482
tags question: http://stackoverflow.com/q/51575310
tags question: http://stackoverflow.com/q/51584343
tags question: http://stackoverflow.com/q/51590045

http://stackoverflow.com/a/51553546
downvote count: 0
has body: You can always Python using gdb and set breakpoints as you like gdb -ex r --args python script.py args If you want to look what happens in Python while running Python script I suggest to use mixed mode gdb -ex r --args python -m pdb script.py This way, you can break in pdb, then press Ctrl-C and end up inside gdb. Then, bt will give you stack trace inside Python.
type: Answer
has comment: http://stackoverflow.com/comment/90079868
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51537967
has comment: http://stackoverflow.com/comment/90081548

http://stackoverflow.com/a/51548933
has comment: http://stackoverflow.com/comment/90065461
upvote count: 2
answers question: http://stackoverflow.com/q/51548874
has comment: http://stackoverflow.com/comment/90065464
score: 2
has comment: http://stackoverflow.com/comment/90086464
downvote count: 0
type: Answer
has body: In your __init__() method for Ball (line #9), you reference self.x (and self.y), but you haven't set those variables.

http://stackoverflow.com/q/51569308
has comment: http://stackoverflow.com/comment/90104752
answer count: 2
has comment: http://stackoverflow.com/comment/90104954
score: 2
has answer: http://stackoverflow.com/a/51569895
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90105093
has body: I am new to python and implementing stack. I am calling stack functions using dictionary. However, push() requires me to pass a parameter. How do I do that? class stack(): def __init__(self): self.items = [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def isEmpty(self): return self.items == [] def getStack(self): return print(self.items) s = stack() switcher = { '1' : s.push, '2' : s.pop, '3' : s.isEmpty, '4' : s.getStack, } def dictionaryCall(key): switcher[key]() while(1): key = input('enter choice 1.push 2. pop 3.isEmpty 4 getStack 5.exit: ') if key == '5': break dictionaryCall(key)
tagged with: python
type: AnsweredQuestion
has title: passing parameters to functions called by dictionary in python
accepted answer: http://stackoverflow.com/a/51569895
has comment: http://stackoverflow.com/comment/90105054
upvote count: 2
has comment: http://stackoverflow.com/comment/90105309
has comment: http://stackoverflow.com/comment/90104787
has comment: http://stackoverflow.com/comment/90105002
type: Question
has comment: http://stackoverflow.com/comment/90104984
possible better answer: http://stackoverflow.com/a/51569543
has answer: http://stackoverflow.com/a/51569543

http://stackoverflow.com/q/51486751
has title: How to convert hhmmss.ff format into datetime with pandas
has comment: http://stackoverflow.com/comment/89942610
type: Question
has body: How can I convert the following time format: hhmmss.ff (like 110241.22 is 11:02:41.22) into the date/time format with pandas? I tries to use pandas.to_datetime() but it fails to do the conversion. Here is an example: hhmmss='110241.22' pd.to_datetime(hhmmss) Thanks
tagged with: pandas
upvote count: 1
tagged with: datetime
answer count: 1
has answer: http://stackoverflow.com/a/51486790
favorite count: 0
accepted answer: http://stackoverflow.com/a/51486790
tagged with: python
has comment: http://stackoverflow.com/comment/89942944
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/89973935
score: 1
has text: I'm not aware of any such controls or customization. GIven the possible diversity it would take a lot of work to develop a general purpose formatter. But if there's anything, I'd expect to find it in `np.core.records` which implements the `recarray` subclass.
comment on: http://stackoverflow.com/q/51500194
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90166663
type: Comment
has text: How committed are you to doing this with HTML? Embedding Python in a web page isn't very simple. If you're only doing it because you want color output, you might have better luck with a desktop GUI, or even a command-line program, assuming your shell can handle colored text. [colorama](https://pypi.org/project/colorama/) is useful in the latter case.
score: 0
comment on: http://stackoverflow.com/q/51600182
type: QuestionComment

http://stackoverflow.com/a/51620742
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/101157395
has body: While there does not appear to be official support in Visual Studio Code for Windows, the plugin "Code Runner" with the runInTerminal setting fixes this problem. It adds a "Run Code" (Alt-Ctrl-N) to the right-click window of an open editor. If you set the User setting: "code-runner.runInTerminal": true And then run the code, it passes the correct filename to the default executable for your terminal environment.
answers question: http://stackoverflow.com/q/51619868
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51619868
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/a/75316885
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51502263
has body: You get AttributeError: 'DataFrame' object has no attribute ... when you try to access an attribute your dataframe doesn't have. A common case is when you try to select a column using . instead of [] when the column name contains white space (e.g. 'col1 '). df.col1 # <--- error df['col1 '] # <--- no error Another common case is when you try to call a Series method on a DataFrame. For example, tolist() (or map()) are Series methods so they must be called on a column. If you call them on a DataFrame, you'll get AttributeError: 'DataFrame' object has no attribute 'tolist' AttributeError: 'DataFrame' object has no attribute 'map' As hoang tran explains, this is what is happening with OP as well. .str is a Series accessor and it's not implemented for DataFrames. Yet another case is if you have a typo and try to call/access an attribute that's simply not defined; e.g. if you try to call rows() instead of iterrows(), you'll get AttributeError: 'DataFrame' object has no attribute 'rows' You can check the full list of attributes using the following comprehension. [x for x in dir(pd.DataFrame) if not x.startswith('_')] When you assign column names as df.columns = 'col1', 'col2', df is a MultiIndex dataframe now, so to access each column, you'll need to pass a tuple: df['col1'].str.contains('Product A') # <---- error df['col1',].str.contains('Product A') # <---- no error; note the trailing comma In fact, you can pass a tuple to select a column of any MultiIndex dataframe, e.g. df['level_1_colname', 'level_2_colname'].str.contains('Product A') You can also flatten a MultiIndex column names by mapping a "flattener" function on it. A common one is ''.join: df.columns = df.columns.map('_'.join)

http://stackoverflow.com/comment/89948554
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51489959
has text: `assert getMax4([-4, 3, -12, -8, 13]) == -4`?
score: 0

http://stackoverflow.com/q/51586350
has answer: http://stackoverflow.com/a/51586436
tagged with: python
accepted answer: http://stackoverflow.com/a/51586436
type: AnsweredQuestion
upvote count: 1
type: Question
tagged with: dataframe
has body: I am trying to sort a pandas df into individual columns based on when values in columns change. For the df below I can sort the df into separate columns when a values changes in Col B. But I'm trying to add Col Cso it's when values change in both Col B and Col C. import pandas as pd df = pd.DataFrame({ 'A' : [10,20,30,40,40,30,20,10,5,10,15,20,20,15,10,5], 'B' : ['X','X','X','X','Y','Y','Y','Y','X','X','X','X','Y','Y','Y','Y'], 'C' : ['W','W','Z','Z','Z','Z','W','W','W','W','Z','Z','Z','Z','W','W'], }) d = df['B'].ne(df['B'].shift()).cumsum() df['C'] = d.groupby(df['B']).transform(lambda x: pd.factorize(x)[0]).add(1).astype(str) df['D'] = df.groupby(['B','C']).cumcount() df = df.set_index(['D','C','B'])['A'].unstack([2,1]) df.columns = df.columns.map(''.join) Output: X1 Y1 X2 Y2 D 0 10 40 5 20 1 20 30 10 15 2 30 20 15 10 3 40 10 20 5 As you can see, this creates a new column every time there's a new value in Col B. But I'm trying to incorporate Col C as well. So it should be every time there's a change in both Col B and Col C. Intended output: XW1 XZ1 YZ1 YW1 XW2 XZ2 YZ2 YW2 0 10 30 40 20 5 15 20 10 1 20 40 30 10 10 20 15 5
has title: Sort pandas df into individual columns
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/51522457
tagged with: tox
has answer: http://stackoverflow.com/a/51538472
tagged with: shell
accepted answer: http://stackoverflow.com/a/51538472
type: Question
has title: Capture just version from tox commands
tagged with: python
has body: I have following in my tox.ini : [tox] skipsdist = true envlist = py27, py36, lint [testenv] whitelist_externals=flake8 commands = version: python setup.py --version When I run tox -e version I get the following output : tox -e version 2&gt;version version runtests: PYTHONHASHSEED='3264081464' version runtests: commands[0] | python setup.py --version 0.2.0 __________________________________________________________________________________________________________________________________________________________ summary ___________________________________________________________________________________________________________________________________________________________ version: commands succeeded congratulations :) I need to capture just the version (0.2.0) from tox -e version output, what the most elegant/pythonic way of doing it ? Also is there anyway I can have tox just output the output to the command and not the rest ?
score: 0
has answer: http://stackoverflow.com/a/51522538
possible better answer: http://stackoverflow.com/a/51522538
answer count: 2
tagged with: bash
type: AnsweredQuestion
tagged with: sed

http://stackoverflow.com/comment/90059230
score: 0
type: AnswerComment
has text: If you found this helpful, hit that green check next to my answer!
type: Comment
comment on: http://stackoverflow.com/a/51542702

timer
tag name: timer
tags question: http://stackoverflow.com/q/51622900
type: Tag
tags question: http://stackoverflow.com/q/51485284
tags question: http://stackoverflow.com/q/51527472

http://stackoverflow.com/q/51487081
has body: await Bot.send_message(message.channel, "**{}**, you have:\n{}".format(message.author.name, author_dragon &gt; 0)) In the second {} only appears True, I would like him to show an emoji like , what should I do? Give me full answers, thanks!
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51487390
tagged with: python
tagged with: string.format
has title: check True in .format python discord
downvote count: 1
type: Question
tagged with: discord.py
score: 0
upvote count: 1
answer count: 1
tagged with: discord
favorite count: 0

http://stackoverflow.com/q/51534546
type: Question
tagged with: group-by
score: 0
tagged with: pandas
has title: Python: how to reshape pandas dataframe with groupby?
has body: I have a dataframe containing the number of accidents for each day in a grid of dimension NxM. For each cell I have its coordinates x and y. df cell n_acc x y day 0 0 5 0 1 1 1 1 2 0 2 1 2 2 0 1 1 1 3 3 1 1 2 1 4 4 8 2 0 1 5 5 0 2 1 1 6 0 0 0 1 2 7 1 3 0 2 2 8 2 7 1 1 2 9 3 2 1 2 2 10 4 0 2 0 2 11 5 0 2 1 2 I would like to map the total number of accidents in each cell a NxM dataframe or in a NxM array. In the first step I did dftmp = dt.group_by('cell').sum() that returns the sum over all the cell.
has comment: http://stackoverflow.com/comment/90036650
has comment: http://stackoverflow.com/comment/90036877
has comment: http://stackoverflow.com/comment/90036724
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90036655
answer count: 0
has comment: http://stackoverflow.com/comment/90036765

http://stackoverflow.com/comment/89955404
type: Comment
comment on: http://stackoverflow.com/a/51486032
has text: Why the downvote? because I asked for acceptance? Anyway, the answer is correct and therefore a downvote isn't funny at all.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51600710
type: Question
has comment: http://stackoverflow.com/comment/90168127
tagged with: jquery
score: 0
has title: Executing Python with PHP and returning results to a Div
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90167706
has comment: http://stackoverflow.com/comment/90167995
has comment: http://stackoverflow.com/comment/90167720
tagged with: python
tagged with: php
has body: I have been able to successfully execute a python script and return the result to the empty div. It was done using a simple python script (test.py) that returns "hello world". However, the python script I want to execute is significantly more complex with dependencies and includes arguments. $cmd = 'python /home/pi/st/staging/st1.6.1/st.py 1 1'; $command = escapeshellcmd($cmd); $command = escapeshellcmd('python ../testing/test.py'); // this works and is normally commented out $output = exec($command); echo($output); I am wondering if I need to add all the dependencies to the www-data group and chmod them to be executable in order for this to work. The st.py script could take up to an hour to complete. I am building a web interface to run various tasks on a Raspberry Pi automated machine.
answer count: 0

http://stackoverflow.com/a/51587671
has body: The syntax error appears to be caused by the indentation level of your elif line. The conditional statement should be formatted like this: if opt == '-h': print('Roll.py -d &lt;dsize&gt;') sys.exit() elif opt in ("-d", "--dsize"): dsize = arg Here's a link that has some example of conditional statement in python: Flow Control in Python
type: Answer
answers question: http://stackoverflow.com/q/51587502
score: 0

http://stackoverflow.com/q/51610626
upvote count: 0
score: -3
tagged with: http://stackoverflow.com/tag/html
answer count: 1
favorite count: 0
tagged with: parsing
has title: How to parse following HTML file in Python and store into csv with all questions as columns and their answers as rows
has answer: http://stackoverflow.com/a/51611816
type: UnansweredQuestion
tagged with: python
has body: &lt;br&gt;Questionnaire score: 0 out of 0&lt;br&gt; &lt;br&gt;Question: 1: Present Location ? Ready to relocate?&lt;br&gt; &lt;br&gt;Answer: Yes&lt;br&gt; &lt;br&gt;Question: 2: Highest level of education and completion date&lt;br&gt; &lt;br&gt;Answer: Bachelors&lt;br&gt; &lt;br&gt;Question: 3: Are you authorized to work in UK?&lt;br&gt; &lt;br&gt;Answer: Yes&lt;br&gt; Questions are fixed but answers may be different. I have tried HTML parser and beautifulsoup4. Please Help with a suitable code. Thanks..!
has comment: http://stackoverflow.com/comment/90185818
downvote count: 3
has comment: http://stackoverflow.com/comment/90185967
tagged with: html-parsing
type: Question

http://stackoverflow.com/a/51565863
has comment: http://stackoverflow.com/comment/96998627
has body: This is a request that is as complex as the dataclasses module itself, which means that probably the best way to achieve this "nested fields" capability is to define a new decorator, akin to @dataclass. Fortunately, if you don't need the signature of the __init__ method to reflect the fields and their defaults, like the classes rendered by calling dataclass, this can be a whole lot simpler: A class decorator that will call the original dataclass and wrap some functionality over its generated __init__ method can do it with a plain "...(*args, **kwargs):" style function. In other words, all one needs to do is write a wrapper around the generated __init__ method that will inspect the parameters passed in "kwargs", check if any corresponds to a "dataclass field type", and if so, generate the nested object prior to calling the original __init__. Maybe this is harder to spell out in English than in Python: from dataclasses import dataclass, is_dataclass def nested_dataclass(*args, **kwargs): def wrapper(cls): cls = dataclass(cls, **kwargs) original_init = cls.__init__ def __init__(self, *args, **kwargs): for name, value in kwargs.items(): field_type = cls.__annotations__.get(name, None) if is_dataclass(field_type) and isinstance(value, dict): new_obj = field_type(**value) kwargs[name] = new_obj original_init(self, *args, **kwargs) cls.__init__ = __init__ return cls return wrapper(args[0]) if args else wrapper Note that besides not worrying about __init__ signature, this also ignores passing init=False - since it would be meaningless anyway. (The if in the return line is responsible for this to work either being called with named parameters or directly as a decorator, like dataclass itself) And on the interactive prompt: In [85]: @dataclass ...: class A: ...: b: int = 0 ...: c: str = "" ...: In [86]: @dataclass ...: class A: ...: one: int = 0 ...: two: str = "" ...: ...: In [87]: @nested_dataclass ...: class B: ...: three: A ...: four: str ...: In [88]: @nested_dataclass .…
has comment: http://stackoverflow.com/comment/93693444
answers question: http://stackoverflow.com/q/51564841
accepted answer of: http://stackoverflow.com/q/51564841
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/122177174
has comment: http://stackoverflow.com/comment/122183964
has comment: http://stackoverflow.com/comment/103772674
type: Answer
has comment: http://stackoverflow.com/comment/103611653
has comment: http://stackoverflow.com/comment/91430496
has comment: http://stackoverflow.com/comment/91450335
score: 40
upvote count: 40

http://stackoverflow.com/q/51584846
has comment: http://stackoverflow.com/comment/90135268
has body: I have a CSV file containing wind speeds, their directions in degrees, and the date on which each datum was recorded. I am trying to write an if statement so that if the direction is 180 and the date is within a certain month, then put those wind speeds into a new variable. These are two attempts out of many others: if ['Wind Direction'] == 180: if ['Wind Speed'].loc['2016-8-1':'2016-8-31'] windS = ['Wind Speed'] print(windS) Another try that also didn't do anything: for ['Wind Direction'] == 180: winddate = 'Date' if winddate == timedata'Wind Speed'.loc['2016-8-1':'2016-8-31']: windspeedS = 'Wind Speed' print(windspeedS) Can anyone help me do this?
type: UnansweredQuestion
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51585092
has comment: http://stackoverflow.com/comment/90135247
tagged with: analysis
has title: Python if statement basic from file
type: Question
has comment: http://stackoverflow.com/comment/90135237
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/90135300
has comment: http://stackoverflow.com/comment/90135482
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
has comment: http://stackoverflow.com/comment/90135342
favorite count: 0
has comment: http://stackoverflow.com/comment/90135386
has comment: http://stackoverflow.com/comment/90135381

http://stackoverflow.com/a/51520196
has body: You have two things writing to stdout. First the pre_defined_func() which gets called right away in your script, and then later the print() which dumps the pickle result. The two outputs are just done one after the other, so, yes, what you receive is a concatenation of the two. The cls or clear you attempted in between the two is just some more bytes which make a terminal clear its screen, but in a stream they are just some additional bytes. Processes typically have two main output channels called stdout and stderr (output and error messages). Default is to print to stdout, so often all the "results" are written there. Any command doing output can decide to which of these channels the output shall go. Btw, the message you see on the stderr just means that your TERM environment variable isn't set. That typically shouldn't be a problem and is out of scope here. I propose to separate the two things your script writes to the two channels stdout and stderr, then you can also separate them later in the reading script. Just don't do the clear stuff, that doesn't help. ssh luckily transports both channels separately, so this should also work. Find my changes inline. I also transformed your code to need way less quoting. import shlex import subprocess import pickle print_func_py = '''\ import sys def pre_defined_func(): print("I want to clear this message but I could not.", file=sys.stderr) return "answer" result = pre_defined_func() import os import pickle import io bytes = io.BytesIO() byte_stream = pickle.dumps(result) print(byte_stream) ''' print_func_py_sh = shlex.quote(print_func_py) get_value_command = ['ssh', 'localhost', 'python3', '-c', print_func_py_sh] get_value_process = subprocess.run(get_value_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print("stdout = {0}".format(get_value_process.stdout)) print("stderr = {0}".format(get_value_process.stderr))
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/90010575
answers question: http://stackoverflow.com/q/51519728
downvote count: 0
has comment: http://stackoverflow.com/comment/90010169
has comment: http://stackoverflow.com/comment/90010308

http://stackoverflow.com/a/51512833
has comment: http://stackoverflow.com/comment/89994742
answers question: http://stackoverflow.com/q/51512306
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89995319
has comment: http://stackoverflow.com/comment/89995234
has body: I think need str.get_dummies with add_prefix: features = ['Genre','Actors'] for f in features: X_dummy = X[f].str.get_dummies(', ').add_prefix(f + '.') X = X.drop([f], axis = 1) X = pd.concat((X, X_dummy), axis = 1) Or: trainset = pd.DataFrame({'Description':list('abc'), 'Genre':['comedy, drama','action, comedy','action'], 'Actors':['a, b','a, c','d, a'], 'Runtime':[1,3,5], 'E':[5,3,6], 'F':list('aaa')}) print (trainset) Description Genre Actors Runtime E F 0 a comedy, drama a, b 1 5 a 1 b action, comedy a, c 3 3 a 2 c action d, a 5 6 a X = trainset.drop(['Description', 'Runtime'], axis=1) features = ['Genre','Actors'] X_dummy_list = [X.pop(f).str.get_dummies(', ').add_prefix(f + '.') for f in features] X = pd.concat([X] + X_dummy_list , axis = 1) print (X) E F Genre.action Genre.comedy Genre.drama Actors.a Actors.b \ 0 5 a 0 1 1 1 1 1 3 a 1 1 0 1 0 2 6 a 1 0 0 1 0 Actors.c Actors.d 0 0 0 1 1 0 2 0 1
accepted answer of: http://stackoverflow.com/q/51512306
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89995387
has comment: http://stackoverflow.com/comment/89996568

http://stackoverflow.com/comment/90007033
has text: @steff9488 Awesome. Good find on that wiki page. I'll add to the text of this problem. Happy coding!
type: AnswerComment
comment on: http://stackoverflow.com/a/51506592
score: 0
type: Comment

http://stackoverflow.com/comment/89986135
has text: Then don't make them constant.
comment on: http://stackoverflow.com/a/51486670
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/89998694
type: Comment
has text: It worked fine. Just added some lines to get it into a Dataframe in the format i want and the index into a seperate column: `result = pd.DataFrame(S)` `result = result.rename(columns={0:'Other_ID'})` `result['New_ID'] = S.index` ~Cheers
comment on: http://stackoverflow.com/a/51506592
score: 1
type: AnswerComment

http://stackoverflow.com/a/51633578
type: Answer
score: 3
downvote count: 0
has body: It honestly depends on what you expect from the try/except block. If connect() runs some code that you expect might throw a KeyError, let's say because it's assuming a dictionary has been populated, then you might want to catch that and populate the dictionary: try: my_value = my_dict['my_key'] except KeyError: my_dict = populate_my_dict() connect() However, if you don't expect an error from connect but don't want b.py to crash when anything happens, you might want to do something like from a import connect try: connect() except StandardError as err: print("{filename} ran into the following error: {err}".format(filename=__name__, err=err) It's important to never do a bare try/except block, i.e. never use except: as is. Catch specific errors that you expect, because otherwise you end up having code crashing and running under the hood, making it near impossible to debug. Btw, what would happen I have 'nested' try-except? If connect() does not throw a ValueError, connect() will crash, after which the exception is piped over to b.py. Since b.py is expecting any Exception (this is similar to a bare except block, use StandardError or UserWarning instead), the exception will be caught and the body of b.py's except block will trigger.
upvote count: 3
answers question: http://stackoverflow.com/q/51633187

http://stackoverflow.com/a/75613745
has body: I had the same question and the only use case I see for accepting **kwargs in get_context_data is to lower the priority of your context variable. This ensures that it will be overridden by any other mixin or parent class if present. Otherwise, providing a resulting dictionary update will have a different effect due to the MRO position of this mixin. class LowPrioContextMixIn: def get_context_data(self, **kwargs): return super().get_context_data(low_prio_var=True, **kwargs)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51631651

http://stackoverflow.com/comment/90111487
type: Comment
has text: @2012v, I mentioned that the filename should be `backend.py` . But in the code you should only `import backend` not `import backend.py`.
comment on: http://stackoverflow.com/q/51565064
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90169902
comment on: http://stackoverflow.com/a/51601851
score: 0
has text: given the script name (setENVvariables.bat) I doubt that this is very efficient, since if the script sets some variables, they're just lost after the script exits.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51638837
has body: I use a ModelCheckPoint in Keras to save only the best models. Although, I see the val_loss decreasing the ModelCheckPoint says; No. Any ideas? checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='max') This is the last bit of output before finalizing the epoch. As far as I see the val_loss is 4.6578 which is lower than 10.44941. 3648/3768 [============================&gt;.] - ETA: 0s - loss: 3.7331 - acc: 0.1812 3712/3768 [============================&gt;.] - ETA: 0s - loss: 3.7264 - acc: 0.1810 3768/3768 [==============================] - 16s 4ms/step - loss: 3.7243 - acc: 0.1802 - val_loss: 4.6578 - val_acc: 0.1643 Epoch 00056: val_loss did not improve from 10.44941
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51638891
type: Question
answer count: 1
tagged with: keras
tagged with: data-science
score: 0
has title: Keras ModelCheckpoint val_loss decreases but says it doesn't
accepted answer: http://stackoverflow.com/a/51638891

http://stackoverflow.com/q/51554023
upvote count: 1
has comment: http://stackoverflow.com/comment/90074918
score: 1
has body: I recently installed rdkit on pycharm by first using an anaconda environment, installing rdkit using conda install -c rdkit rdkit, and lastly shifting the installed lib package folder to the anaconda environment that my pycharm uses. My pycharm can detect that is an rdkit library imported as I can type the following statement and it suggests a list of possible functions. from rdkit import chem chem.(suggested list appears) However, the suggested list is missing many important functions which is in the rdkit documentation, such as rdkit.chem.Molfromsmiles. Is it because I have to do the proper installation listen on the rdkit website (http://www.rdkit.org/docs/Install.html)? I am not sure how to do those on pycharm and any help is appreciated!
type: Question
downvote count: 0
favorite count: 0
tagged with: rdkit
has comment: http://stackoverflow.com/comment/90107813
tagged with: python
has comment: http://stackoverflow.com/comment/90107792
has comment: http://stackoverflow.com/comment/90078757
has comment: http://stackoverflow.com/comment/90080591
has title: Python: rdkit library missing many functions
tagged with: pycharm
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51608162
has answer: http://stackoverflow.com/a/51608457
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90181480
accepted answer: http://stackoverflow.com/a/51608457
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
tagged with: regex
has body: I want to match and extract a domain name. I have the following line of code: result = re.findall(r"(^((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,1}\.(xn--)?([a-z0-9\-]{1,61}|[a-z0-9-]{1,30}\.[a-z]{2,})$)", text) It does work well for domains like example.org, example.org.eu. But it does not work for domains like sub_example.example.org.eu.
has title: Regular expression to match and extract a long domain

http://stackoverflow.com/comment/90211643
has text: It is really hard to understand your logic. At the end, which teacher `student_7` would get is ambiguous, and so is in some cases in group 2
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51622738

http://stackoverflow.com/a/51484584
type: Answer
has body: out not being defined indicates that the process proc.communicate() did not return any values, otherwise it would have populated your tuple (out, err). Now to find out whether the communicate() method was supposed to return or whether, more likely, your keyboard interrupt simply killed it, thus preventing out from being defined. I assume you imported the subprocess module, but make sure you do that first. I rewrote your program without using global out or the try statements. import subprocess class Testclass: def __init__(self,out): # allows you to pass in the value of out self.out = out # makes out a member of this class def Testdef(self): print("Tail running") tail_cmd='tail -f log.Reconnaissance' proc = subprocess.Popen([tail_cmd], stdout=subprocess.PIPE, shell=True) # Perhaps this is where you want to implement the try: (self.out, err) = proc.communicate() # and here the except: # and here the finally: if __name__ == "__main__": app = Testclass(1) # pass 1 (or anything for testing) to the out variable app.Testdef() print('%r' % app.out) # print the contents of the out variable # i get an empty string, '' So as-is this program runs once. There is nothing in out. I believe to create a meaningful example of the user doing a keyboard interrupt, we need the program to be doing something that can be interrupted. Maybe I can provide an example in the future...
answers question: http://stackoverflow.com/q/51484491
has comment: http://stackoverflow.com/comment/89940674
score: 0
has comment: http://stackoverflow.com/comment/89938315

document
tags question: http://stackoverflow.com/q/51598114
type: Tag
tag name: document

http://stackoverflow.com/comment/90242156
comment on: http://stackoverflow.com/a/51638711
type: AnswerComment
score: 0
type: Comment
has text: @PeterWang you also need my code if you want to write back to the file

http://stackoverflow.com/q/51502558
upvote count: 1
type: Question
has body: I'm trying to automate ChemDraw for a user in the background, preferably avoiding using SendKeys() as I believe that requires a ChemDraw instance to be visible for that to work. What I need to do is somehow click Edit -> Copy As -> InChI programmatically, then retrieve the result from the Windows clipboard. We're currently using Python and COM scripting to attempt this. Here's our current code: # Opens ChemDraw and loads the file, while keeping the window hidden. ChemDraw = w32.DispatchEx('ChemDraw.Application') # ChemDraw Application Object ChemDraw.Visible = False # Makes Invisible Compound= ChemDraw.Documents.Open(cdx_filepath) # ChemDraw File Object (Can be seen with ChemDraw.Activate()) # Selects the whole molecule. Compound.Objects.Select() # Here is where we need to figure out how to do CopyAs and Save off clipboard content. # Saves the file and Quits afterwards. Compound.SaveAs(jpg_filepath) ChemDraw.Quit() I guess I have two questions: how do we access "Edit" in the toolbar and the resulting values in it? How do take the resulting object made from a line like "ChemDraw = w32.DispatchEx('ChemDraw.Application')" and determine what you can do with it? Part of the issue is that we can't seem to introspect the resulting DispatchEx object, thus we're having a hard answering our own question.
tagged with: automation
linked to: http://stackoverflow.com/q/26990655
tagged with: win32com
has answer: http://stackoverflow.com/a/51504119
answer count: 2
has answer: http://stackoverflow.com/a/51543307
tagged with: com
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Windows Application Automation with python/COM
linked to: http://stackoverflow.com/q/58183902
score: 1

http://stackoverflow.com/comment/90095380
type: QuestionComment
score: 1
has text: For what kind of problems do you need such huge evaluations ??? This looks pathological.
comment on: http://stackoverflow.com/q/51556833
type: Comment

http://stackoverflow.com/a/51550306
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51550255
has comment: http://stackoverflow.com/comment/90083049
downvote count: 0
type: Answer
has body: Doing two merge with combine_first r1=df.merge(df1,left_on='code',right_on='album_code',how='left') r2=df.merge(df2,left_on='code',right_on='song_code',how='left') r1.combine_first(r2) Out[547]: value_num code value_letter song album_code song_code 0 1 CDX A Song1 CDX GIB 1 2 DEF B Song2 DEF FRE 2 3 RPQ C Song3 RPQ SSS 3 4 EEE D Song4 REA EEE 4 5 FFX E Song5 VEY FFX 5 6 TRE F Song6 LFM TRE

http://stackoverflow.com/q/51550383
has body: I was calling for an image for a sprite (using notepad++) and the cmd output gave me an error. self.image = pygame.image.load("invader.png").convert() ^ TabError: inconsistent use of tabs and spaces in indentation After running the same code in IDLE it worked just fine with no error messages. I saved and tested the code in notepad++ again and it ran without a problem. Is there a way to get notepad++ stop giving me error messages that aren't errors? both IDLE and notepad++ are up to date and I'm using Python 3.7.
has title: Notepad++/cmd output shows an error that IDLE does not
downvote count: 1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/51550421
score: -1
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51561321
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90089550
has title: Mock a global variable in python
upvote count: 5
type: UnansweredQuestion
tagged with: python
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/90090490
downvote count: 0
has body: I have a function in main module which takes in two values and performs opertaions on them.This uses a global variable which is created before calling this function def calc(keys,values): if globalvar == "calc": return sum(keys) else: return sum(values) Now in unittesting class Testcalc(TestCase): @mock.patch('module.globalvar ', "calc") def test_unit(self,calc): keys=[1,2,3] values=[4,5,6] sum=module.calc(keys,values) """ check asserts """ I am getting an type error with invalid arguments. TypeError('test_unit() takes exactly 2 arguments (1 given)',) Could anyone show me the correct way of mocking the global variable Update: This worked for me not sure why class Testcalc(TestCase): @mock.patch('module.globalvar') def test_unit(self,var): keys=[1,2,3] values=[4,5,6] var="calc" sum=module.calc(keys,values) """ check asserts """ Thank you everyone
tagged with: python-unittest
has answer: http://stackoverflow.com/a/51566836
type: Question
score: 5
tagged with: mocking
has comment: http://stackoverflow.com/comment/90090241
answer count: 1
has comment: http://stackoverflow.com/comment/90089587
favorite count: 0

http://stackoverflow.com/comment/125957845
score: 0
type: Comment
has text: And you if you have Python 2 and Python 3 installed with `/usr/bin/python` linked to `/usr/bin/python2`... As well as the package `python3-apt` installed... You'd specify: `-e ansible_python_interpreter=/usr/bin/python3`
comment on: http://stackoverflow.com/a/65859504
type: AnswerComment

http://stackoverflow.com/q/51636434
has comment: http://stackoverflow.com/comment/90259632
has comment: http://stackoverflow.com/comment/90242575
has body: I have a pandas dataframe with 1 million rows. I want to replace values in 900,000 rows in a column by another set of values. Is there fast way to do this without a for loop (which takes me two days to complete)? For example, look at this sample dataframe where I have condensed 1 million rows to 8 rows import numpy as np import pandas as pd df = pd.DataFrame() df['a'] = [-1,-3,-4,-4,-3, 4,5,6] df['b'] = [23,45,67,89,0,-1, 2, 3] L2 = [-1,-3,-4] L5 = [9,10,11] I want to replace values where a is -1, -3, -4 in a single shot if possible or as fast as possible without a for loop. The crucial part is that values in L5 have to be repeated as needed. I have tried df.loc[df.a &lt; 0, 'a'] = L5 but this works only when len(df.a.values) == len(L5)
has comment: http://stackoverflow.com/comment/90242499
accepted answer: http://stackoverflow.com/a/51636516
upvote count: 4
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51636569
has comment: http://stackoverflow.com/comment/90239034
favorite count: 0
has comment: http://stackoverflow.com/comment/90259617
has title: fastest way to change multiple loc in a dataframe
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51636569
tagged with: python
type: AnsweredQuestion
downvote count: 1
type: Question
score: 3
has answer: http://stackoverflow.com/a/51636516

http://stackoverflow.com/a/51553778
accepted answer of: http://stackoverflow.com/q/51553467
has body: The problem is you are using find() for ipList, which fetches only one ip, you can use findall() or select which will return ip array. import requests from bs4 import BeautifulSoup url ='https://myip.ms/browse/blacklist/Blacklist_IP_Blacklist_IP_Addresses_Live_Database_Real-time' response = requests.get(url).content soup = BeautifulSoup(response, 'html.parser') ipList = soup.select(".row_name") with open('ip_output.csv', 'w') as f: for ips in ipList: f.write(ips.find('a').text + '\n') Output in csv 195.154.251.86 37.140.192.194 80.94.174.55 175.103.39.28 90.173.129.250 51.15.146.121 ... ...
answers question: http://stackoverflow.com/q/51553467
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90074468
has comment: http://stackoverflow.com/comment/90074442
has comment: http://stackoverflow.com/comment/90074626

http://stackoverflow.com/comment/90041001
comment on: http://stackoverflow.com/q/51536619
score: 0
type: Comment
type: QuestionComment
has text: Prepend *why* to title. @sophros

http://stackoverflow.com/q/51483072
has body: I have a data set that is in a 2-d numpy array of size 25000 by 13. There are numbers in 25 by 7 of that array and the rest is nan. How do I remove all the nans? I have tried: test[~np.isnan(test)] with "test" being my array and separately have tried (I believe they are the same) test[np.logical_not(np.isnan(test))] both of which put the 25 by 7 array into a 175 by 1 array after going through the operation. Thank you in advance
has comment: http://stackoverflow.com/comment/89941941
tagged with: python
has comment: http://stackoverflow.com/comment/89935009
has comment: http://stackoverflow.com/comment/89936381
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89935386
accepted answer: http://stackoverflow.com/a/51486304
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/89941613
tagged with: arrays
has comment: http://stackoverflow.com/comment/89941620
score: -1
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51486304
has title: Deleting "nan" from 2-d array in python
favorite count: 0

http://stackoverflow.com/q/51593052
has comment: http://stackoverflow.com/comment/90151662
has comment: http://stackoverflow.com/comment/90151520
type: Question
has comment: http://stackoverflow.com/comment/90151686
has comment: http://stackoverflow.com/comment/90154982
has answer: http://stackoverflow.com/a/51593194
possible better answer: http://stackoverflow.com/a/51594780
has comment: http://stackoverflow.com/comment/90158659
has comment: http://stackoverflow.com/comment/90158584
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/51594780
accepted answer: http://stackoverflow.com/a/51594913
answer count: 3
tagged with: unicode
has title: python - conversion of a string to a unicode string
has comment: http://stackoverflow.com/comment/90155076
has comment: http://stackoverflow.com/comment/90152069
has comment: http://stackoverflow.com/comment/90151929
has comment: http://stackoverflow.com/comment/90151718
has body: Im using a library unidecode to convert accentred strings to ascii represented stirngs. &gt;&gt;&gt; accented_string = u'Málaga' # accented_string is of type 'unicode' &gt;&gt;&gt; import unidecode &gt;&gt;&gt; unidecode.unidecode(accented_string) &gt;&gt;&gt; Malaga But the problem is I'm reading the string from a file how do I send it to the 'unidecode' library. for name in strings: print unidecode.unidecode(u+name) #????? I can't get my head around it? if I encode it that just gives me the wrong encoding.
tagged with: python
tagged with: utf
has comment: http://stackoverflow.com/comment/90151773
has comment: http://stackoverflow.com/comment/90151815
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90154926
has answer: http://stackoverflow.com/a/51594913

http://stackoverflow.com/a/61027090
upvote count: 0
score: -1
has body: El problema se solucionaba importando en orden. user.py: from topic import Topic class User(Document): username = StringField(unique=True, required=True) following_topics = ListField(ReferenceField('Topic', reverse_delete_rule=PULL, unique=True)) topic.py: class Topic(Document, ModelMixin): title = StringField(default='') user = ReferenceField('User', required=True)
type: Answer
answers question: http://stackoverflow.com/q/51563007
has comment: http://stackoverflow.com/comment/107965871
downvote count: 1

http://stackoverflow.com/q/51505792
has body: I`m trying to install library called textgenrnn, followed by this in docs: pip3 install textgenrnn Got error that my Python version is 2.7: Collecting textgenrnn Using cached https://files.pythonhosted.org/packages/00/69/5d995322502f8a33d408c547a6dbf00e74d4434ecc1b704b684260739b21/textgenrnn-1.3.1.tar.gz textgenrnn requires Python '&gt;=3' but the running Python is 2.7.15 You are using pip version 9.0.3, however version 18.0 is available. You should consider upgrading via the 'pip install --upgrade pip' command. I also check my Python version using this command: python -V and get Python 3.6.5 :: Anaconda, Inc. Update: After uninstalling anaconda I got this: dmitriy@dmitriy-PC:~$ python -V Python 2.7.15rc1 dmitriy@dmitriy-PC:~$ python3 -V Python 3.6.5 My first think is to delete or disable python 2. But after googling I decided that python2 is impossible to uninstall or disable
upvote count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51512777
has title: Error with installing textgenrnn
tagged with: python
has answer: http://stackoverflow.com/a/51512021
has answer: http://stackoverflow.com/a/51512777
tagged with: installation
score: 1
type: Question
type: AnsweredQuestion
tagged with: anaconda
possible better answer: http://stackoverflow.com/a/51512021
answer count: 2

http://stackoverflow.com/q/51487797
tagged with: python
has title: In Django, how to find rows which would violate a unique together constraint?
type: AnsweredQuestion
downvote count: 0
type: Question
has body: For the following API endpoint, import json from django.contrib.auth.decorators import login_required from django.http import JsonResponse, HttpResponseBadRequest from django.views.decorators.http import require_POST from lucy_web.models import UserApn @login_required @require_POST def save_apn(request, version): player_id = json.loads(request.body).get('player_id') if player_id: UserApn.objects.get_or_create(user=request.user, player_id=player_id) return JsonResponse({'status': 'success'}) else: return HttpResponseBadRequest() Here is the underlying model: from django.contrib.auth.models import User from django.db import models from .timestamped_model import TimeStampedModel class UserApn(TimeStampedModel): user = models.ForeignKey(User) player_id = models.CharField(max_length=255) The call to get_or_create() has been raising some MultipleObjectsReturned errors. To fix this, I'd like to impose a unique_together constraint on the user and player_id. Firstly, however, I have to write a data migration that eliminates rows that violate this unique together constraint. How could I write a query that selects these? Right now the following has been proposed: def remove_duplicate_apns(apps, schema_editor): UserApn = apps.get_model('lucy_web', 'UserApn') previous_user_id = None previous_player_id = None for apn in UserApn.objects.all().order_by('user_id', 'player_id'): if apn.user_id == previous_user_id and apn.player_id == previous_player_id: print(f'deleting {apn} (id: {apn.id})') apn.delete() else: previous_user_id = apn.user_id previous_player_id = apn.player_id It seems, though, that this could also be done in a single query. Update I've found that one can pass the two fields, user and player_id, to .values(), and then check for duplicates using .distinct(). For example, the following test passes: from django.test import TestCase from django.contrib.auth.models import User from myapp.models import UserApn class UserApnTest(TestCase): def test_1(self): user = User.objec…
tagged with: database
upvote count: 6
tagged with: migration
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51488990
accepted answer: http://stackoverflow.com/a/51488990
score: 6
tagged with: unique-constraint
tagged with: django

http://stackoverflow.com/comment/132135693
comment on: http://stackoverflow.com/q/51624803
score: 0
type: Comment
type: QuestionComment
has text: Does this answer your question? [Cannot split, a bytes-like object is required, not 'str'](https://stackoverflow.com/questions/50829364/cannot-split-a-bytes-like-object-is-required-not-str)

http://stackoverflow.com/comment/89939927
comment on: http://stackoverflow.com/a/51485188
has text: @mahesh Exactly. I have added a function that you can use to normalize your data with different scikit-learn scalers.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/136807982
type: Comment
has text: How can I use `['NoStockCode','Description','Quantity']` as a variable? something like: `df.groupby(list_1, as_index=False)list_2.agg(lambda x: list(x))`
comment on: http://stackoverflow.com/a/51584444
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90089893
comment on: http://stackoverflow.com/q/51561500
score: 2
type: Comment
type: QuestionComment
has text: Please don't include screenshots of the error, copy/paste them in code format into your question. Links to images can expire.

http://stackoverflow.com/comment/90050634
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51541416
has text: Whereas in C, this would be a valid operation and probably quite a nasty (if not immediately apparent) bug to fix.
type: Comment

http://stackoverflow.com/a/51484023
answers question: http://stackoverflow.com/q/51483611
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/90054127
has body: Perhaps you should be using INSERT ... ON DUPLICATE KEY UPDATE. Then, instead of selecting and re-processing each row of the table, you merely insert that data with one call to cursor.execute, and let the MySQL engine handle the updates when there is a duplicate key: heads = ','.join(str(i) for i in mylisth) placelst = ['%s' for i in mylisth] placestr = ','.join(str(i) for i in placelst) replacestr = ', '.join(['{}=%s'.format(h) for h in mylisth]) sql = """INSERT INTO capacitors ({heads}) VALUES ({placestr}) ON DUPLICATE KEY UPDATE {replacestr}""".format( heads=heads, placestr=placestr, replacestr=replacestr) for data_capacitor in larger_loop: args = data_capacitor*2 cursor.execute(sql, args)
has comment: http://stackoverflow.com/comment/89938338
has comment: http://stackoverflow.com/comment/90023831
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51483611
has comment: http://stackoverflow.com/comment/90027071
has comment: http://stackoverflow.com/comment/89937540

http://stackoverflow.com/a/51582406
accepted answer of: http://stackoverflow.com/q/51582380
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: Removing an item from the middle of a list will shift everything after that item one position closer to the start of the list. l = ['a', 'b', 'c'] del l[1] print(l) # ['a', 'c'] print(l[1]) # c
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51582380

http://stackoverflow.com/comment/90135381
comment on: http://stackoverflow.com/q/51584846
has text: @Dodo Not sure how to link something. It's a file on my computer! I tried to drop it in here but it didn't work.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51636973
has body: I would use a function such as the following def create_list(arr1, arr2, n): c = [] for i in range(len(arr1)//n): for j in range(3): c.append(arr1[(i*3)+j]) for j in range(3): c.append(arr2[(i*3)+j]) return c This should give you the kind of list you were looking for.
score: 0
answers question: http://stackoverflow.com/q/51636876
type: Answer

http://stackoverflow.com/q/51520137
answer count: 4
has answer: http://stackoverflow.com/a/51521500
has comment: http://stackoverflow.com/comment/90009063
has body: I have tried numerous ways but how do I input a matrix something like this 2,3;2,4;2,1;3,5;3,4;4,2 4,2;4,1;3,1;3,6;4,4;1,4 1,2;1,3;4,5;5,5;2,1;1,5 6,2;6,1;2,2;5,6;2,6;2,5 3,2;3,3;6,5;6,6;6,3;6,4 5,3;5,4;5,1;5,2;4,6;1,6 my approach is as shown below: matrix=[[j for j in input().split(';')]for i in range(n)] Where n is the order of matrix of size n by n .I need to input coordinates of another cell in each cell .Eg: At (1,1) we have (2,3) then it should redirect me to the cell row=2 and column =3 where the coordinates are (3,1) and so on until an ending condition is met.I am using 1 based indexing here. When I do as above it takes '2,3' as a string and when I use int(j) it gives an error showing that 2,3 cannot be an integer. Can anyone come up with an approach ?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90009525
has comment: http://stackoverflow.com/comment/90009594
has comment: http://stackoverflow.com/comment/90009178
downvote count: 1
possible better answer: http://stackoverflow.com/a/51520296
has comment: http://stackoverflow.com/comment/90009472
type: Question
has title: how do I input pairs of comma separated positive integers, each pair separated by a semicolon(;) in python
has comment: http://stackoverflow.com/comment/90009288
has answer: http://stackoverflow.com/a/51520296
has comment: http://stackoverflow.com/comment/90009554
has comment: http://stackoverflow.com/comment/90009473
has comment: http://stackoverflow.com/comment/90009214
has comment: http://stackoverflow.com/comment/90009431
has answer: http://stackoverflow.com/a/51520411
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/90009223
has answer: http://stackoverflow.com/a/51520920
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90009536
accepted answer: http://stackoverflow.com/a/51520411
has comment: http://stackoverflow.com/comment/90009267
tagged with: python

http://stackoverflow.com/comment/90023561
type: QuestionComment
has text: @Joel Can you explain more, I think it shouldn't. About the first example it was a typo and I fixed it.
comment on: http://stackoverflow.com/q/51508937
score: 0
type: Comment

http://stackoverflow.com/a/51557574
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90086649
has body: The repository lacks setup.py hence it's not pip-installable. Clone it or download it, create a subdirectory in site-packages/ and copy the code there manually.
has comment: http://stackoverflow.com/comment/90087291
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51555900
answers question: http://stackoverflow.com/q/51555900

http://stackoverflow.com/comment/90153039
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51590144
has text: Thanks! I managed in other way, but yours seems easier. Btw. here is the project subject, I you'd like to check: https://stackoverflow.com/questions/51592631/real-estate-market-scrapping-using-python-and-beautifulsoup
score: 0

http://stackoverflow.com/a/51548173
has body: You're looking for the Cartesian product of a bunch of ranges the argument of which is defined by your input list: from itertools import product lims = [3, 2, 1] gen = product(*(range(1,lim+1) for lim in lims)) print(list(gen)) The result is [(1, 1, 1), (1, 2, 1), (2, 1, 1), (2, 2, 1), (3, 1, 1), (3, 2, 1)]
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51548094

http://stackoverflow.com/comment/90120939
has text: you may improve even more, iterating upto `(i+1)/2`, because there will be no divisors above that =)
comment on: http://stackoverflow.com/a/51577350
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51585383
has answer: http://stackoverflow.com/a/51604388
accepted answer: http://stackoverflow.com/a/51604388
score: 0
answer count: 2
has title: Error while getting the redirected url in scrapy : Python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51586767
tagged with: python
type: AnsweredQuestion
has body: I'm using the code: def parse_find(self, response): Download_URL = "https://download.example.com/b/zMTY" request = Request(Download_URL, callback=self.parse_final) yield request def parse_final(self, response): redirected_URL = response.url FileName = response.headers['Content-Disposition'] yield{ "Download_URL":redirected_URL, "FileName":FileName} to get the redirected url and its headers, but the scrapy gives debug: 2018-07-30 04:41:49 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting ( 302) to &lt;GET https://example.com/url&gt; from &lt;GET https://download.example.com/b/zMTY&gt; 2018-07-30 04:41:51 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting ( meta refresh) to &lt;GET https://example.com&gt; from &lt;GET https://example.com/url&gt; It must be noted that when I use fetch to extract this url in scrapy shell then it grabs the redirected url and response.headers works fine. I'm using Python 3.6.5 and scrapy 1.5
tagged with: web-scraping
tagged with: scrapy
type: Question
possible better answer: http://stackoverflow.com/a/51586767

http://stackoverflow.com/comment/90078303
type: QuestionComment
comment on: http://stackoverflow.com/q/51555629
has text: Good question. This answer provides more details and probably has a more reliable method: https://stackoverflow.com/a/48665619/8477066 If using that method it most likely does not matter.
score: 0
type: Comment

http://stackoverflow.com/comment/139433008
comment on: http://stackoverflow.com/a/72266642
type: AnswerComment
score: 0
has text: What, you mean tensorflow?
type: Comment

http://stackoverflow.com/q/51576642
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/51577313
tagged with: python
tagged with: artificial-intelligence
has body: everyone, I have a CNN-LSTM model trained in keras. As input, i loaded sets of 15 frames per video with 30x30 and with just one channel (15, 30, 30, 1). I extracted them from a total of 279 videos, and stored them in a big tensor with dimensions (279, 15, 30, 30, 1). X_data.shape = (279, 15, 30, 30, 1) y_data.shape = (279,) I'm working with two classes of videos (so targets are 0 and 1). The input layer of my time distributed CNN (before my LSTM layer) is: input_layer = Input(shape=(None, 30, 30, 1)) Ok, they feeded in my network and everything worked well, but now i need to predict these videos and i want to display the output in the video i'm classifying. I wrote this to read the video and display the text: vid = cv2.VideoCapture(video_path) while(vid.isOpened()): ret, frame = vid.read() if ret == True: texto = predict_video(frame) frame = cv2.resize(frame,(750,500),interpolation=cv2.INTER_AREA) frame = cv2.putText(frame,str(texto),(0,130), cv2.FONT_HERSHEY_SIMPLEX, 2.5, (255, 0, 0), 2, cv2.LINE_AA) cv2.imshow('Video', frame) if cv2.waitKey(25) &amp; 0xFF == ord('q'): break else: break vid.release() cv2.destroyAllWindows() The predict_video() is used to generate the predicted output as a text, as you can see: def predict_video(frame): count_frames = 0 frame_list = [] frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frame = cv2.resize(frame,(30,30),interpolation=cv2.INTER_AREA) while count_frames &lt; 15: frame_list.append(frame) count_frames = 0 frame_set = np.array(frame_list) frame_set = frame_set.reshape(1, 15, 30, 30, 1) pred = model.predict(frame_set) pred_ = np.argmax(pred,axis=1) #i'm using the Model object from Keras if pred_ == 1: return 'Archery' elif pred_ == 0: return 'Basketball' Due to the fact that the input dimension of the CNN-LSTM is equal to (None, 30, 30, 1) i need to predict with model.predict(sample) a sample with dimensions like this (1, 15, 30, 30, 1). How i can predict a video in real time, once i want to predict not frame by frame but with…
downvote count: 1
type: Question
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51577313
score: -1
has title: How to Display CNN-LSTM predicted output in the Video with OpenCV?
tagged with: deep-learning
upvote count: 0
answer count: 1

acrobat
type: Tag
tags question: http://stackoverflow.com/q/51530305
tag name: acrobat

http://stackoverflow.com/comment/90025252
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51527369
has text: I just had to remove '\n' from text variable and then your solution worked. Thank you.
type: AnswerComment

http://stackoverflow.com/comment/90196760
score: 0
comment on: http://stackoverflow.com/q/51614561
type: Comment
type: QuestionComment
has text: $LD_LIBRARY_PATH is located here: /home/david/Documents/oracle: as is the pyhton file i am running

http://stackoverflow.com/a/51626550
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51626468
has body: You need change condition for equal, shift and filter by inverted boolean mask: dl = df[~(df['B'] == 'Foo').shift().fillna(False)] print (dl) A B C 0 X Foo X 2 3 X Foo X
answers question: http://stackoverflow.com/q/51626468
type: Answer

http://stackoverflow.com/comment/90072104
comment on: http://stackoverflow.com/a/51486187
type: AnswerComment
has text: I see there is no explicit MacOS guideline there. Though MacOS build steps are very similar to the Linux ones, you might some find specific guidelines here: https://gist.github.com/jruizvar/0535fb8612afb105e0eef64051dc0d00
score: 0
type: Comment

http://stackoverflow.com/comment/90060717
type: QuestionComment
has text: Note that I am creating a new list, not simply mutating an old list. I'm creating a new list whose items result from mutating individual items in a list_of_lists.
comment on: http://stackoverflow.com/q/51546348
score: 0
type: Comment

http://stackoverflow.com/comment/90210455
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51622010
has text: And what if I have to calculate the rolling mean for the same for each season?
type: Comment

http://stackoverflow.com/comment/89978050
type: Comment
has text: what exactly do you want to plot? do you only need a scatter plot or do you want to plot the decision surface/boundaries ?? Also what is `d_train_std `?
type: QuestionComment
comment on: http://stackoverflow.com/q/51495819
score: 0

http://stackoverflow.com/q/51635541
tagged with: progress-bar
has body: I need a progressbar to show the user the progress of the svn updates, but I do not know how to do this simultaneously to the svn update, I can only do it afterwards and then only indirectly, but if I let the progressbar show after the update , then I need twice the time and that's not the point. Please help me how to update the progressbar while the update is running which needs a variable time and please give me an example of what you mean class test(): def __init__(self, dictionary_with_paths): self.dictionary_with_paths = {} self.progressbar = Progressbar(range_end) def update_local_tag_folder(self): os.system('svn update '+ self.dictionary_with_paths['local_tags']) def update_progressbar(self, current_value): """ Progressbar() is a class that simply create an tk() frame with 1 label, an progressbar and a button and it need an start value and an end point, the end point comes with an parameter in the class, the start/current count are given from method Progressbar().set_current_Value(current_value) """ self.progressbar.set_current_value(current_Value) self.progressbar.update() def get_update_progress_and_update_bar(self): """ here is the point i have no idea how can i can get an list of files or any other useful things """ SVN_list = os.system('svn ls -v -R '+ \ self.dictionary_with_paths['repository_trunk']) """ Console shows an list with all files, but i cant read the lines to count that """ I also thought about using subprocessor but I do not know exactly how to read the output of SVN_list so that I can count the lines SOLVED: Fixed problem, I have created new threads in which I can once run the svn update and in another I can simultaneously create the Progressbar and let it run ... short snapshot what i mean... from threading import Thread from time import sleep class Yeeeehaaa(): def mymethod1(self, arg): for e in range(0,arg): print('Yeeeee') sleep(1) def mymethod2(self, arg): for e in range(0,arg): print('haaaaa') sleep(1) def start_threads(self): thread …
has comment: http://stackoverflow.com/comment/90246486
type: Question
tagged with: python
tagged with: tkinter
tagged with: time
score: 0
tagged with: svn
type: UnansweredQuestion
has title: Python tkinter Progressbar for svn update
has comment: http://stackoverflow.com/comment/90238738
answer count: 0

http://stackoverflow.com/comment/90120841
comment on: http://stackoverflow.com/q/51568417
score: 0
type: Comment
type: QuestionComment
has text: @DanCornilescu I've updated the question with that output; it works correctly.

http://stackoverflow.com/a/51586509
has body: Client and User have a many-to-many relationship in this case, so you should define you Client and User with a ManyToManyField: class Client(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, blank=True, null=True) class User(models.Model): username = models.CharField(max_length=50, unique=True) password = models.CharField(max_length=50, blank=True, null=True) clients = models.ManyToManyField(Client) So that you can easily obtain a list of clients a given user is assigned to: for user in User.clients.all(): print(user) Please read Many-to-many relationships documentation. On a side note, id field is automatically generated for every model, so you don't have to define it explicitly.
answers question: http://stackoverflow.com/q/51586393
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90139146

http://stackoverflow.com/comment/90170291
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51601905
type: AnswerComment
has text: I have tried doing what you mentioned, but I receive an error: AttributeError: 'str' object has no attribute 'decode'.

http://stackoverflow.com/a/51629382
has body: Print z is used prior to Python version 3.x. Newer versions (>3.x) require the print() syntax. If you are defining a function for multiplication, you should not print inside of it, rather return the result and print it there: print(test(4,6)). In this way, you can also use the actual function for something else.
downvote count: 1
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/90223175
answers question: http://stackoverflow.com/q/51629244
has comment: http://stackoverflow.com/comment/90224030
type: Answer

http://stackoverflow.com/q/51526324
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
tagged with: matplotlib
has answer: http://stackoverflow.com/a/56730347
type: Question
answer count: 1
has title: Displaying 3D data with uneven voxel size using matplotlib
has comment: http://stackoverflow.com/comment/90024911
linked to: http://stackoverflow.com/q/42611342
downvote count: 0
has body: I'm trying to display 3D data using matplolib. I have a list of numpy arrays representing DICOM slices. Each slice contains structure points. I want to display this structure in 3d but dicom voxels are of irregular shape. Ex their shape is [1.4, 1.4, 2]. Is there a way to scale axes in x, y and z dimensions, so it would show how the structure really looks like? Currently, when i display it looks deformed.
favorite count: 0

http://stackoverflow.com/q/51553722
tagged with: math
tagged with: numpy
score: 0
accepted answer: http://stackoverflow.com/a/51567082
answer count: 1
has title: Tensor Scalar Multiplication Tensor Flow
has comment: http://stackoverflow.com/comment/90079564
tagged with: python
has body: I'm currently trying to implement my own loss function. I have three tensors. A [batch, row, col, keypoints] # Actual Values B [batch, row, col, keypoints] # Predicted Values C [batch, keypoints_mask] # Mask keypoints_mask is either 1 or 0. I want to treat the tensors as arrays and do scalar multiplication of the last dimension. E.g something like this: A [5, 100, 100, 10] B [5, 100, 100, 10] C [5, 10] A[-1][0] = A[-1][0] * C[-1][0] A[-1][1] = A[-1][1] * C[-1][1] ... B[-1][0] = B[-1][0] * C[-1][0] B[-1][1] = B[-1][1] * C[-1][1] ... Loss = Mean_Squared_Error(A, B) What would be the best approach to do implement this? Edit: The data is an image, where for every pixel I have 10 values. Psuedo Code for b in batch: for r in row: for c in col: for i in enumerate(keypoints): A[b, r, c, i] = A[b, r, c, i] * C[b, i] B[b, r, c, i] = B[b, r, c, i] * C[b, i]
has answer: http://stackoverflow.com/a/51567082
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90091064
type: AnsweredQuestion

http://stackoverflow.com/q/51530678
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90053798
has comment: http://stackoverflow.com/comment/90029414
has comment: http://stackoverflow.com/comment/90067491
has title: Python 3: Binary Search Tree failed to set nodes
has answer: http://stackoverflow.com/a/51532516
answer count: 1
downvote count: 0
has body: so I have been working on this class project implementing a binary search tree. The professor wants us to make the private recursive while make the public one simple. (like when to insert_element(50), it calls a private function recursive_insert(50, self.__root) to solve). My insertion function runs for no error yet the test case always return empty, and here are my codes for the private functions: class Binary_Search_Tree: class __BST_Node: def __init__(self, value): self.value = value self.left=None self.right=None def __init__(self): self.__root = None self.__height=0 self.__size=0 def _in_order_str(self, root): if root is None: outcome= "[ ]" elif self.__size==1: outcome = "[ " + str(root.value) + " ]" else: outcome = "[ " self._in_order_str(root.left) outcome += str(root.value) +", " self._in_order_str(root.right) outcome+= " ]" return outcome def _recur_ins(self, val,root): if root is None: root=Binary_Search_Tree.__BST_Node(val) elif root.value&gt;val: root.left = _recur_ins(val,root.left) #do I need self here? elif root.value &lt;val: root.right = _recur_ins(val,root.right) return root And this one is for the public: def insert_element(self, value): self._recur_ins(value,self.__root) self.__size+=1 My Test Case: def test_insertion_from_empty(self): root=None self.__bst.insert_element(50) self.__bst.insert_element(30) self.__bst.insert_element(70) self.assertEqual('[ 30, 50, 70 ]', self.__bst.in_order()) UPDATE: I think the problem comes from my _in_order_str(self, root): method. The general case I found online is: def inorder(root): if root is not None: inorder(root.left) print root.key inorder(root.right) I know this could be a very silly question, but I really failed to figure it our by myself. Any help will be appreciated so thank you so much!!!
favorite count: 0
tagged with: binary-tree
tagged with: python-3.x
tagged with: binary-search-tree
has comment: http://stackoverflow.com/comment/90029477
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90053878
accepted answer: http://stackoverflow.com/a/51532516

http://stackoverflow.com/a/51576588
type: Answer
has comment: http://stackoverflow.com/comment/90336791
has comment: http://stackoverflow.com/comment/90332711
score: 4
upvote count: 4
has body: Not exactly sure if I understand the question correctly. It looks like it would make more sense to look at the proportion of answers per boat type and color. import matplotlib.pyplot as plt import pandas as pd data = [{'ship': 'Yes','canoe': 'Yes', 'cruise': 'Yes', 'kayak': 'No','color': 'Red'},{'ship': 'Yes', 'cruise': 'Yes', 'kayak': 'Yes','canoe': 'No','color': 'Green'},{'ship': 'Yes', 'cruise': 'Yes', 'kayak': 'No','canoe': 'No','color': 'Green'},{'ship': 'Yes', 'cruise': 'Yes', 'kayak': 'No','canoe': 'No','color': 'Red'},{'ship': 'Yes', 'cruise': 'Yes', 'kayak': 'Yes','canoe': 'No','color': 'Red'},{'ship': 'No', 'cruise': 'Yes', 'kayak': 'No','canoe': 'Yes','color': 'Green'},{'ship': 'No', 'cruise': 'No', 'kayak': 'No','canoe': 'No','color': 'Green'},{'ship': 'No', 'cruise': 'No', 'kayak': 'No','canoe': 'No','color': 'Red'}] df = pd.DataFrame(data) ax = df.replace(["Yes","No"],[1,0]).groupby("color").mean().transpose().plot.bar(color=["g","r"]) ax.set_title('Proportion "Yes" answers per of boat type and color') plt.show() This means e.g. that 25% of all green canoes answered "yes".
downvote count: 0
answers question: http://stackoverflow.com/q/51532581

http://stackoverflow.com/comment/90215460
has text: @Nin: It doesn't necessarily need a `sum` function or the like; if the class implements `__index__`/`__int__`, when it gets used in a scenario that requires an integer value, it can seamlessly compute the final summed value. Along with a custom `__repr__`, it can appear to be an `int` in most ways.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51625207
type: QuestionComment

http://stackoverflow.com/comment/90234612
comment on: http://stackoverflow.com/a/51631955
type: AnswerComment
has text: @ArhiliucCristina I see. My assumption was correct after all then. Thanks for the clarification.
score: 0
type: Comment

http://stackoverflow.com/q/51574701
has body: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a1 = np.arange(10000, dtype=np.int32) &gt;&gt;&gt; a2 = np.arange(10000, dtype=np.float32) &gt;&gt;&gt; %timeit -n 1000 -r 5 np.sum(a1) 110 µs ± 1.18 µs per loop (mean ± std. dev. of 5 runs, 1000 loops each) &gt;&gt;&gt; %timeit -n 1000 -r 5 np.sum(a2) 50.1 µs ± 895 ns per loop (mean ± std. dev. of 5 runs, 1000 loops each) Can anybody please explain to me this massive difference between speed for the same operation but with different dtypes? This has really confused me. Naively I would think the ops on int32 would be faster but it was a shock to see the above results. Thanks for the help in advance.
type: Question
has comment: http://stackoverflow.com/comment/90115437
linked to: http://stackoverflow.com/q/18743397
tagged with: numpy
has title: Why NumPy operations are faster for np.float32 than np.int32?
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90115533
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/90115187
upvote count: 1

http://stackoverflow.com/comment/90170686
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51602052
score: 1
has text: Oh, so this error message is actually pretty self-explanatory. It essentially already lists all the options you have.

http://stackoverflow.com/q/51632716
has title: Keras Concatenate Layers: Difference between different types of concatenate functions
tagged with: keras-layer
answer count: 2
has body: I just recently started playing around with Keras and got into making custom layers. However, I am rather confused by the many different types of layers with slightly different names but with the same functionality. For example, there are 3 different forms of the concatenate function from https://keras.io/layers/merge/ and https://www.tensorflow.org/api_docs/python/tf/keras/backend/concatenate keras.layers.Concatenate(axis=-1) keras.layers.concatenate(inputs, axis=-1) tf.keras.backend.concatenate() I know the 2nd one is used for functional API but what is the difference between the 3? The documentation seems a bit unclear on this. Also, for the 3rd one, I have seen a code that does this below. Why must there be the line ._keras_shape after the concatenation? # Concatenate the summed atom and bond features atoms_bonds_features = K.concatenate([atoms, summed_bond_features], axis=-1) # Compute fingerprint atoms_bonds_features._keras_shape = (None, max_atoms, num_atom_features + num_bond_features) Lastly, under keras.layers, there always seems to be 2 duplicates. For example, Add() and add(), and so on.
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/51633009
tagged with: python
upvote count: 15
type: AnsweredQuestion
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/51633018
accepted answer: http://stackoverflow.com/a/51633018
possible better answer: http://stackoverflow.com/a/51633009
score: 15

http://stackoverflow.com/comment/90255381
type: Comment
comment on: http://stackoverflow.com/a/51639725
has text: https://docs.python.org/3/reference/import.html#loading. Second bullet point under the code snippet
type: AnswerComment
score: 1

http://stackoverflow.com/comment/90015442
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51521733
has text: I'm working in a python notebook and it's better to visualize a dataframe
type: Comment

http://stackoverflow.com/q/51504087
score: 0
has comment: http://stackoverflow.com/comment/89977101
type: UnansweredQuestion
has title: Cannot find reference self.loadFinished.connect when trying to execute scripts in HTML pages
tagged with: python
answer count: 0
tagged with: pyqt5
type: Question
has body: I'm trying to build a PyQT5 class that will execute s embedded within it. Here's the code: class Render(QWebPage): def __init__(self, html): self.html = None self.app = QApplication(sys.argv) QWebPage.__init__(self) self.loadFinished.connect(self._loadFinished) self.mainFrame().setHtml(html) self.app.exec_() def _loadFinished(self, result): self.html = self.mainFrame().toHtml() self.app.quit() That connect method is unreferencable, here's what I imported: from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl from PyQt5.QtWebKitWidgets import QWebPage Am I missing something?
has comment: http://stackoverflow.com/comment/89977039
tagged with: qwebpage
has comment: http://stackoverflow.com/comment/89986711

http://stackoverflow.com/comment/112068065
comment on: http://stackoverflow.com/q/51511813
has text: Title does not match the question. :/
type: Comment
type: QuestionComment
score: 6

http://stackoverflow.com/comment/90171291
has text: On a side note, use the prefix r to your path, that is, path_4BPSK = r"C:\Users...". Using this saves you from adding the '\\' instead of a simple '\'
comment on: http://stackoverflow.com/q/51593390
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/51609904
tagged with: pandas
has body: I have a folder with a number of CSV files. Each file follows the same format with the header: date,total_cost,total_pnl_pre,total_pnl_pos,total_pnl_per_pre,total_pnl_per_pos A typical CSV file will look like: date,total_cost,total_pnl_pre,total_pnl_pos,total_pnl_per_pre,total_pnl_per_pos 2015-07-27,-0.0,0.0,0.0,0.0,0.0 2015-07-28,-0.0,0.0,0.0,0.0,0.0 2015-07-29,-0.6738699251792465,0.0,-0.6738699251792465,-0.0,-0.027000000000000003 2015-07-30,-0.0,-123.88294424426506,-123.88294424426506,-4.961880089696313,-4.961880089696313 2015-07-31,-0.0,1.9275568497366795,1.9275568497366795,0.09627642044988116,0.09627642044988116 However there are some files where I have NaN values (see below) date,total_cost,total_pnl_pre,total_pnl_pos,total_pnl_per_pre,total_pnl_per_pos 2015-07-27,-0.0,0.0,0.0,0.0,0.0 2015-07-28,-0.0,0.0,0.0,0.0,0.0 2015-07-29,NaN,NaN,NaN,0.0,0.0 2015-07-30,NaN,NaN,NaN,0.0,0.0 2015-07-31,NaN,NaN,NaN,0.0,0.0 I have two scripts hit_rate and max_drawdown that I use to process these files is: def hit_rate(array_like): seq=np.array(array_like) seq=seq[np.nonzero(seq)] total_num=len(seq) if total_num==0: return -float('Inf') pos_num=len(seq[seq&gt;0.0]) neg_sum=total_num-pos_num if neg_sum==0: return float('inf') return pos_num/neg_sum def max_drawdown(ser): running_max=pd.expanding_max(ser) cur_dd=ser-running_max return min(0,cur_dd.min()) The CSV file is read into the script in the variable array_like and ser The scripts falls over when it encounters a NaN value. Is there a way to either set the NaN values to zero or ignore the NaN values when processing the CSV file?
has comment: http://stackoverflow.com/comment/90185346
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/13295735
tagged with: python
has comment: http://stackoverflow.com/comment/90185213
has title: Introduce a check for or ignore NaN values
duplicate of: http://stackoverflow.com/q/13295735
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/90184681
has comment: http://stackoverflow.com/comment/90185309
type: Question
has comment: http://stackoverflow.com/comment/90185265
has comment: http://stackoverflow.com/comment/90185146

http://stackoverflow.com/comment/90021361
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51526242
has text: Note that if you change `10` to `11`, the `[None] * 11` list has size `152`, but the list comprehension still has size `192`. The previously linked question isn't an exact duplicate, but it is relevant in understanding why this happens.
score: 1

http://stackoverflow.com/comment/90101493
has text: What isn't clear about "If classinfo is not a type or tuple of types and such tuples, a `TypeError` exception is raised."?
comment on: http://stackoverflow.com/q/51567356
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51497299
has body: I am using csvFile=open("yelloUSA.csv",'w+') to make a new csv file. now I want to write the file names from 1-10. But I want to use formatting to write the names. how can I do that? I used below code but it is showing error for i in range(0,10): csvFile=open("{0}.csv",'w+').format(i) writer=csv.writer(csvFile)
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: -4
type: Question
has answer: http://stackoverflow.com/a/51497359
downvote count: 4
has title: how to use formatting to write a new csv file in python
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89962435

http://stackoverflow.com/a/51547349
has body: You need to change input_size to 4 (2*2), and not 2 as your modified code currently shows. If you compare it to the original MNIST example, you'll see that input_size is set to 784 (28*28) and not just to 28.
answers question: http://stackoverflow.com/q/51545026
accepted answer of: http://stackoverflow.com/q/51545026
type: Answer
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/comment/90116667
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51575203
has text: That worked! It gave me the SellerSKU for each order. Now if I can ask a followup - do you know how I would be able to pull out SellerSKU and QuantityOrdered separated by a comma?
type: AnswerComment

http://stackoverflow.com/comment/90101277
comment on: http://stackoverflow.com/a/51566598
type: AnswerComment
has text: How about `window=4;df.rolling(window, min_periods=1).apply(lambda x: (x>70).sum()>=2)`? That seems to handle edge cases correctly.
score: 0
type: Comment

boto3
tags question: http://stackoverflow.com/q/51517996
tags question: http://stackoverflow.com/q/51503458
tags question: http://stackoverflow.com/q/51518511
tags question: http://stackoverflow.com/q/51551417
tags question: http://stackoverflow.com/q/51576138
tags question: http://stackoverflow.com/q/51556951
tags question: http://stackoverflow.com/q/51528871
tags question: http://stackoverflow.com/q/51604102
tags question: http://stackoverflow.com/q/51544804
tags question: http://stackoverflow.com/q/51546550
tags question: http://stackoverflow.com/q/51511376
tags question: http://stackoverflow.com/q/51606401
tags question: http://stackoverflow.com/q/51506863
tag name: boto3
tags question: http://stackoverflow.com/q/51604091
tags question: http://stackoverflow.com/q/51589901
tags question: http://stackoverflow.com/q/51635286
tags question: http://stackoverflow.com/q/51531900
tags question: http://stackoverflow.com/q/51620414
type: Tag
tags question: http://stackoverflow.com/q/51604689

http://stackoverflow.com/comment/90124388
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51578522
type: QuestionComment
has text: It looks ok, but the idea is for you to *understand* the suggestion and continue on your own. If you have to ask if you are on track, then you must be missing something basic (like how Python global variables work) and I'm not really helping.

http://stackoverflow.com/comment/90092064
comment on: http://stackoverflow.com/q/51561242
has text: This code is pretty confusing, but, for one thing: arrays start at 0. Therefore, the reason you're skipping the letter 'a' is because your loop goes from 1 to 25.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51578252
has comment: http://stackoverflow.com/comment/90121947
has body: In my opinion loop is not necessary. You can specify column(s) in list for aggregation: df = locPd.groupby('Filename', as_index=False)['Code Lines'].sum() print (df) Filename Code Lines 0 Repo_1 401 1 Repo_2 471 2 Repo_3 300 If want aggregate all numeric columns: df1 = locPd.groupby('Filename', as_index=False).sum() print (df1) Filename Blank Lines Code Lines Comment Lines 0 Repo_1 100 401 68 1 Repo_2 110 471 89 2 Repo_3 78 300 74 For get counts is possible use DataFrameGroupBy.agg: df1 = (locPd.groupby('Filename')['Code Lines'] .agg([('tot', 'sum'),('count', 'size')]) .reset_index()) print (df1) Filename tot count 0 Repo_1 401 20 1 Repo_2 471 23 2 Repo_3 300 15
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51578234
has comment: http://stackoverflow.com/comment/90121992
answers question: http://stackoverflow.com/q/51578234
type: Answer
upvote count: 6
score: 6

http://stackoverflow.com/comment/90214470
score: 0
type: AnswerComment
type: Comment
has text: Thank you so much. And by the way is it possible to have a independent python 3.6.5 and anaconda with 3.6 at the same time? I'm affraid they might overlap
comment on: http://stackoverflow.com/a/51624703

http://stackoverflow.com/q/51638613
has answer: http://stackoverflow.com/a/51638634
accepted answer: http://stackoverflow.com/a/51638634
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: How do I multiply a pandas column with a part of a multi index dataframe
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: multiplication
has body: I have a data frame with a multi index and one column. Index fields are type and amount, the column is called count I would like to add a column that multiplies amount and count df2 = df.groupby(['type','amount']).count().copy() # I then dropped all columns but one and renamed it to "count" df2['total_amount'] = df2['count'].multiply(df2['amount'], axis='index') doesn't work. I get a key error on amount. How do I access a part of the multi index to use it in calculations?
upvote count: 1
type: Question

http://stackoverflow.com/comment/90052476
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51531002
has text: Sorry it took so long. Mobile is a pain to write on.

http://stackoverflow.com/a/51635764
score: 0
has body: Why don't you use pd.merge directly? You could create two dataframes, one for company_name matching, the second for website matching and then left merge competitor_companies on each of these dataframes. # Create 2 matching tables c_website = companies'uuid', 'website'.rename(columns={'uuid': 'uuid_from_website'}) c_name = companies'uuid', 'company_name'.rename(columns={'uuid': 'uuid_from_name'}) # Merge on each of these tables result = competitor_companies\ .merge(c_website, how='left', on='website')\ .merge(c_name, how='left', on='company_name') You then need to reconciliate those two values, for instance giving priority to uuid_from_name: result['uuid'] = np.where(res.uuid_from_name.notnull(), res.uuid_from_name, res.uuid_from_website) del result['uuid_from_name'] del result['uuid_from_website'] It should be much faster than using pd.Series.isin.
type: Answer
answers question: http://stackoverflow.com/q/51625942

http://stackoverflow.com/a/51588469
has comment: http://stackoverflow.com/comment/90248787
answers question: http://stackoverflow.com/q/51585285
type: Answer
has comment: http://stackoverflow.com/comment/90178949
has body: The tutorial you're following doesn't look very good, a couple of things: You don't need to do pg.font.init() if you do pg.init() (docs) If you're going to use a Sysfont (like calibri), you don't need to do self.font_name = pg.font.match_font('calibri') and then pg.font.Font(self.font_name, size). Just use SysFont Where is self.all_sprites define? You use it in draw but I don't see where is initialize. If new() resets the game, it does not make much sense call it in the game loop. Also, if new() resets the game, why it calls the draw functions? mixer is for sounds. If you're not going to play any sound, there's no need to initialize it. Also, if you don't want sound delay, you have to initialize it before pg.init() and using mixer.pre_init() and mixer.init() show_go_screen method is missing too :/ The fill method does not receive (0,0,0), it should be ((0,0,0)) for black. In the draw_text method, "white" is not a color, it's a variable. You should use (255,255,255) instead. After all of this: The error I have is from the fill function, not from font. After fixing it, I have an error from that missing variables/methods I pointed before. After fixing all this. I don't have any error. If you know spanish, I have a repo with the basics of pygame https://github.com/Patataman/PythonBasic/tree/master/frameworks/pygame. If not, well, maybe you can figure out xD
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90172154
downvote count: 0

http://stackoverflow.com/comment/89948048
type: Comment
comment on: http://stackoverflow.com/a/51489407
has text: What version of tensorflow have you got installed?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51526142
accepted answer: http://stackoverflow.com/a/66488249
has comment: http://stackoverflow.com/comment/90124333
possible better answer: http://stackoverflow.com/a/73265487
score: 8
has answer: http://stackoverflow.com/a/73265487
has comment: http://stackoverflow.com/comment/90070188
answer count: 5
has answer: http://stackoverflow.com/a/77381606
tagged with: python
tagged with: mongodb-atlas
has title: connection times out when trying to connect to mongodb atlas with python
has body: I'm trying to connect to my mongodb atlas cluster but i keep getting timed out as soon as i try to do something with my db. The db i use was created in mongoshell and also the collection i checked their existence in mongodb compass ERROR pymongo.errors.ServerSelectionTimeoutError: projekt-shard-00-01-rk7ft.mongodb.net:27017: timed out,projekt-shard-00-00-rk7ft.mongodb.net:27017: timed out,projekt-shard-00-02-rk7ft.mongodb.net:27017: timed out CODE client = MongoClient("""mongodb://user:password@projekt-shard-00-00-rk7ft.mongodb.net:27017,projekt-shard-00-01-rk7ft.mongodb.net:27017,projekt-shard-00-02-rk7ft.mongodb.net:27017/projekt?ssl=true&amp;replicaSet=projekt-shard-0&amp;authSource=admin""") client.projekt.category.insert_one({type : "pants"}).inserted_id
type: AnsweredQuestion
downvote count: 0
tagged with: pymongo
has answer: http://stackoverflow.com/a/71070573
upvote count: 8
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/78081162
favorite count: 0
has answer: http://stackoverflow.com/a/66488249

http://stackoverflow.com/comment/90122876
comment on: http://stackoverflow.com/q/51578659
score: 1
has text: I think these are the flags: https://docs.opencv.org/3.4/de/d30/structcv_1_1DrawMatchesFlags.html Maybe `flags=2|4` can help?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51503997
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/51504070
type: AnsweredQuestion
tagged with: list
has body: Im trying to parse some XML files.. but for some reason it overwrites the list values even tho I append to the list. Code here: def parseXML(): xmlfiles = glob.glob('./*.xml') temp = {} for host in xmlfiles: tree = ET.parse(host) root = tree.getroot() for wizard in tree.findall('.'): for grandpa in wizard: for parent in grandpa: if parent.get('addr') != None: ip = parent.get('addr') temp[ip] = {} for child in parent: if child.get('portid') != None: for grandchild in child: if grandchild.get('name') != None: name = grandchild.get('name') if child.get('portid') not in temp: temp[ip][name] = [] temp[ip][name].append(child.get('portid')) else: print (temp + " else") print (temp) expected outcome: {'127.0.0.2': {'ssh': ['22'], 'http': ['80','8080']}, '127.0.0.1': {'ssh': ['22'], 'http': ['80','8080']}} but Instead I get: {'127.0.0.2': {'ssh': ['22'], 'http': ['8080']}, '127.0.0.1': {'ssh': ['22'], 'http': ['8080']}}
downvote count: 1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/89976721
score: -1
answer count: 1
has title: Python overwrites list values
has comment: http://stackoverflow.com/comment/89976781
favorite count: 0
has answer: http://stackoverflow.com/a/51504070
has comment: http://stackoverflow.com/comment/89976753
tagged with: python

http://stackoverflow.com/comment/90033480
type: Comment
has text: It is `records` like `orient='records'`
comment on: http://stackoverflow.com/a/51531439
type: AnswerComment
score: 0

http://stackoverflow.com/a/51671065
downvote count: 0
score: 11
type: AcceptedAnswer
has body: You can use the following project structure: # /myproject # settings.py # main.py # /models # __init__.py # base.py # requisitions.py # workorders.py # sales_orders.py settings.py is a file with database settings: # settings.py db_params = {'provider': 'sqlite', 'filename': ':memory:'} main.py is a file when you start application. You put db.generate_mapping here: # main.py from pony import orm import settings from models import db from your_favorite_web_framework import App # orm.set_sql_degug(True) db.bind(**settings.db_params) db.generate_mapping(create_tables=True) with orm.db_session: orm.select(u for u in db.User).show() if __name__ == '__main__': app = App() app.run() Note that it is not necessary to implicitly import all models, as they are accessible as attributes of db object (like db.User) You can put db object in base.py (or general.py), where you define your core models: # base.py from pony import orm db = orm.Database() class User(db.Entity): name = Required(str) orders = Set('Order') Note that in User model I can refer to Order model defined in another module. You can also write it as orders = Set(lambda: db.Order) Unfortunately, IDEs like PyCharm at this moment cannot recognize that db.Order refers to specific Order class. You can import and use Order class directly, but in some cases it will lead to problem with cyclic imports. In other model files you import db from .base: # workorders.py from pony import orm from .base import db class Order(db.Entity): description = Optional(str) user = Required('User') In /models/__init__.py you import all modules to ensure that all models classes are defined before generate_mapping is called: # /models/__init__.py from .base import db from . import workorders ... And then you can write from models import db And access models as db attributes like db.User, db.Order, etc. If you want to refer models directly in your code instead of accessing them as db attributes, you can import all models in __init__.py: # /model…
type: Answer
upvote count: 11
answers question: http://stackoverflow.com/q/51601838
accepted answer of: http://stackoverflow.com/q/51601838

http://stackoverflow.com/q/51536758
has comment: http://stackoverflow.com/comment/90041214
upvote count: 1
has answer: http://stackoverflow.com/a/51536990
type: Question
has comment: http://stackoverflow.com/comment/90041391
downvote count: 0
tagged with: python-2.7
has title: How to replace the function in Python?
answer count: 1
has body: I want to change a Python 2 code to Python 3. In particular, I would like to change a.itervalues to a.values. I would to know if it is possible to define a new function so that when the program comes across .itervalues, it will run my new function instead of its original one? Thank you very much.
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 1

http://stackoverflow.com/a/51581212
has comment: http://stackoverflow.com/comment/90128010
has comment: http://stackoverflow.com/comment/90128179
has comment: http://stackoverflow.com/comment/90132630
has comment: http://stackoverflow.com/comment/90128099
has comment: http://stackoverflow.com/comment/90127783
score: 0
answers question: http://stackoverflow.com/q/51581145
has body: Instead of using an inner for loop, use XPath. for product_number in products_missing_from_postgresql: entries = xml_tree.xpath("//entry[@id = '%s']" % product_number) if entries: print('FOUND: ' + product_number) else: print('NOT FOUND: ' + product_number) If your product_number can contain single quotes, the above will break. It's generally preferable to use a placeholder in the XPath and pass the actual value separately: entries = xml_tree.xpath("//entry[@id = $value]", value=product_number)
type: Answer

http://stackoverflow.com/a/51519335
accepted answer of: http://stackoverflow.com/q/51519086
type: Answer
answers question: http://stackoverflow.com/q/51519086
upvote count: 7
has comment: http://stackoverflow.com/comment/90020295
score: 7
type: AcceptedAnswer
downvote count: 0
has body: Use tearoff=0. From the NM Tech Tkinter reference: tearoff Normally, a menu can be torn off: the first position (position 0) in the list of choices is occupied by the tear-off element, and the additional choices are added starting at position 1. If you set tearoff=0, the menu will not have a tear-off feature, and choices will be added starting at position 0. You can see the difference in this example: from tkinter import * root = Tk() menubar = Menu(root) tearoff = Menu(menubar, tearoff=1) tearoff.add_command(label="Tearoff") menubar.add_cascade(label="Tearoff", menu=tearoff) notearoff = Menu(menubar, tearoff=0) notearoff.add_command(label="No Tearoff") menubar.add_cascade(label="No Tearoff", menu=notearoff) root.config(menu=menubar) root.mainloop()

http://stackoverflow.com/a/51489096
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89947124
score: 1
answers question: http://stackoverflow.com/q/51489071
has body: Because the dictionary isn't None. There's a difference between a value being falsey, and it satisfying is None. Just test the truthiness directly: if a is not None and not dict: As noted in the comments though, don't name variables the same as existing function names. That's just asking for 'dict' object is not callable errors in the future.
downvote count: 0
has comment: http://stackoverflow.com/comment/89947135

http://stackoverflow.com/a/51571709
score: 2
upvote count: 3
downvote count: 1
has body: Use if: if lst: for a in lst: do_something
has comment: http://stackoverflow.com/comment/90109374
answers question: http://stackoverflow.com/q/51571696
type: Answer

http://stackoverflow.com/q/51511957
has answer: http://stackoverflow.com/a/51512169
has comment: http://stackoverflow.com/comment/89992296
answer count: 3
accepted answer: http://stackoverflow.com/a/51512169
has body: I have large file contain multiple lines but in some line having unique pattern, I want to split our large file based on this pattern. Below data in text file: commit e6bcab96ffe1f55e80be8d0c1e5342fb9d69ca30 Date: Sat Jun 9 04:11:37 2018 +0530 configurations commit 5c8deb3114b4ed17c5d2ea31842869515073670f Date: Sat Jun 9 02:59:56 2018 +0530 remote commit 499516b7e4f95daee4f839f34cc46df404b52d7a Date: Sat Jun 9 02:52:51 2018 +0530 remote fix This reverts commit 0a2917bd49eec7ca2f380c890300d75b69152353. commit 349e1b42d3b3d23e95a227a1ab744fc6167e6893 Date: Sat Jun 9 02:52:37 2018 +0530 Revert "Removing the printf added" This reverts commit da0fac94719176009188ce40864b09cfb84ca590. commit 8bfd4e7086ff5987491f280b57d10c1b6e6433fe Date: Sat Jun 9 02:52:18 2018 +0530 Revert Bulk This reverts commit c2ee318635987d44e579c92d0b86b003e1d2a076. commit bcb10c54068602a96d367ec09f08530ede8059ef Date: Fri Jun 8 19:53:03 2018 +0530 fix crash observed commit a84169f79fbe9b18702f6885b0070bce54d6dd5a Date: Fri Jun 8 18:14:21 2018 +0530 Interface PBR commit 254726fe3fe0b9f6b228189e8a6fe7bdf4aa9314 Date: Fri Jun 8 18:12:10 2018 +0530 Crash observed commit 18e7106d54e19310d32e8b31d584cec214fb2cb7 Date: Fri Jun 8 18:09:13 2018 +0530 Changes to fix crash Currently my code as below: import re readtxtfile = r'C:\gitlog.txt' with open(readtxtfile) as fp: txtrawdata = fp.read() commits = re.split(r'^(commit|)[ a-zA-Z0-9]{40}$',txtrawdata) print(commits) Expected Output: I want to split above string based on "commit 18e7106d54e19310d32e8b31d584cec214fb2cb7" and convert them into python list.
has title: How to split large text file based on regex using python
score: 2
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/51512117
has answer: http://stackoverflow.com/a/51512117
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89992469
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51512362
tagged with: python
tagged with: regex

http://stackoverflow.com/a/51623575
score: 1
answers question: http://stackoverflow.com/q/51622604
upvote count: 1
type: Answer
downvote count: 0
has body: IIUC Try cumcount df.groupby(df.index).cumcount() Out[11]: 0 0 1 0 2 0 0 1 1 1 2 1 0 2 1 2 2 2 0 3 1 3 2 3 dtype: int64

http://stackoverflow.com/q/51579074
downvote count: 0
favorite count: 0
has title: Read all rows of a column and check for delimiter and if found create column with that data (need of 4 columns) in Python
score: 3
tagged with: python
tagged with: delimiter
upvote count: 3
type: UnansweredQuestion
has body: I have a column data like below (dtype:object): Column A 1324@Hi how are you//where are you: I am in London@Cool place@Nice 5649@Hello Christina@Awesome Trip @Fantastic Expected output: Col A Col B Col C Col D 1324 Hi how are you//where Cool place Nice are you: I am in London 5649 Hello Christina Awesome Trip Fantastic I need to check for the delimiter "@" in all rows. Create 4 columns for the first 4 occurrences and for the next four occurences, need to append the data in next row of the same 4 columns as i mentioned in above table. It would be grateful if any possible solution. Thanks in Advance.
has answer: http://stackoverflow.com/a/51579202
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51579309

django-views
tags question: http://stackoverflow.com/q/51512931
tags question: http://stackoverflow.com/q/51581516
tags question: http://stackoverflow.com/q/51628776
tags question: http://stackoverflow.com/q/51536732
tags question: http://stackoverflow.com/q/51594414
tags question: http://stackoverflow.com/q/51606239
tags question: http://stackoverflow.com/q/51630858
tags question: http://stackoverflow.com/q/51559298
tags question: http://stackoverflow.com/q/51524567
tag name: django-views
tags question: http://stackoverflow.com/q/51509710
type: Tag
tags question: http://stackoverflow.com/q/51489154
tags question: http://stackoverflow.com/q/51534109
tags question: http://stackoverflow.com/q/51612839
tags question: http://stackoverflow.com/q/51574458
tags question: http://stackoverflow.com/q/51615227
tags question: http://stackoverflow.com/q/51610002
tags question: http://stackoverflow.com/q/51524441
tags question: http://stackoverflow.com/q/51580691
tags question: http://stackoverflow.com/q/51607991
tags question: http://stackoverflow.com/q/51584401
tags question: http://stackoverflow.com/q/51595004
tags question: http://stackoverflow.com/q/51537874

http://stackoverflow.com/a/51599057
type: Answer
answers question: http://stackoverflow.com/q/51598916
has body: from collections import Counter v = ['a','e','i','o','u'] word ="Milliwaysaaa" d=dict(Counter(word)) found=[key for key in d.keys() if key in v] #['a', 'i']
score: 0

http://stackoverflow.com/q/51546742
has comment: http://stackoverflow.com/comment/90061326
has comment: http://stackoverflow.com/comment/90061836
tagged with: big-o
has comment: http://stackoverflow.com/comment/90061306
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90061276
has body: Working my way through "Cracking the coding interview", and a practice question says Given 2 strings, write a method to decide if one is a permutation of the other. The author's python solution is as follows: def check_permutation(str1, str2): if len(str1) != len(str2): return False counter = Counter() for c in str1: counter[c] += 1 for c in str2: if counter[c] == 0: return False counter[c] -= 1 return True Which claims to be in O(N) time. My solution is as follows: def perm(str1,str2): if(len(str1) != len(str2)): return False for c in str1: if c not in Str2: return False return True And I believe this to also be O(N). Is this true? Which algorithm is favorable? The author's data type seems unneccesary. And lastly, is this algorithm O(NlogN)? def perm(str1,str2): return sorted(str1)==sorted(str2)
has comment: http://stackoverflow.com/comment/90061814
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90061808
accepted answer: http://stackoverflow.com/a/51547542
type: AnsweredQuestion
tagged with: algorithm
score: 1
has comment: http://stackoverflow.com/comment/90061456
possible better answer: http://stackoverflow.com/a/51547556
has answer: http://stackoverflow.com/a/51547556
type: Question
answer count: 2
downvote count: 0
tagged with: runtime
favorite count: 0
has title: What is big O notation of these permutation algorithms
has answer: http://stackoverflow.com/a/51547542

http://stackoverflow.com/a/51522983
score: 1
upvote count: 1
has body: One way to do so would be to first use int to just obtain the integer part of the float. Then if you just want a number like 3. this is impossible without converting to string since 3. give 3.0. So perhaps convert the integer part to a string then concatenate a period of the form '3.' An example: In [1]: num = 3.14 In [2]: myint = int(num) In [3]: myint Out[3]: 3 In [4]: mystr = str(myint) In [5]: mystr Out[5]: '3' In [6]: mystr += '.' In [7]: mystr Out[7]: '3.' or in one step: mystr = str(int(num)) + '.' giving the output of '3.' given the input num = 3.14: In [12]: mystr Out[12]: '3.'
type: Answer
answers question: http://stackoverflow.com/q/51522816
downvote count: 0

http://stackoverflow.com/q/51580601
has body: I'm a beginner Python programmer and currently using pyCharm CE IDE on a MAC OS High Sierra system following a tutorial to create a database web-app. The issue I am facing is when I try to add any mysql access library in 'requirements.txt' the installation fails. (tried with Flask-Mysqldb, mysqlclient, mysqldb) I figured out that the issue i was facing earlier missing mysql_config was due to using AMPPS (Softaculous) MAMP stack and was able to fix it by updating my $PATH variable to include the path to /Applications/AMPPS/mysql/bin Now the error I am getting is clang: error: unknown argument: '-fabi-version=2' Most of the solutions I have come across are suggestions to replace MAMP MySQL with the homebrew version (or something similar). Ideally I would like to stick with AMPPS since I am familiar with this and have other apps currently hosted on it (e.g. Wordpress).
type: Question
tagged with: python
tagged with: pycharm
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51636087
has title: Error "-fabi-version=2" when installing Msyqldb or Flask-mysqldb (or any mysql client) in PyCharm on Mac OS using AMPPS
tagged with: mysql
type: UnansweredQuestion

http://stackoverflow.com/q/51508185
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51508697
type: Question
tagged with: locate
tagged with: dataframe
tagged with: type-conversion
score: 0
tagged with: types
answer count: 1
has title: How to check if a dataframe contains any string and find the location of it if it does exist in python?
has body: When I try to convert a dataframe to dtype=float, it returns error says can't convert string to float. Thus I am trying to find the location of the string in the dataframe. Here is a sample dataframe I created: df = pd.DataFrame(np.arange(1,25).reshape(6,4)) Attribute = ['Eric', 'Sarah', 'Steve', 'David', 'Sam', 'Joe'] df.insert(0, 'Name', Attribute) df[2][4] = 'strin' and it looks like: Name 0 1 2 3 0 Eric 1 2 3 4 1 Sarah 5 6 7 8 2 Steve 9 10 11 12 3 David 13 14 15 16 4 Sam 17 18 strin 20 5 Joe 21 22 23 24 By the way it raises a warning: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame If anyone knows how to avoid the warning pls lmk too. I create an iterator to return the position of str in columns I want: for x in range(2,df.shape[1]): for y in range(df.shape[0]): if type(df.iloc[:,x][y]) == str: print('str:',(y,x)) it works. returns str: (4, 3). I wonder if there is a easier way to do it.
accepted answer: http://stackoverflow.com/a/51508697
tagged with: python

http://stackoverflow.com/q/51632215
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51633073
tagged with: ftplib
tagged with: python
tagged with: ftp
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51633073
has title: Upload a in-memory file (generated by API calls) in FTP by chunks in Python
tagged with: paramiko
tagged with: sftp
has body: I need to be able to upload a file through FTP and SFTP in Python but with some not so usual constraints. File MUST NOT be written in disk. The file how it is generated is by calling an API and writing the response which is in JSON to the file. There are multiple calls to the API. It is not possible to retrieve the whole result in one single call of the API. I can not store in a string variable the full result by doing the multiple calls needed and appending in each call until I have the whole file in memory. File could be huge and there is a memory resource constraint. Each chunk should be sent and memory deallocated. So here some sample code of what I would like to: def chunks_generator(): range_list = range(0, 4000, 100) for i in range_list: data_chunk = requests.get(url=someurl, url_parameters={'offset':i, 'limit':100}) yield str(data_chunk) def upload_file(): chunks_generator = chunks_generator() for chunk in chunks_generator: data_chunk= chunk chunk_io = io.BytesIO(data_chunk) ftp = FTP(self.host) ftp.login(user=self.username, passwd=self.password) ftp.cwd(self.remote_path) ftp.storbinary("STOR " + "myfilename.json", chunk_io) I want only one file with all the chunks appended. What I have already and works is if I have the whole file in memory and send it at once like this: string_io = io.BytesIO(all_chunks_together_in_one_string) ftp = FTP(self.host) ftp.login(user=self.username, passwd=self.password) ftp.cwd(self.remote_path) ftp.storbinary("STOR " + "myfilename.json", string_io ) I need this in ftplib but will need it in Paramiko as well for SFTP. If there are any other libraries that this would work better I am open.

http://stackoverflow.com/q/51617848
has comment: http://stackoverflow.com/comment/90458107
score: 0
type: UnansweredQuestion
tagged with: python
has body: from random import randint board = [] for x in range(0, 5): board.append(["O"] * 5) def print_board(board): for row in board: print " ".join(row) print_board(board) def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) ship_row = random_row(board) ship_col = random_col(board) print ship_row print ship_col guess_col = int(raw_input("Guess Col: ")) guess_row = int(raw_input("Guess Row: ")) if guess_row == ship_row and guess_col == ship_col: print "Congratulations! You sank my battleship!" else: if guess_row not in range(5) or \ guess_col not in range(5): print "Oops, that's not even in the ocean." elif (board[guess_row][guess_col] == 'X'): print "You guessed that one already." else: print "You missed my battleship!" board[guess_row][guess_col] = "X" print_board(board)
answer count: 0
has comment: http://stackoverflow.com/comment/90201494
type: Question
has title: When I run this program, it does not take the second user input and automatically makes First_User_Input == Second_User_Input

http://stackoverflow.com/q/51624207
tagged with: python
has comment: http://stackoverflow.com/comment/90214088
has body: I'm planning to implement autocomplete feature using trie data structure. I want to convert my trie into a JSON format. class Trie(object): """Class representing the structure of trie""" def __init__(self): self.children={} #Links to other nodes self.isEndOfWord=False This is the output of my trie program [ ('Z', &lt;search_trie.Trie object at 0x7f3350f32c50&gt;), ('j', &lt;search_trie.Trie object at 0x7f3353e77da0&gt;), ('z', &lt;search_trie.Trie object at 0x7f3350f32be0&gt;), ('M', &lt;search_trie.Trie object at 0x7f33538eb668&gt;) ] where: 'Z'-character stored in the trie node &lt;search_trie.Trie object at 0x7f3350f32c50&gt; -points to other node How can I convert this to JSON format? I don't want the object address to be present in JSON. How can I extract the nodes from the address and include it in JSON? EDIT: This is my code. What modification should I do to avoid storing nodes as references? If I can store the actual object value instead of address, converting it into JSON will be simple. from functools import reduce class Trie(object): """Class representing the trie""" def __init__(self): self.children={} self.isEndOfWord=False def add(self,char): #Adds a character to dictionary and creates a new node self.children[char]=Trie() def insert(self,word): #Insert a new word to the trie node=self for char in word: if char not in node.children: node.add(char) node=node.children[char] node.isEndOfWord=True def search(self, word): #Search for a particular word in a trie node = self for char in word: if char not in node.children: return False node = node.children[char] return node.isEndOfWord def all_suffixes(self,prefix): results = set() if self.isEndOfWord: results.add(prefix) if not self.children: return results return reduce(lambda a, b: a | b, [node.all_suffixes(prefix + char) for (char, node) in self.children.items()]) | results def autocomplete(self, prefix): node = self for char in prefix: if char not in node.children: return set() node = node.children[char] …
answer count: 0
score: 1
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/51295864
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90213452
tagged with: trie
downvote count: 0
favorite count: 0
has title: Converting a Trie into JSON format
has comment: http://stackoverflow.com/comment/90213511
type: UnansweredQuestion

http://stackoverflow.com/q/51537065
tagged with: python
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90041689
linked to: http://stackoverflow.com/q/48207115
score: 1
has answer: http://stackoverflow.com/a/51537096
type: Question
tagged with: split
answer count: 2
upvote count: 1
has body: Given below is the view of my Dataframe Id,user_id 1,glen-max 2,tom-moody I am trying to split the values in user_id column and store it in a new column. I am able to split the user_id using the below code. z = z['user_id'].str.split('-', 1, expand=True) I would like this split column to be part of my original Dataframe. Given below is the expected format of the Dataframe Id,user_id,col1,col2 1,glen-max,glen,max 2,tom-moody,tom,moody Could anyone help how I could make it part of the original Dataframe. Tnx..
favorite count: 0
has answer: http://stackoverflow.com/a/51537108
tagged with: pandas
has title: Pandas - Splitting text using a delimiter

http://stackoverflow.com/a/51550511
answers question: http://stackoverflow.com/q/51550255
score: 0
has body: Here is a reproducible solution: import pandas as pd cols = ['value_num', 'code', 'value_letter'] data = [(1, 'CDX', 'A'), (2, 'DEF', 'B'), (3, 'RPQ', 'C'), (4, 'EEE', 'D'), (5, 'FFX', 'E'), (6, 'REM', 'F'), (7, 'TRE', 'G')] main_df = pd.DataFrame.from_records(data, columns=cols) ind_df = pd.DataFrame(index=main_df['code']) cols = ['song', 'album_code', 'song_code'] data = [('Song1', 'CDX', 'GIB'), ('Song2', 'DEF', 'FRE'), ('Song3', 'RPQ', 'SSS')] map1 = pd.DataFrame.from_records(data, columns=cols) cols = ['song', 'album_code', 'song_code'] data = [('Song4', 'REA', 'EEE'), ('Song5', 'VEY', 'FFX'), ('Song6', 'LFM', 'TRE')] map2 = pd.DataFrame.from_records(data, columns=cols) merged_map1 = main_df.merge(map1, left_on='code', right_on='album_code') merged_map2 = main_df.merge(map2, left_on='code', right_on='song_code') merged_maps = merged_map1.append(merged_map2) map_all = ind_df.merge(merged_maps, left_index=True, right_on=['code'], how='left') print(map_all) Final result: value_num code value_letter song album_code song_code 0 1.0 CDX A Song1 CDX GIB 1 2.0 DEF B Song2 DEF FRE 2 3.0 RPQ C Song3 RPQ SSS 0 4.0 EEE D Song4 REA EEE 1 5.0 FFX E Song5 VEY FFX 2 NaN REM NaN NaN NaN NaN 2 7.0 TRE G Song6 LFM TRE
type: Answer
has comment: http://stackoverflow.com/comment/90083053

http://stackoverflow.com/q/51492897
favorite count: 0
duplicate of: http://stackoverflow.com/q/46878156
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/17071871
score: 2
answer count: 0
linked to: http://stackoverflow.com/q/17071871
downvote count: 0
linked to: http://stackoverflow.com/q/20109391
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/89954387
upvote count: 2
tagged with: pandas
has title: Python pandas. how to delete date rows by condition?
has body: i have a dataframe with dates as index, dates from 2013 year to 2018 year how can i delete all rows where year &lt; 2018? enter image description here

http://stackoverflow.com/q/51517016
has body: # coding=utf-8 import re f = open('/Users/.../example.txt') mensaje = f.read() mensaje = mensaje.replace("\n","") keywords_cap = ['SpA','SPA','LIMITADA','LTDA','S.A.'] keywords_cap = map(re.escape, keywords_cap) keywords_cap.sort(key=len, reverse=True) obj = re.compile(r'\s*([^:]*)(?&lt;!\w)(?:{})'.format('|'.join(keywords_cap))) print("COMPANY NAME: %s" % obj.findall(mensaje)) I have different files that contains : or ;, the company name, and one word defined in keywords_cap. The file contains: Nombre o razón social: "MJ FACILITIES SERVICES SpA nombre de fantasía MJ SpA." Now my output is: MJ FACILITIES SERVICES SpA nombre de fantasía and I only want MJ FACILITIES SERVICES SpA.
downvote count: 0
answer count: 1
tagged with: regex
favorite count: 0
type: UnansweredQuestion
tagged with: path
has answer: http://stackoverflow.com/a/51517783
tagged with: keyword
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90003446
score: 1
has title: Extract name in a text file between (: or , or ; ) and (keyword) with regex in python
type: Question
has comment: http://stackoverflow.com/comment/90003508

http://stackoverflow.com/q/51564345
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/51564403
has answer: http://stackoverflow.com/a/51564638
has answer: http://stackoverflow.com/a/51564403
tagged with: python
has answer: http://stackoverflow.com/a/51564382
accepted answer: http://stackoverflow.com/a/51564382
has comment: http://stackoverflow.com/comment/90095808
has title: apply function to array then append result to the array without loop in python
type: AnsweredQuestion
tagged with: reduce
type: Question
tagged with: numpy
tagged with: arrays
has body: I have an array a and a list b. I want to sum values in a indexed by values in b then append it to a. For example, a[[1,2]] = 3 + 4 = 7 then append 7 to a. import numpy as np a = np.array([1,3,4,5,6]) b = [[1,2], [3,4]] for positions in b: tmp = a[positions].sum() a = np.append(a, tmp) a array([ 1, 3, 4, 5, 6, 7, 11]) Could I use reduce instead of a loop?
score: 0
answer count: 3
upvote count: 1

http://stackoverflow.com/q/51581836
tagged with: sendgrid
upvote count: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52062569
has title: Bad Request when using Substitutions with the SendGrid API v3 via the Python API Wrapper
has answer: http://stackoverflow.com/a/53033650
downvote count: 0
score: 1
favorite count: 0
tagged with: sendgrid-api-v3
type: UnansweredQuestion
tagged with: python
tagged with: sendgrid-templates
has body: I created a nice template via the SendGrid UI and am encountering issues trying to send emails with it via the sendgrid python API wrapper (v5.4.1). I've got the template id for a template that has the following (truncated) text: Hello, {{name}}! Click the following link to verify your account: {{verification_url}}. However, when following the example in the documentation, I get a 400 Bad Request error whenever I include the personalizations. I am including the personalizations as follows: mail.personalizations[0].add_substitution(Substitution("{{name}}", "Example User")) In addition, mail.get() returns the following: { 'from': { 'email': 'test@school.edu' }, 'subject': 'Account Verification', 'personalizations': [ { 'to': [{'email': 'testemail@test.com'}], 'substitutions': { '{{name}}': 'Example User'} } ], 'template_id': '&lt;template_id_here&gt;' } Is there any way to debug what's going on? A 400 Bad Request unfortunately isn't all that helpful... It looks like these features are actually not yet supported: https://github.com/sendgrid/sendgrid-python/issues/591

http://stackoverflow.com/comment/90037691
type: QuestionComment
has text: In the first one, I am calling the function userInputs and passing arguments. In the second one I have defined the function userInputs.
comment on: http://stackoverflow.com/q/51533808
score: 0
type: Comment

http://stackoverflow.com/comment/89962072
comment on: http://stackoverflow.com/a/51489232
type: AnswerComment
has text: @rmahesh since the answer resolved your issue, kindly *accept* it; please do not "update" questions with new issues - open a new question instead!
type: Comment
score: 0

http://stackoverflow.com/comment/90087320
type: Comment
comment on: http://stackoverflow.com/q/51559975
type: QuestionComment
score: 2
has text: You should *seriously* consider learning Python 3, Python 2 will reach its official End Of Life some time in 2020. If you _really_ need to learn Python 2 syntax to work on old code, then I strongly advise you to learn Python 3 first.

http://stackoverflow.com/q/51634679
has comment: http://stackoverflow.com/comment/90233959
has title: Getting "TypeError: string indices must be integers" in python
has body: I tried imitating my code in simple steps on python prompt: &gt;&gt;&gt; path="D:/workspace/a/b\\c\\d.txt" &gt;&gt;&gt; path[0,18] But it gives me following error: TypeError: string indices must be integers I wanted to retrieve only directory as path. That is, I want to strip away the file name: D:/workspace/a/b\\c Why I am getting this error?
has answer: http://stackoverflow.com/a/51634796
linked to: http://stackoverflow.com/q/509211
score: 0
duplicate of: http://stackoverflow.com/q/17057544
answer count: 3
duplicate of: http://stackoverflow.com/q/509211
tagged with: python
has comment: http://stackoverflow.com/comment/90233649
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51634725
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90234104
type: Question
has answer: http://stackoverflow.com/a/51634900

http://stackoverflow.com/q/51637149
type: UnansweredQuestion
has body: File "C:\Users\Suhaas\Documents\ocr_local_image.py", line 8 print pytesseract.image_to_string(Image.open('test.jpg')) ^ SyntaxError: invalid syntax
type: Question
has comment: http://stackoverflow.com/comment/90239098
answer count: 1
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/90238741
tagged with: python
has comment: http://stackoverflow.com/comment/90238786
has title: How do I fix the syntax error for this?
tagged with: python-tesseract
has answer: http://stackoverflow.com/a/51637243

http://stackoverflow.com/q/51628463
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/51629934
has body: I have this YAML file : pb: {EF:{16, 19}, EH:{16, 19}} when I apply my flattendict Python function, I get this {('pb', 'EF', 16): None, ('pb', 'EF', 19): None, ('pb', 'EH', 16): None, ('pb', 'EH', 19): None} I search the syntax of my YAML file as below, to get the same result (I want factoring my YAML node data) pb: {EF, EH}, {16, 19}} Have you an idea? Here my python flattendict function #!/usr/bin/env python #encoding: UTF-8 import codecs import sys import yaml import pprint import collections from collections import Mapping from itertools import chain from operator import add _FLAG_FIRST = object() def flattenDict(d, join=add, lift=lambda x:x): results = [] def visit(subdict, results, partialKey): for k,v in subdict.items(): newKey = lift(k) if partialKey==_FLAG_FIRST else join(partialKey,lift(k)) if isinstance(v,Mapping): visit(v, results, newKey) else: results.append((newKey,v)) visit(d, results, _FLAG_FIRST) return results testdata = yaml.safe_load(open('data.yaml', 'r')) from pprint import pprint as pp result = flattenDict(testdata, lift=lambda x:(x,)) pp(dict(result))
tagged with: pyyaml
type: Question
downvote count: 0
tagged with: yaml
answer count: 1
has title: factoring mapping key in a yaml file
tagged with: flatten
favorite count: 0
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/a/51521483
answers question: http://stackoverflow.com/q/51521412
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51521412
type: Answer
has body: &gt;&gt;&gt; [x for i in range(0, len(l), 5) for x in (l[i:i+4], l[i+4])] [['119', '222', '219', '293'], '4', ['179', '124', '500', '235'], '7']
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/90012353
upvote count: 6

http://stackoverflow.com/comment/113938461
score: 2
comment on: http://stackoverflow.com/a/51643134
has text: The authorized scopes could be different from what was requested. Functionally there could be a problem if _fewer_ scopes are granted than what were requested. Security-wise you don't necessarily want _more_ scopes granted but that's exactly what `include_granted_scopes=True` does in Google's library: https://developers.google.com/identity/protocols/oauth2/web-server#incrementalAuth
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51494675
tagged with: categories
possible better answer: http://stackoverflow.com/a/51494851
score: 4
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/89957661
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51494851
has body: I want to efficiently categorize the elements of a given list L1. This list can be arbitrary long, so I am looking for an efficient way to do the following. The list L1 contains several elements [e_1,...,e_N] that can be compared with a generic function called areTheSame(e1,e2). If this function returns True, it means that both elements belong to the same category. At the end, I want to have another list L2, which in turn contains different lists [LC_1, ..., LC_M]. Each LC list contains all the elements from the same category.
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/89957691
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/51494864
accepted answer: http://stackoverflow.com/a/51494864
has title: Categorize elements of a list in python
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/90024703
comment on: http://stackoverflow.com/a/51527912
type: Comment
has text: Hey thanks! Lots of great things that I didn't know here! I tried implementing your code but am running into an error with the group line: AttributeError: 'list' object has no attribute 'group'
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90210612
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51622601
has text: numbers are just marks, its should help you to see what parts of matrix I want to extract
score: 0

http://stackoverflow.com/comment/90060074
comment on: http://stackoverflow.com/a/51524508
score: 1
has text: Your example is still not clear, because the only tokens shared between "Samsung galaxy 4 gb ram, black, 64 gb internal memory" and "Nokia 6T 3 gb ram, rose gold" are "gb ram" – and it seems almost every product will have those words. So if these are, in fact, similar, it requires other knowledge you're not supplying to the algorithm. It knows nothing but what you tell it. Now, if they were both mentioned in the same review, or appeared in the same list-of-products browsed/bought by the same person, that'd be a data-driven hint of similarity.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51613969
type: Question
has comment: http://stackoverflow.com/comment/90197104
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90199202
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90461699
tagged with: python-3.x
has title: when opeing spyder getting No module named 'PyQt4'
has comment: http://stackoverflow.com/comment/90197635
has comment: http://stackoverflow.com/comment/90198333
type: UnansweredQuestion
tagged with: spyder
has comment: http://stackoverflow.com/comment/90199341
tagged with: python
has body: When i am opening spyder on ubuntu 16.04 os i am getting following error NOTE: The following error appeared when setting your Matplotlib backend Traceback (most recent call last): File "/home/nd/anaconda3/lib/python3.6/site-packages/spyder_kernels/console/kernel.py", line 471, in _set_mpl_backend get_ipython().run_line_magic(magic, backend) File "/home/nd/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2131, in run_line_magic result = fn(*args,**kwargs) File "&lt;decorator-gen-107&gt;", line 2, in matplotlib File "/home/nd/anaconda3/lib/python3.6/site-packages/IPython/core/magic.py", line 187, in &lt;lambda&gt; call = lambda f, *a, **k: f(*a, **k) File "/home/nd/anaconda3/lib/python3.6/site-packages/IPython/core/magics/pylab.py", line 99, in matplotlib gui, backend = self.shell.enable_matplotlib(args.gui) File "/home/nd/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3049, in enable_matplotlib pt.activate_matplotlib(backend) File "/home/nd/anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py", line 310, in activate_matplotlib import matplotlib.pyplot File "/home/nd/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py", line 115, in &lt;module&gt; _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/home/nd/anaconda3/lib/python3.6/site-packages/matplotlib/backends/__init__.py", line 62, in pylab_setup [backend_name], 0) File "/home/nd/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_qt4agg.py", line 9, in &lt;module&gt; from .backend_qt5agg import ( File "/home/nd/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_qt5agg.py", line 15, in &lt;module&gt; from .backend_qt5 import ( File "/home/nd/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_qt5.py", line 19, in &lt;module&gt; import matplotlib.backends.qt_editor.figureoptions as figureoptions File "/home/nd/anaconda3/lib/python3.6/site-packages/matplotlib/backe…
has comment: http://stackoverflow.com/comment/90196444
has comment: http://stackoverflow.com/comment/90193854
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90441533

http://stackoverflow.com/q/51560750
tagged with: ipython
has body: %precision 2 x = 2/3 print(x) this prints 0.6666666666666666 instead of 0.67 any idea why it does not work? I'm using ipython notebook Thanks
type: Question
downvote count: 0
has title: python %precision magic function does not work for print()
upvote count: 1
answer count: 1
tagged with: jupyter-notebook
favorite count: 0
has answer: http://stackoverflow.com/a/51560816
accepted answer: http://stackoverflow.com/a/51560816
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90088533

http://stackoverflow.com/comment/90244344
has text: Now I want to feed .txt file to BeautifulSoup() as an input, but I don't know how to do it. I'm not sure it's possible right away.
comment on: http://stackoverflow.com/a/51639793
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/62841333
score: 3
upvote count: 5
answers question: http://stackoverflow.com/q/51550617
has comment: http://stackoverflow.com/comment/129470986
type: Answer
has body: import sys sys.setrecursionlimit(10**8) def ackermann(m,n): if m == 0: return (n + 1) elif n == 0: return ackermann(m - 1, 1) else: return ackermann(m - 1, ackermann(m, n - 1)) for x in range(5): for y in range(5): print(ackermann(x, y)) Python's default recursion limit is 10**4. Changable with setrecursionlimit() so you can get a 'Stack overflow' error because Ackermann function's output is too long.
downvote count: 2

http://stackoverflow.com/a/51509717
answers question: http://stackoverflow.com/q/51509128
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/51509128
has body: I solved the problem by going to Control Panel -&gt; Uninstall A Program, right clicking on "Python 2.7.15", clicking "change", and pressing "repair". No clue why I didn't try that first.
score: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51616995
has comment: http://stackoverflow.com/comment/90201599
has body: I have an old file written using python2, which contains things like 148191387849281587952L. When I try to read it (using ast.literal_eval) in python3, I, naturally, get SyntaxError: invalid syntax. Is there anything I could do to read the file into python3? PS. The only solutions I see at this time require modifying the file: Convert to JSON: read the file into python2, write it using json, then read into python3 using json. Remove the offending L using sed -i 's/([0-9]+)L/\1/g'. Convert the file using 2to3 (suggested by @user3080953). Is there anything better?
score: 0
has comment: http://stackoverflow.com/comment/90201352
answer count: 1
has comment: http://stackoverflow.com/comment/90199862
has answer: http://stackoverflow.com/a/51618845
tagged with: python-3.x
linked to: http://stackoverflow.com/q/45681702
has comment: http://stackoverflow.com/comment/90199796
has comment: http://stackoverflow.com/comment/90201258
has comment: http://stackoverflow.com/comment/90201532
tagged with: python
has comment: http://stackoverflow.com/comment/90200063
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90199934
has comment: http://stackoverflow.com/comment/90199766
accepted answer: http://stackoverflow.com/a/51618845
type: Question
has comment: http://stackoverflow.com/comment/90199769
has title: How do I read python2 long integer syntax into python3?
has comment: http://stackoverflow.com/comment/90200133

http://stackoverflow.com/a/51633489
answers question: http://stackoverflow.com/q/51625529
has comment: http://stackoverflow.com/comment/90291012
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/95807516
downvote count: 0
has body: To use either initializable or reinitializable iterators, you must create a class that inherits from tf.train.SessionRunHook. This class then have access to the session used by the tf.estimator functions. Here is quick example that you can adapt to your needs : class IteratorInitializerHook(tf.train.SessionRunHook): def __init__(self): super(IteratorInitializerHook, self).__init__() self.iterator_initializer_func = None # Will be set in the input_fn def after_create_session(self, session, coord): self.iterator_initializer_func(session) def get_inputs(X, y): iterator_initializer_hook = IteratorInitializerHook() def input_fn(): X_pl = tf.placeholder(X.dtype, X.shape) y_pl = tf.placeholder(y.dtype, y.shape) dataset = tf.data.Dataset.from_tensor_slices((X_pl, y_pl)) dataset = ... ... iterator = dataset.make_initializable_iterator() next_example, next_label = iterator.get_next() iterator_initializer_hook.iterator_initializer_func = lambda sess: sess.run(iterator.initializer, feed_dict={X_pl: X, y_pl: y}) return next_example, next_label return input_fn, iterator_initializer_hook ... train_input_fn, train_iterator_initializer_hook = get_inputs(X_train, y_train) test_input_fn, test_iterator_initializer_hook = get_inputs(X_test, y_test) ... estimator.train(input_fn=train_input_fn, hooks=[train_iterator_initializer_hook]) estimator.evaluate(input_fn=test_input_fn, hooks=[test_iterator_initializer_hook]) This is a modified version from a code I found in a blogpost by Sebastian Pölsterl. Have a look under the "Feeding data to an Estimator via the Dataset API" section.
type: Answer
has comment: http://stackoverflow.com/comment/102819484

http://stackoverflow.com/q/51597928
tagged with: alexa-skills-kit
has comment: http://stackoverflow.com/comment/90165800
has comment: http://stackoverflow.com/comment/90168582
has comment: http://stackoverflow.com/comment/90168649
answer count: 1
has title: Attribute Error when trying to access device ID Alexa
has answer: http://stackoverflow.com/a/51658765
type: UnansweredQuestion
tagged with: flask-ask
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/90165598
type: Question
has body: I'm currently building an Alexa skill which will eventually need the users Zip Code. I'm going off of this code: https://data-dive.com/alexa-get-device-location-from-custom-skill The problem I'm having is this line: 'TOKEN = context.System.user.permissions.consentToken' and the error: 'AttributeError: 'NoneType' object has no attribute 'consentToken'' I have already requested permissions through the Alexa dev console, but my guess is that there isn't something going right when I'm testing. I tried testing through the Alexa app on my phone but came to the same error. Any steps in the right direction would be great!

http://stackoverflow.com/comment/90162157
type: Comment
has text: 'request': {'type': 'IntentRequest', 'requestId': 'amzn1.echo-api.request.omitted', 'timestamp': '2018-07-30T15:56:15Z', 'locale': 'en-US', 'intent': {'name': 'ScheduleCall', 'confirmationStatus': 'NONE', 'slots': {omitted}}}, 'dialogState': 'STARTED'}}
comment on: http://stackoverflow.com/a/51567868
score: 0
type: AnswerComment

http://stackoverflow.com/q/51523765
tagged with: opencv
linked to: http://stackoverflow.com/q/46441893
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51524749
linked to: http://stackoverflow.com/q/48303309
type: Question
answer count: 1
downvote count: 0
has title: How to use OpenCV ConnectedComponents to get the images
accepted answer: http://stackoverflow.com/a/51524749
favorite count: 0
has body: How to use Python OpenCV ConnectedComponents function to obtain the images? From searching some past question, I have only been able to find how to shade the connected objects in different colors (Which I tested and it worked, but I have no idea how the labels work) Reference from these previously answered questions: Stackoverflow question 48303309 and Stackoverflow question 46441893 Using this code, I can get the shaded output import cv2 import numpy as np img = cv2.imread('eGaIy.jpg', 0) img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1] # ensure binary ret, labels = cv2.connectedComponents(img) # Map component labels to hue val label_hue = np.uint8(179*labels/np.max(labels)) blank_ch = 255*np.ones_like(label_hue) labeled_img = cv2.merge([label_hue, blank_ch, blank_ch]) # cvt to BGR for display labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR) # set bg label to black labeled_img[label_hue==0] = 0 cv2.imshow('labeled.png', labeled_img) cv2.waitKey() Is there any way I can get the connected objects out from the image? So output would be multiple images from the original image
tagged with: python
score: 13
upvote count: 13

http://stackoverflow.com/a/51534418
has comment: http://stackoverflow.com/comment/90037435
has comment: http://stackoverflow.com/comment/90036719
type: Answer
has comment: http://stackoverflow.com/comment/90036717
has comment: http://stackoverflow.com/comment/90036772
upvote count: 7
has body: Here is the pattern, first there is some number so we use [0-9]+ followed by string and special characters like &amp; - &gt;, therefore we can use [a-zA-Z \-&amp;&gt;]+: &gt;&gt;&gt; str_ = "123 - Footwear, 5678 - Apparel, Accessories &amp; Luxury Goods, 9876 - Leisure Products" &gt;&gt;&gt; re.findall(r'(?is)([0-9]+[a-zA-Z \-&amp;&gt;,]+)', str_) ['123 - Footwear, ', '5678 - Apparel, Accessories &amp; Luxury Goods, ', '9876 - Leisure Products'] Another string you mentioned in OP &gt;&gt;&gt; str_ = "321 - Apparel &amp; Accessories, 4321 - Apparel &amp; Accessories &gt; Handbags, Wallets &amp; Cases, 187 - Apparel &amp; Accessories &gt; Shoes" &gt;&gt;&gt; re.findall(r'(?is)([0-9]+[a-zA-Z \-&amp;&gt;,]+)', str_) ['321 - Apparel &amp; Accessories, ', '4321 - Apparel &amp; Accessories &gt; Handbags, Wallets &amp; Cases, ', '187 - Apparel &amp; Accessories &gt; Shoes']
score: 7
answers question: http://stackoverflow.com/q/51534312
downvote count: 0

http://stackoverflow.com/q/51514021
type: Question
tagged with: python
score: -2
has title: How to estimate the required time and computational needs before the actual training of a ML model?
tagged with: cpu
downvote count: 2
tagged with: machine-learning
has answer: http://stackoverflow.com/a/51515468
answer count: 1
has body: Is there any way to estimate the required computational memory and time before the actual training of a machine learning model? I am using a laptop without GPU and don't have any AWS credit left.. how not to overload my CPU? thanks!
type: UnansweredQuestion
tagged with: deep-learning
upvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90240268
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51637089
has text: Are you trying to perform a matrix multiplication in `mm*np.matrix(evecs[:,x])`? If yes, then use `np.dot(mm, evecs[:,x])`.

http://stackoverflow.com/q/51549860
has answer: http://stackoverflow.com/a/51549899
tagged with: python-3.x
type: UnansweredQuestion
has title: Python using def function to create defferent variables
linked to: http://stackoverflow.com/q/1373164
tagged with: python
has comment: http://stackoverflow.com/comment/90067204
type: Question
tagged with: function
has body: I'm new to python and just want to ask if it is possible to use def function to create new variables. Here is my code, trying to build a function that i can input the variable name and data, it will automaticed output the different list. But it seems not working: def Length5_list(list_name, a, b, c, d, e): list_name = list() list_name = [a, b, c, d, e] list_name1 = 'first_list' list_name2 = 'second_list' A = 1 B = 2 C = 3 D = 4 E = 5 Length5_list(list_name1, A, B, C, D, E) Length5_list(list_name2, E, D, C, B, A) print(list_name1, list_name2) Also wondering if there is any other way to achieve it? Thank you guys soooo much!
score: 0
answer count: 1

http://stackoverflow.com/a/51558517
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51558469
has body: IIUC, use str.format and dict comprehension num_rows = 10 num_cols = 15 df = pd.DataFrame({ 'c{}'.format(n): [randint(0, 9) for x in range(num_rows)] for n in range(num_cols)}, index=[x+1 for x in range(num_rows)] , ) c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 1 1 6 2 1 3 1 8 8 2 0 2 2 6 2 2 5 7 4 1 6 2 3 1 2 6 8 7 5 5 7 2 2 4 5 5 3 3 4 7 8 1 8 6 5 7 2 8 6 5 6 2 0 0 4 6 8 2 4 4 6 3 0 1 0 2 7 5 6 8 5 1 0 4 8 4 7 8 1 5 4 5 2 4 4 6 2 7 9 5 7 7 8 5 0 2 7 3 2 10 4 8 5 3 3 7 5 1 5 1
upvote count: 1

http://stackoverflow.com/comment/90014358
has text: I have many text fields in my QML and they are set/updated through Python backend which talks to hardware
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51521856

http://stackoverflow.com/comment/90037262
comment on: http://stackoverflow.com/q/51509698
score: 1
has text: @stijn OK! Thanks for your kind suggestion. :) I will edit my question and post my own answer.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51514840
answer count: 0
type: UnansweredQuestion
has title: Plotting a timeline with different colors in the same line with Python (Gantt-Chart?)
linked to: http://stackoverflow.com/q/17219413
tagged with: python
tagged with: plot
has comment: http://stackoverflow.com/comment/89998398
tagged with: plotly
has comment: http://stackoverflow.com/comment/89998045
has comment: http://stackoverflow.com/comment/90018329
type: Question
has body: I have a question concerning a plot I'd like to make. I have data of leaders (dictators, presidents, chancellors...) from all over the world and the date when they got to power and when they lost it. Additionally I have information if the regime was a dictatorship, democracy or something else... My plan is to have a plot with all countries in the data and different bars for their leaders. Depending on the regime category I'd like to have different colors. I have 6 different regime categories. I tried to find something, found plot.ly but no luck with that. A small text example, I hope you can imagine what I'm planning to do (not reperesentative!). "-" = democracy "~" = monarchy "x" = dictatorship USA: ----|---------|----------|------|--------|-----------|----- UK: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~|~~~~~~|-------|---|-----|----- GER: --------|xxxxxxxxxx|---------|---------|--------| My data starts in 1945, but not all countries have existed by then, so some bars will start in 1970. I'd say it's like a stacked horizontal gantt-chart. But after trying with plotly without a result I'm curious for other solutions. Thanks for your help! edit: Maybe I should add: I imported the data as pd.DataFrame and tried that for plot.ly as well. edit 2: I managed to get a result, it's a bit ugly, the text on the left is not fully visible, the "legend" hides behind a scroll bar and has no names, just the keys assigned in the data. I tried to use a dict for the layout, didn't work. I saw that in the documentation, but it doesn't work, what do I do wrong, would be nicer for adaption. The current version: https://plot.ly/~derhannes/10.embed # The actual plotting fig = ff.create_gantt(df_dd_gantt_final, colors=colors, index_col='Resource', show_colorbar=False, height=2400, width=1200, title='Regimes in history worldwide', showgrid_x=True, group_tasks=True) py.iplot(fig, filename='regimes', world_readable=True)
score: 0
tagged with: pandas

http://stackoverflow.com/comment/106325075
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51528626
type: Comment
has text: after wasting half a day, I finally found this solution... thank you!

http://stackoverflow.com/q/51509970
has answer: http://stackoverflow.com/a/51510140
has answer: http://stackoverflow.com/a/73748016
downvote count: 0
possible better answer: http://stackoverflow.com/a/68056558
tagged with: flask
has comment: http://stackoverflow.com/comment/89989131
has answer: http://stackoverflow.com/a/68056558
favorite count: 0
tagged with: download
has body: I have a post fetch request coming from my React client to my remote Flask server like so: fetch(FETCH_URL, { method: 'POST', body: data, headers: { 'Content-Type': 'application/json' } }).then((response) =&gt; { var a = response.body.getReader(); a.read().then(({ done, value }) =&gt; { console.log(new TextDecoder("utf-8").decode(value)); } ); }); response.body comes in the form of a ReadableStream object so I was able to extract a Uint8array which I then decoded to be the contents of the txt file I sent back from my flask server as shown in the code above. At this point I'm lost, what I'm trying to do is send a request to my remote server with a filename (in the requests' data), and download that file on my computer. As shown above, I tried a fetch request to my remote server, then in flask, my server finds and opens the file which is stored on the server itself, and sends back the file. filename = request.get_json()['filename'] f = open(filename) return f The problem now is that from what I've read, I can't create a file on my computer just with react. Even so, I don't know if this would work with all types of files or just txt files. Does anyone have any guidance to get to my end goal of downloading a file from a remote flask server.
tagged with: python
linked to: http://stackoverflow.com/q/51525964
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51510140
score: 1
linked to: http://stackoverflow.com/q/3665115
upvote count: 1
type: Question
tagged with: javascript
has comment: http://stackoverflow.com/comment/89989152
has title: Download file in react client from flask remote server
tagged with: reactjs
answer count: 3

http://stackoverflow.com/q/51548888
upvote count: 2
has comment: http://stackoverflow.com/comment/90089825
type: Question
has comment: http://stackoverflow.com/comment/90089595
possible better answer: http://stackoverflow.com/a/51548953
has answer: http://stackoverflow.com/a/51603072
answer count: 2
has answer: http://stackoverflow.com/a/51548953
downvote count: 0
accepted answer: http://stackoverflow.com/a/51603072
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90065921
has title: How to remove/prevent duplicate lines in a text file
tagged with: python
has comment: http://stackoverflow.com/comment/90065985
type: AnsweredQuestion
score: 2
has body: I've been wracking my braining with this all day trying so many things on stack overflow and nothing is working, so apologies if this is something really simple and I'm missing it. My situation is that my Python bot is grabbing a post ID from a post and putting it into a text file. subreddit = reddit.subreddit('pythonforengineers') # limiting the selection to the top 5 in hot for submission in subreddit.new(limit=20): # re.findall is performing the filtering = removing all text but the found keys a = re.findall(steamKey15, submission.selftext, re.IGNORECASE) b = re.findall(steamKey25, submission.selftext, re.IGNORECASE) c = re.findall(steamKey17, submission.selftext, re.IGNORECASE) readPostIDFile() while submission.id not in steamKeyPostID: if a: #print(a) savePostID() saveSteamKey() removeDups() if b: #print(b) savePostID() saveSteamKey() removeDups() if c: #print(c) savePostID() saveSteamKey() removeDups() break This is my looping logic. The 3 variables are the steamKey15/25/17, so I'm testing it on a post with all 3 formats and naturally its returning all 3, but its also writing the post id 3x to my text file. Here is the logic for the post id save: def savePostID(): #print(submission.selftext) #print(submission.id) # adds the id to the text file steamKeyPostID.append(submission.id) with open('steamKeyPostID.txt', 'a') as f: for post_id in steamKeyPostID: f.write(submission.id + '\n') if submission.id not in 'steamKeyPostID.txt': print('Beep. Boop. Bot saving the keys of: ' + '"' + submission.title + '"'+ ' to ---&gt; steamKeys.txt') break else: print('No keys were found!') break My goal is to either prevent multiple post IDs from reaching the text file, OR to perform a filtering on the text file to remove the duplicates(this would require writing back to the same text file). I'm not sure which would be easier, but I've been trying both all day and failing. I have tried using OrderedDict and set() codes of varying types. I have also tried modifying my for/if loop…

http://stackoverflow.com/a/51544898
answers question: http://stackoverflow.com/q/51536391
downvote count: 0
type: Answer
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/90076338
has body: You have to properly specify function's restype (and argtypes) as explained in [Python.Docs]: ctypes - A foreign function library for Python. test00.py: import sys import ctypes as ct LIB_NAME = "./libtest.so" def main(): libtest_lib = ct.CDLL(LIB_NAME) get_str_func = libtest_lib.get_str get_str_func.atgtypes = [] get_str_func.restype = ct.c_char_p s = get_str_func() print(s) if __name__ == "__main__": print("Python {:s} on {:s}\n".format(sys.version, sys.platform)) main() Output: [cfati@cfati-ubtu16x64-0:~/Work/Dev/StackOverflow/q051536391]> python3 ./test00.py Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux b'constant string'

http://stackoverflow.com/comment/90206286
type: Comment
comment on: http://stackoverflow.com/a/51619934
score: 0
type: AnswerComment
has text: Thank you! I have created a Venn diagram to illustrate the idea. Please correct me if I am wrong.

http://stackoverflow.com/q/51602800
has comment: http://stackoverflow.com/comment/90172702
tagged with: pandas
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90172742
type: UnansweredQuestion
downvote count: 2
tagged with: python
has body: I have two data frames. The first df-df1 and the second one is The second df-df2 import pandas as pd d = {'0': [2446, 2446,2445], '1': [2447, 2447, 2446],'2':[3537,177,3535],'3':[177,17,2903]} df1 = pd.DataFrame(data=d) d={'PART_NO': ['KH661-10059','KH661-10057', 'KH661-10058'], 'PART_NO_ENCODED': [2447, 2446, 2445]} df2 = pd.DataFrame(data=d) I want to get the part number corresponding to the encoded part which I can get like this : df2[df2['PART_NO_ENCODED'].isin([789,1023,569])] However my question is I do not want to hardcode the values I want to pick up each column from the df1 and get the corresponding encoded parts from df2. How can I do this?
has answer: http://stackoverflow.com/a/51603410
has title: Get a row value from a data frame corresponding to another column in a second data frame
type: Question
score: -2
tagged with: dataframe

http://stackoverflow.com/a/55796971
has comment: http://stackoverflow.com/comment/112601282
has comment: http://stackoverflow.com/comment/130055098
has comment: http://stackoverflow.com/comment/137513369
has body: The approach below deals with this problem while using pure python dataclasses and without much boilerplate code. The ugly: dataclasses.InitVar[bool] serves as a pseudo-field just to help us do initialization and will be lost once the instance is created. While _ugly: bool = field(init=False) is an instance member which will not be initialized by __init__ method but can be alternatively initialized using __post_init__ method (you can find more here.). from dataclasses import dataclass, field, InitVar @dataclass class Parent: name: str age: int ugly: InitVar[bool] _ugly: bool = field(init=False) def __post_init__(self, ugly: bool): self._ugly = ugly def print_name(self): print(self.name) def print_age(self): print(self.age) def print_id(self): print(f'The Name is {self.name} and {self.name} is {self.age} year old') @dataclass class Child(Parent): school: str jack = Parent('jack snr', 32, ugly=True) jack_son = Child('jack jnr', 12, school='havard', ugly=True) jack.print_id() jack_son.print_id() Note that this makes field ugly mandatory to make it optional you can define a class method on the Parent that includes ugly as an optional parameter: from dataclasses import dataclass, field, InitVar @dataclass class Parent: name: str age: int ugly: InitVar[bool] _ugly: bool = field(init=False) def __post_init__(self, ugly: bool): self._ugly = ugly @classmethod def create(cls, ugly=True, **kwargs): return cls(ugly=ugly, **kwargs) def print_name(self): print(self.name) def print_age(self): print(self.age) def print_id(self): print(f'The Name is {self.name} and {self.name} is {self.age} year old') @dataclass class Child(Parent): school: str jack = Parent.create(name='jack snr', age=32, ugly=False) jack_son = Child.create(name='jack jnr', age=12, school='harvard') jack.print_id() jack_son.print_id() Now you can use the create(...) class method as a factory method for creating Parent/Child classes with a default value for ugly. Note you must use named parameters for this approach …
type: Answer
answers question: http://stackoverflow.com/q/51575931
upvote count: 16
downvote count: 1
score: 15

http://stackoverflow.com/comment/90066590
type: AnswerComment
score: 0
type: Comment
has text: list_a_more_than_hundred = df[(df.a>100) & (df.b<57)]
comment on: http://stackoverflow.com/a/51549374

http://stackoverflow.com/a/51601946
upvote count: 4
has comment: http://stackoverflow.com/comment/90183372
has comment: http://stackoverflow.com/comment/90184747
score: 4
has comment: http://stackoverflow.com/comment/90184533
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51601508
has comment: http://stackoverflow.com/comment/90188438
has comment: http://stackoverflow.com/comment/90183755
has comment: http://stackoverflow.com/comment/90183674
type: Answer
accepted answer of: http://stackoverflow.com/q/51601508
has comment: http://stackoverflow.com/comment/90183855
has comment: http://stackoverflow.com/comment/90176545
has body: From the django-webpack-loader tutorial: Now that we’ve handed off the build process webpack, only thing we need on the django side is to know which bundle to include in our html pages. This is where django-webpack-loader comes in. It’ll also raise exceptions when webpack fails to build a bundle and will show some useful information to help debug the problem. During development, webpack loader will also block requests while a new bundle is being generated so that only the latest bundles are loaded. This is the core functionality of that loader. It tells django which are the current bundles to be served. It does not server side render your react app nor does it replace an API that the app needs to consume. When developing a react app you usually use some kind of bundler that transpiles your javascript code to es5, uglyfies and minifies it. So every time your code changes a new bundle will be created containing your new javascript. A lot of people are using webpack for this task. Now when a request arrives in django it needs to serve the basic html along with the css and js to be loaded by the client that contains the react app. So django needs to know the path to the files to link. But the path may constantly change when webpack rebuilds them. django-webpack-loader helps you to keep track of these changes and includes the correct paths to the current bundles for your react app to be fetched. It is not a replacement for an API. Its sole task is to resolve the correct paths to your react app files. EDIT So the primary purpose of django-webpack-loader is to ensure that the paths to the most recent build are resolved correctly and in turn can be served. What is the reason these paths will change ? Weppack appends a random hash to a new bundle like bundle.4j2a032fg.js. This way django can tell the client to cache the script so that it does not have to be re-request it every time. The client will only request a new bundle if the url/path changed. But this also requires tha…
has comment: http://stackoverflow.com/comment/90184202

http://stackoverflow.com/comment/90206298
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51620378
has text: `newList = [ "{} {}".format(yourPath,x) for x in List]`

http://stackoverflow.com/comment/90287725
type: AnswerComment
score: 0
type: Comment
has text: What would I need to put into the code to make it find that class instead of going for the xpath?
comment on: http://stackoverflow.com/a/51637783

http://stackoverflow.com/comment/90091294
has text: It looks like `Shortener('Google',api_key = apiKey)` is expecting a string as `api_key`, but you appear to be passing the contents of a png file? What's going on there?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51561899

http://stackoverflow.com/a/51579124
accepted answer of: http://stackoverflow.com/q/51577887
answers question: http://stackoverflow.com/q/51577887
score: 0
type: AcceptedAnswer
type: Answer
has body: Alright. Figured it out. Comments were enabled for the site but they default to closed when the API posts them. post.comment_status = 'open' Set the comments as open when they were posted and it starts working.

http://stackoverflow.com/comment/119142008
comment on: http://stackoverflow.com/a/67366481
score: 0
has text: Sure thing, It's a valuable resource so I figured I wouldn't be the only one still interested. I actually got hit with a division by zero error at the start of the analyses but the cleaned tables in feather format were produced so I didn't feel the need to continue.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51541377
has comment: http://stackoverflow.com/comment/90052823
type: UnansweredQuestion
has body: The code is easy, but it caused the kernel to die, and the error is mentioned in the second image. I tried my best to figure it out, but did not succeed. If you have a suggestion or the solution, please tell me. Thank you very much. import pandas as pd import numpy as np ser = pd.Series(np.random.randn(1000)) ser.plot(kind='kde') Kernel died, restarting /home/flowqer/anaconda3/lib/python3.5/site-packages/traitlets/config/configurable.py:84: UserWarning: Config option `use_jedi` not recognized by `IPCompleter`. self.config = config
tagged with: python
has comment: http://stackoverflow.com/comment/90051578
tagged with: anaconda
type: Question
has title: can't use plot(kind='kde') in spyder
score: 0
tagged with: pandas
tagged with: spyder
answer count: 0

http://stackoverflow.com/q/51525435
has answer: http://stackoverflow.com/a/51525463
tagged with: pypi
upvote count: 30
type: Question
has body: I'm having trouble reaching a nexus server that we're using to store custom python packages. I've been told to change the settings in both my ~/.pypirc file and the ~/.pip/pip.conf file. What's the difference between those two files in how they're used? It seems like the pip install -r requirements.txt command refers to the pip.conf file, and then the fields within the pip.conf file requires looking up the pypirc file? Example pip.conf file: [global] index = https://user:password@someurl.com/somerepo/pypi-group/pypi index-url = index = https://user:password@someurl.com/somerepo/pypi-group/simple Example pypirc file: [distutils] index-servers = pypi nexus [pypi] repository: https://pypi.org/pypi username: abc password: def [nexus] repository: https://someurl.com/somerepo/pypi-internal username: someuser password: somepassword Also, what's the difference between index and index-url in the pip.conf file?
downvote count: 1
answer count: 1
favorite count: 0
tagged with: nexus
tagged with: python
accepted answer: http://stackoverflow.com/a/51525463
type: AnsweredQuestion
has title: What's the difference between Python pip's pip.conf and pypirc file?
score: 29
tagged with: pip

http://stackoverflow.com/q/51614419
has title: HMAC Encoding in R vs Python
upvote count: 1
type: Question
downvote count: 0
tagged with: hmac
accepted answer: http://stackoverflow.com/a/51615297
tagged with: http://stackoverflow.com/tag/r
answer count: 1
favorite count: 0
tagged with: python
has body: I am trying to create a token for an API call in R. I have example code and output in Python, but I am unable to replicate in R. I know little to nothing about encoding, decoding, etc. Hoping someone can shed some light on what I can do to make these outputs match. Here is a toy example. R Code: library(RCurl) library(digest) api_key = "abcdefghijklmnopqrstuvwxyz123456789==" decoded_api_key = base64Decode(api_key) hmac_binary = hmac(decoded_api_key, "MySpecialString", "sha512") hmac_encoded = base64Encode(digest(hmac_binary)) print(as.character(hmac_encoded)) # ZmZjZDBlMjkyNzg3NDNmYWM1ZDcyNjVkNmY4ZmM1OGQ= Python: import hmac import hashlib import base64 api_key = "abcdefghijklmnopqrstuvwxyz123456789==" decoded_api_key = base64.b64decode(api_key) hmac_binary = hmac.new(decoded_api_key, "MySpecialString", hashlib.sha512) hmac_encoded = base64.b64encode(hmac_binary.digest()) print(hmac_encoded) # MduxNfXVkwcOtCpBWJEl96S43boYVYTtHb4waR21ARCMo6iokKuxbwEJMTkuytbrCOxvBqKCYiaZiV/AyHTEcw== The answers I obtain are given at the end of the code blocks. Clearly they don't match. I'd like someone to help me change my R code to match the Python output. Thanks in advance.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51615297
score: 1

chemistry
tag name: chemistry
type: Tag
tags question: http://stackoverflow.com/q/51522103

http://stackoverflow.com/q/51597997
answer count: 2
upvote count: 0
accepted answer: http://stackoverflow.com/a/51598062
has comment: http://stackoverflow.com/comment/90162053
favorite count: 0
has body: I have just upgraded my python from 2 to 3 and start getting following error. I have checked indent and spaces also but no luck CODE def _download_track(self, song_url, track_name, dir_name,metadata): if '.mp4' in song_url: track_name = track_name + '.m4a' else: track_name = track_name + '.mp3' file_path = dir_name.replace(".","_") + '/' + track_name print(('Downloading to', file_path)) if os.path.isfile(file_path): return #print metadata #response = self._get_url_contents(song_url) #with open(file_path,'wb') as f: #f.write(response.content) r = requests.get(song_url, stream=True, verify=False) with open(file_path, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: f.write(chunk) f.flush() if '.m4a' in track_name: self._update_metadata_mp4(file_path,metadata) else : self._update_metadata_mp3(file_path,metadata) ERROR File "a.py", line 60 return ^ SyntaxError: 'return' outside function
possible better answer: http://stackoverflow.com/a/51598085
has answer: http://stackoverflow.com/a/51598085
has title: Python SyntaxError: 'return' outside function
tagged with: python
has comment: http://stackoverflow.com/comment/90162014
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90162097
score: -5
has answer: http://stackoverflow.com/a/51598062
type: Question
downvote count: 5

http://stackoverflow.com/a/51622519
upvote count: 2
has body: Well. Tarantool does not have a Django plugin. That means you have to introduce it first. By the way, tarantool has python 2.71 and python 3.x1 libraries, so it may be useful for integration. How it could be implemented? You have to use taranool's python library and also MySQL's python library for creating some Django / Python plugin. Also. About MySQL replication. Tarantool has this feature, you can get codes from GH repo[2]. I'm not sure that Django's sample could be found. Afterword. It's the pretty big task :) 1 https://github.com/tarantool/tarantool-python [2] https://github.com/tarantool/mysql-tarantool-replication UPD: February 2021: The Django-Tarantool Database Backend was introduced as django-tarantool PyPi package and can be used for Django 1.10-3.1 versions. pip install django-tarantool Feel free to contribute to the package https://github.com/artembo/django-tarantool
answers question: http://stackoverflow.com/q/51541762
has comment: http://stackoverflow.com/comment/115598452
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51541762
type: Answer
score: 2

http://stackoverflow.com/a/51484933
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51484885
has body: In general... you can use global variables. But with how your method is set up, you should just do df = read_file() inside of your clean_data() method. Then use df from there. Notice df is just the local name for the result of calling read_file(), you can call it anything.

http://stackoverflow.com/comment/89963475
type: Comment
comment on: http://stackoverflow.com/q/51497682
type: QuestionComment
has text: For example,I Guess because if you use some number start with 0 but list(str(num)) will only have length of 3 or less. And later you called num[3], therefore out of index.
score: 1

http://stackoverflow.com/comment/90156231
comment on: http://stackoverflow.com/a/51594280
type: Comment
has text: okay that works partially what I want only I want the specific person perms to be different that the role Member sorry if the name of that role got you confused
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89959657
has text: fro eg : if i call the method with the help of self , like self.my_obj.some_method() inside my method's(my_method) in my main class it will say "my_method' object has no attribute 'my_obj"
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51495624
score: 0

http://stackoverflow.com/a/51516198
has body: What you can do is create and use a virtualenv. It is recommended to manage python packages and versions. If you want to move / reinstall all your packages, pip can generate a list of installed packages with pip freeze, in a requirement.txt format. So you can reinstall everything anywhere you want using. pip install -r requirements.txt --target=/path/ You could also directly copy site-packages folders, but I would not recommend it.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51516032
upvote count: 1
answers question: http://stackoverflow.com/q/51516032
type: Answer
has comment: http://stackoverflow.com/comment/90002578
downvote count: 0
score: 1

http://stackoverflow.com/comment/90114566
has text: @RafaelIC Oh, I'm dumb! Yea that output works, but that's half of my problem solved. Now I'm left with the count of words from highest to lowest
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51574183

http://stackoverflow.com/q/51620286
has answer: http://stackoverflow.com/a/51621713
linked to: http://stackoverflow.com/q/46855458
accepted answer: http://stackoverflow.com/a/51621713
type: Question
upvote count: 4
tagged with: graph
has body: I'm trying to create an interactive graphs. I can't figure out how to plot a quadratic graph that is continuous - as in if you zoom out/move across the axes, the equation is plotted there, not just between 2 x points, so it's continuous. I've got this so far. import matplotlib.pyplot as plt xcoord=[] ycoord=[] for x in range(0,10): y=(2*x)**2 + 2*x + 4 xcoord.append(x) ycoord.append(y) plt.plot(xcoord,ycoord) plt.show()
has answer: http://stackoverflow.com/a/51621459
has answer: http://stackoverflow.com/a/51620573
downvote count: 0
score: 4
answer count: 3
has title: How do I create a graph that has a continuous axes with matplotlib?
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51621459
tagged with: python
tagged with: plot
type: AnsweredQuestion
tagged with: matplotlib

http://stackoverflow.com/q/51544094
duplicate of: http://stackoverflow.com/q/51505744
tagged with: python
possible better answer: http://stackoverflow.com/a/51544131
type: AnsweredQuestion
upvote count: 0
tagged with: list
has comment: http://stackoverflow.com/comment/90056333
downvote count: 2
type: Question
linked to: http://stackoverflow.com/q/51505744
has answer: http://stackoverflow.com/a/51544126
accepted answer: http://stackoverflow.com/a/51544126
score: -2
has body: I have a list as list1 = [(4356, 'OPIL', 2), (4356, 'OILY', 3), (5986, 'UISL', 1), (6985, 'LIBK', 3), (6985, 'LIBK', 1)] I want output to be like this: Output: result = [[(4356, 'OPIL', 2),(4356, 'OILY', 3)],[(5986, 'UISL', 1)], [(6985, 'LIBK', 3), (6985, 'LIBK', 1)]] How do we do it?
has answer: http://stackoverflow.com/a/51544131
answer count: 2
has comment: http://stackoverflow.com/comment/90056623
favorite count: 0
has title: How to group as defined by having their first element common, and keep them in a list of lists?

http://stackoverflow.com/q/51488975
has body: Here is the simple code import sys print (sys.argv[1]) I am working on passing argument to PYTHON from PHP For that first I want to make sure Python taking argument successfully. For that purpose i am running that simple two line code and I am getting Error C:\wamp3\www\v3.0&gt;argument.py hello Traceback (most recent call last): File "C:\wamp3\www\v3.0\argument.py", line 2, in &lt;module&gt; print (sys.argv[1]) IndexError: list index out of range Can anyone suggest some solution. I have gone through previous posted questions but nothing seems to work for me.
has comment: http://stackoverflow.com/comment/89946873
favorite count: 0
linked to: http://stackoverflow.com/q/4765085
has title: In Windows python sys.argv[1] returning error
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89947026
tagged with: python
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89946902
type: Question
has comment: http://stackoverflow.com/comment/89946887
has comment: http://stackoverflow.com/comment/129431194
has comment: http://stackoverflow.com/comment/89946875
has comment: http://stackoverflow.com/comment/89946840
linked to: http://stackoverflow.com/q/31689100
duplicate of: http://stackoverflow.com/q/29540541
upvote count: 1

http://stackoverflow.com/comment/90108635
type: QuestionComment
comment on: http://stackoverflow.com/q/51570291
has text: Let's say we have a time-series with some dependent variable, and an exogenous variable, like a code. I want to show that a code (code red/green) was active at a certain interval, by means of filling the interval with a color.
score: 0
type: Comment

http://stackoverflow.com/q/51604688
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90175285
has answer: http://stackoverflow.com/a/51604730
tagged with: python
duplicate of: http://stackoverflow.com/q/6181935
has title: Python: Declaring variables in for loop, each with different variable name
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/6181935
has body: I have a code that needs to declare several class attributes as shown below. However, what if I have 100 molecules, would I need to copy and paste the code and manually change the numbers accordingly 100 times? Or is there a way to declare variables with different names according to the for loop counter? For example For i in range(100): self.features_str(i+1)x_a= ... A quick explanation on what each function does. tensorise_smiles returns 3 tensors (in the form of ndarray) features_to_listedtuple takes in the tensor and another ndarray and returns one ndarray. What I have to do is create an attribute for each molecule 3 times, for the atom, bond, and edge features. However, the problem is if there are many molecules, I have to copy and paste the code many times, changing 1x to 2x, 3x, ..., 100x,... and so on. Is there a better way to do this? # Setting up features_d. Features containing SMILES for solvent, ligand, RA self.features_d_a = features_d # 1,2,3 represents the molecule for the solvent, ligand, RA. x,y,z for atom, bond, edge tensor self.features_1x_a, self.features_1y_a, self.features_1z_a = tensorise_smiles(features_d[:, 0]) self.features_2x_a, self.features_2y_a, self.features_2z_a = tensorise_smiles(features_d[:, 1]) self.features_3x_a, self.features_3y_a, self.features_3z_a = tensorise_smiles(features_d[:, 2]) self.features_1x_a = features_to_listedtuple(self.features_1x_a, labels) self.features_1y_a = features_to_listedtuple(self.features_1y_a, labels) self.features_1z_a = features_to_listedtuple(self.features_1z_a, labels) self.features_2x_a = features_to_listedtuple(self.features_2x_a, labels) self.features_2y_a = features_to_listedtuple(self.features_2y_a, labels) self.features_2z_a = features_to_listedtuple(self.features_2z_a, labels) self.features_3x_a = features_to_listedtuple(self.features_3x_a, labels) self.features_3y_a = features_to_listedtuple(self.features_3y_a, labels) self.features_3z_a = features_to_listedtuple(self.features_3z_a, labels…
type: Question
score: 0

http://stackoverflow.com/comment/90238231
type: AnswerComment
comment on: http://stackoverflow.com/a/51633335
score: 0
type: Comment
has text: thks, I've updated the question, the problem persists though

http://stackoverflow.com/comment/90058763
comment on: http://stackoverflow.com/q/51543298
has text: @user43134 you might want to look at `random.choice`... and then your code becomes `fighter_name = random.choice(NAMES)`... instead of the massive if/elif block... And to note - `ALL_CAPS_NAMES` should be used to indicate constants... it's preferable to use `fighter_name` instead of `FIGHTERNAME` and `player_hp` instead of `PLAYERHP` etc... You might want to have a read through [PEP8](https://www.python.org/dev/peps/pep-0008/?)
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/a/51573442
type: Answer
has body: simply np.flatten(), pd.Series(df.values.flatten()) (or) pd.Series(df.unstack().values)
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51571680
downvote count: 0

http://stackoverflow.com/a/51578233
answers question: http://stackoverflow.com/q/51578145
has body: I believe that you should be able to check the __args__ parameter: &gt;&gt;&gt; from typing import Dict, List, Type, TypeVar &gt;&gt;&gt; List[Dict].__args__ (typing.Dict,) &gt;&gt;&gt; List[int].__args__ (&lt;class 'int'&gt;,) But note from the docs: Note The typing module has been included in the standard library on a provisional basis. New features might be added and API may change even between minor releases if deemed necessary by the core developers. So this probably isn't future proof.
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51578145
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/51584850
has comment: http://stackoverflow.com/comment/90137974
has body: Using pandas, df = pd.read_csv(testcsv, index_col=['Header1'], sep=',\s+') df.to_dict() Output: {'Header2': {'A': 1, 'B': 2, 'C': 3}, 'Header3': {'A': 10, 'B': 20, 'C': 30}}
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51584754
has comment: http://stackoverflow.com/comment/90135357
accepted answer of: http://stackoverflow.com/q/51584754
score: 0

http://stackoverflow.com/a/53809259
score: 0
answers question: http://stackoverflow.com/q/51503649
type: Answer
has body: The black box with white letters is a python interactive shell. In there, you can only execute one line at a time. Like this: &gt;&gt;&gt; num = 1+2 &gt;&gt;&gt;print(num) 3 That shows that you can only enter one line at a time. Now, the white box with black letters is called an editor, it means that instead of writing your code every time to run it, you can just save it to file. So, in the editor, you write code like this: num = 1+2 print(num)

http://stackoverflow.com/comment/90017687
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51524289
type: AnswerComment
has text: ``` a = a.astype(np.uint8) ```

http://stackoverflow.com/a/51524096
downvote count: 0
has body: Using the '%timeit' magic in ipython, I got the following results: Array generation: %%timeit a1 = np.array(np.random.random(500000) * 1000) a2 = np.array(np.random.random(500000) * 5000) % 23.3 ms min-max gap: %%timeit np.max(a1) - np.min(a2) % 444 µs I think this is already very fast, maybe you measured some additional overhead, like @juvian suggested?
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51523034

http://stackoverflow.com/a/59476545
score: 0
type: Answer
has body: def cleanMerge(self, list1, list2): if len(list1)!=len(list2): less = list1 if len(list1)&lt;len(list2) else list2 chosenList = list2 if len(list1)&lt;len(list2) else list1 chosenList = list1 less = list2 l1,l2,r1,r2 = 0,0,len(chosenList),len(less) while l2&lt;r2 and l1&lt;r1: if chosenList[l1]&gt;less[l2]: chosenList[l1+1:r1+1] = chosenList[l1:r1] chosenList[l1] = less[l2] l2+=1 l1+=1 r1+=1 else: l1+=1 continue if l2&lt;r2: for item in less[l2:r2]: chosenList.append(item) return chosenList
answers question: http://stackoverflow.com/q/51588610

http://stackoverflow.com/comment/90174606
has text: @Geshode the intended code is on the bottom section. Fixing the code is strightforward
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51604374
type: Comment

http://stackoverflow.com/comment/90187932
type: QuestionComment
has text: Another point is that your question is becoming admittedly off topic for SO, bounty not withstanding.
comment on: http://stackoverflow.com/q/51518601
score: 1
type: Comment

http://stackoverflow.com/q/51576014
tagged with: libvirt
has body: I'm currently trying to get the mac address but I'm a bit confused. When I try import libvirt # To connect to the hypervisor # Connect to your local hypervisor. See https://libvirt.org/uri.html conn = libvirt.open('qemu+ssh://%s/system' % servidor.ubicacion_ip) # Open the hypervisor in read-only mode # conn = libvirt.open(None) # Open the default hypervisor in read-write mode (require if conn == None: raise Exception('Failed to open connection to the hypervisor') dom = conn.lookupByName('userid_%s_servidor_%s.qcow2' % (user.id, servidor.id)) But when I check guest python api commands in libvirt but the c api commands seems to show that it should have a way to get the mac address?
has answer: http://stackoverflow.com/a/51576171
tagged with: python
tagged with: kvm
type: UnansweredQuestion
has title: Get Mac address of guest KVM with libvirt
type: Question
score: 0
answer count: 1

http://stackoverflow.com/q/51601272
has title: python matplotlib heatmap colorbar from transparent
upvote count: 13
tagged with: heatmap
has answer: http://stackoverflow.com/a/51601850
type: AnsweredQuestion
tagged with: colorbar
tagged with: matplotlib
has body: How to implement python matplotlib heatmap colorbar like this？ plt.imshow(a,aspect='auto', cmap=plt.cm.gist_rainbow_r) plt.colorbar()
type: Question
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51601850
favorite count: 0
has comment: http://stackoverflow.com/comment/90169294
tagged with: python
score: 13

http://stackoverflow.com/a/69343240
score: 1
has body: If you want to insert multiple documents into the collection you can use insert_many option (If you want to insert names of the people into different documents) try { db.Human.insertMany( [ { name: "John"}, { item: "Jack"}, { item: "Chris"} ] ); } catch (e) { print (e); }
answers question: http://stackoverflow.com/q/51608235
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/q/51543105
tagged with: django
tagged with: python
score: 0
type: Question
has answer: http://stackoverflow.com/a/51543225
has title: Issue with __range function in Django
tagged with: django-queryset
answer count: 1
type: UnansweredQuestion
has body: What I need to do is filter all the sales objects from a particular zone and region and within a date range. So, I used the __range function in the query something like this start = start_date.strftime('%d-%b-%y') end = end_date.strftime('%d-%b-%y') Sales.objects.filter(zone_code=zone_code_, region_code=region_code_, sales_date__range(start,end)) All my dates are stored as characters in my models, so I changed the input dates to that format using strftime(). But this query is giving me objects beyond the specified range, and sometimes a null set.

http://stackoverflow.com/q/51530785
has answer: http://stackoverflow.com/a/51531681
has body: below is a csv snippet with some dummy headers while the actual frame anchored by beerId: This work is an unpublished, copyrighted work and contains confidential information. beer consumption consumptiondate 7/24/2018 consumptionlab H1 numbeerssuccessful 40 numbeersfailed 0 totalnumbeers 40 consumptioncomplete TRUE beerId Book 341027 Northern Light this df = pd.read_csv(path_csv, header=8) code works, but the issue is that header is not always in 8 depending on a day. cannot figure out how to use lambda from help as in skiprows : list-like or integer or callable, default None Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file. If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be lambda x: x in [0, 2]. to find the index row of beerId
tagged with: pandas
answer count: 1
favorite count: 0
has title: pandas read_csv skiprows - determine rows to skip
accepted answer: http://stackoverflow.com/a/51531681
tagged with: python
score: 4
type: AnsweredQuestion
type: Question
upvote count: 4
downvote count: 0

http://stackoverflow.com/a/51538110
has body: Your s is a list of nested tuples. But you could easily create a dict from it, by passing it to the dict constructor. But if you actually have a dict you can efficiently extract the 1st item from each key tuple using operator.itemgetter. from operator import itemgetter s = [ ((3, 6), 9.0), ((1, 6), 8.0), ((3, 8), 8.0), ((3, 7), 7.0), ((0, 6), 7.0), ((1, 8), 7.0), ((0, 8), 6.0), ((2, 4), 6.0), ((1, 7), 6.0), ((2, 6), 5.0), ((2, 9), 5.0), ((0, 7), 5.0), ((3, 5), 5.0), ((2, 8), 4.0), ((1, 5), 4.0), ((0, 4), 4.0), ((3, 2), 4.0), ((2, 3), 4.0), ((2, 1), 3.0), ((1, 2), 3.0), ((2, 7), 3.0), ((1, 4), 3.0), ((0, 5), 3.0), ((0, 9), 3.0), ((3, 0), 2.0), ((0, 3), 2.0), ((2, 0), 2.0), ((3, 4), 2.0), ((0, 2), 2.0), ((1, 9), 2.0), ((1, 3), 1.0), ((2, 5), 1.0), ((3, 9), 1.0), ((1, 0), 1.0), ((0, 1), 1.0), ((3, 1), 1.0), ((3, 3), 0.0), ((1, 1), 0.0), ((0, 0), 0.0), ((2, 2), 0.0) ] d = dict(s) print(d) a = list(map(itemgetter(0), d)) print(a) output {(3, 6): 9.0, (1, 6): 8.0, (3, 8): 8.0, (3, 7): 7.0, (0, 6): 7.0, (1, 8): 7.0, (0, 8): 6.0, (2, 4): 6.0, (1, 7): 6.0, (2, 6): 5.0, (2, 9): 5.0, (0, 7): 5.0, (3, 5): 5.0, (2, 8): 4.0, (1, 5): 4.0, (0, 4): 4.0, (3, 2): 4.0, (2, 3): 4.0, (2, 1): 3.0, (1, 2): 3.0, (2, 7): 3.0, (1, 4): 3.0, (0, 5): 3.0, (0, 9): 3.0, (3, 0): 2.0, (0, 3): 2.0, (2, 0): 2.0, (3, 4): 2.0, (0, 2): 2.0, (1, 9): 2.0, (1, 3): 1.0, (2, 5): 1.0, (3, 9): 1.0, (1, 0): 1.0, (0, 1): 1.0, (3, 1): 1.0, (3, 3): 0.0, (1, 1): 0.0, (0, 0): 0.0, (2, 2): 0.0} [3, 1, 3, 3, 0, 1, 0, 2, 1, 2, 2, 0, 3, 2, 1, 0, 3, 2, 2, 1, 2, 1, 0, 0, 3, 0, 2, 3, 0, 1, 1, 2, 3, 1, 0, 3, 3, 1, 0, 2] However, you probably should not do this, unless you're using Python 3.6+, because in earlier versions dictionaries do not preserve insertion order, so there is no guarantee that the items in a are in the same order as the items in s. If you don't actually have a dict, but you just have that s list, then your code l = [a[0][0] for a in s] is perfectly fine.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51537905
upvote count: 1
has comment: http://stackoverflow.com/comment/90050573
downvote count: 1

http://stackoverflow.com/q/51549170
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/36989653
tagged with: import
type: Question
has answer: http://stackoverflow.com/a/51549288
duplicate of: http://stackoverflow.com/q/36989653
tagged with: javascript
tagged with: flask
has title: Python flask using variables from config.py in javascript file
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51549288
tagged with: python-3.x
tagged with: python
has body: I am trying to reuse some of my variables from my config.py in my javascript files, specifically WEBSERVER_HOST and WEBSERVER_PORT variables. My config.py looks like this: config.py # Webserver configs WEBSERVER_HOST = 'myhost' WEBSERVER_PORT = 5000 In my js file I declare these on the top of my js file like this: app.js: var HOST = 'myhost'; // I want this var HOST = WEBSERVER_HOST; var PORT = 5000; // and this var PORT = WEBSERVER_PORT; I can import config.py in a regular python file (e,g. run.py), but I would like to know if I can somehow also import these values into my javascript files as well so I don't have to declare them twice.

http://stackoverflow.com/q/51517668
has comment: http://stackoverflow.com/comment/90004512
has comment: http://stackoverflow.com/comment/90003970
tagged with: python-requests
has comment: http://stackoverflow.com/comment/90003998
linked to: http://stackoverflow.com/q/38021629
type: Question
has comment: http://stackoverflow.com/comment/90004545
has comment: http://stackoverflow.com/comment/90004523
has comment: http://stackoverflow.com/comment/90004663
linked to: http://stackoverflow.com/q/41882184
has comment: http://stackoverflow.com/comment/90004153
has title: Python requests - Put ignores file upload
has comment: http://stackoverflow.com/comment/90004577
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90006349
has comment: http://stackoverflow.com/comment/90004737
favorite count: 0
has answer: http://stackoverflow.com/a/51537139
upvote count: 2
has comment: http://stackoverflow.com/comment/90006433
type: UnansweredQuestion
has body: I am trying to upload a file through python requests using the PUT method. But on the server side, the file is never received. The code that I am using is: files = {'test' : open(r"C:\Users\test.jar", 'rb')} response = session.put(api_base + url.get('url').format(foo, bar), headers=headers, data=data, files=files) Does PUT ignore file uploads? Is it only valid for posts? What am I doing wrong?
tagged with: python
has comment: http://stackoverflow.com/comment/90006519
score: 2
has comment: http://stackoverflow.com/comment/90004544

http://stackoverflow.com/q/51513259
downvote count: 0
possible better answer: http://stackoverflow.com/a/51513557
has answer: http://stackoverflow.com/a/51513557
type: AnsweredQuestion
score: 1
tagged with: duplicates
type: Question
accepted answer: http://stackoverflow.com/a/51513374
answer count: 2
upvote count: 1
has body: Giving this Data sample, I would like to deduplicate rows by mergin info by one column and not by deleting rows. In this case would be the field CODE. df = pd.DataFrame({'CODE':['000', '111','111','222','222', '333'],'NAME':['help','foo','bar', 'bla','booo','nyaa'] ,'ALT_NAME':['zzz','foo 1','bar', 'bl','bo','rrr'] }) print(df) Output: ALT_NAME CODE NAME 0 zzz 000 help 1 foo 1 111 foo 2 bar 111 bar 3 bl 222 bla 4 bo 222 booo 5 rrr 333 nyaa The result would be: ALT_NAME CODE NAME 0 zzz 000 help 1 [foo 1, bar] [111,111] [foo,bar] 2 [bl,bo] [222,222] [bla,boo] 3 rrr 333 nyaa Im near to the solution but i can not reach it: clue: df.groupby('CODE')['ALT_NAME','NAME'].apply(list).reset_index() But this is not working for several columns
favorite count: 0
has title: merge information from duplicate records in python
has answer: http://stackoverflow.com/a/51513374
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/105713733
has text: XXX: Fixtures do not support migrations. Don't use them in case if your model will change frequently, otherwise you'll have to re-generate fixtures per model change.
type: Comment
comment on: http://stackoverflow.com/a/55223981
score: 7
type: AnswerComment

http://stackoverflow.com/q/51637537
has comment: http://stackoverflow.com/comment/90263620
tagged with: discord.py
has comment: http://stackoverflow.com/comment/90257286
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90282368
type: Question
has title: Create an async function for my discord bot that can be run at any time
linked to: http://stackoverflow.com/q/50216043
has comment: http://stackoverflow.com/comment/90239577
has comment: http://stackoverflow.com/comment/90257120
tagged with: discord
answer count: 0
tagged with: python
linked to: http://stackoverflow.com/q/49835742
has comment: http://stackoverflow.com/comment/90239623
has body: I am creating a discord bot using Discord's discord.py API. I've seen that by creating on_message() and on_ready() functions, I can make my bot do things when a message is sent, or when the bot is started, but if I want my bot to do something without needing to restart my bot or sending a message, what should I do? I need to do that because I'm creating an API for my bot, so if I write say(channel, "Hello"), that should make my bot, without restarting it or sending any message to the bot, say Hello on the channel Id specified.
score: 0

http://stackoverflow.com/comment/90132778
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51583403
has text: It's not {% url 'book_types_list:book_types_detail' **book_type.id** %} but **book_type.0**. book_type is not a model object.
score: 0

http://stackoverflow.com/comment/115574820
has text: Make sure that you download the whl file that has the same `cp` number as your python version. I use python 3.8, so I downloaded this: `Twisted‑20.3.0‑cp38‑cp38‑win_amd64.whl`
type: Comment
comment on: http://stackoverflow.com/a/61078910
score: 0
type: AnswerComment

http://stackoverflow.com/q/51604748
has comment: http://stackoverflow.com/comment/90175204
has comment: http://stackoverflow.com/comment/90175226
type: UnansweredQuestion
downvote count: 2
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51604827
score: -1
has comment: http://stackoverflow.com/comment/90175257
type: Question
has comment: http://stackoverflow.com/comment/90177979
answer count: 1
tagged with: raspberry-pi3
has title: How do I rectify this error: "newline" is invalid keyword argument for this function
favorite count: 0
has comment: http://stackoverflow.com/comment/90175234
tagged with: sensors
has body: I'm currently working with raspberry pi and using DHT11 to read temperature and humidity values every second. I have to save these values into a database in real time. Here's my code that showing sensor data every second. import RPi.GPIO as GPIO import dht11 import time import datetime import csv import os # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup() instance = dht11.DHT11(pin=dht11_pin) with open('file_name.csv', 'w', newline='') as csvfile: field_names = ['Date', 'Time', 'Status', 'Temperature', 'Humidity'] writer = csv.DictWriter(csvfile, fieldnames=field_names) writer.writerow( {'Date': 'Date', 'Time': 'Time', 'Status': 'Status', 'Temperature': 'Temperature', 'Humidity': 'Humidity'}) while True: cnt += 1 if cnt%limit_sec == 0 or cnt == 1: result = instance.read() if result.is_valid(): if previous_temperature != result.temperature or previous_humidity != result.humidity: previous_temperature = result.temperature previous_humidity = result.humidity counter += 1 rightnow = datetime.datetime.now() if result.humidity&gt;=40: status = 'Your plant is on the good condition.' print(str(counter)+". Last valid input: " ) print("Date: " + rightnow.strftime("%d/%m/%Y")) print("Time: " + rightnow.strftime("%H:%M:%S")) print("Status: Your plant is on the good condition.") print("Temperature: %d C" % result.temperature) print("Humidity: %d %%" % result.humidity) print("*******************************************") else: status = 'Your plant is on the bad condition. Please open the water supply.' print(str(counter)+". Last valid input: " ) print("Date: " + rightnow.strftime("%d/%m/%Y")) print("Time: " + rightnow.strftime("%H:%M:%S")) print("Status: Your plant is on the bad condition. Please open the water supply.") print("Temperature: %d C" % result.temperature) print("Humidity: %d %%" % result.humidity) print("*******************************************") writer.writerow( {'Date': rightnow.strftime("%d/%m/%Y"), 'Time': rightnow.strftime("%H:%M…
has comment: http://stackoverflow.com/comment/90175219
tagged with: python-3.x

http://stackoverflow.com/comment/90174355
type: Comment
type: QuestionComment
has text: I'll be on hold here to provide more data, because I'm not sure what you guys may need. Just let me know. Thank you in advance!
score: 0
comment on: http://stackoverflow.com/q/51604282

http://stackoverflow.com/comment/90151319
comment on: http://stackoverflow.com/a/51580070
score: 0
type: AnswerComment
has text: Oh I was catching the return so I could parse it out to file.
type: Comment

http://stackoverflow.com/comment/89997608
type: Comment
comment on: http://stackoverflow.com/a/51514361
type: AnswerComment
score: 1
has text: what does this add that isn't present in the existing answer?

http://stackoverflow.com/q/51485955
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/89941073
has title: Python dataframe data cleanup- normalize range of columns
has comment: http://stackoverflow.com/comment/89941013
has comment: http://stackoverflow.com/comment/89941057
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89940994
linked to: http://stackoverflow.com/q/26414913
tagged with: python
has answer: http://stackoverflow.com/a/51486037
score: 2
has body: I have a df with 2171 columns and 200+ rows. I want to normalize a range of those cols. [Input df] Time '340.0' '341.0' '342.0' 'Mode' 11:30:15 PM 0.25 0.35 0.65 light 11:31:15 PM 0.22 0.30 0.62 auto 11:32:15 PM 0.32 0.39 0.98 auto . . . [Code if only used on one col, I am not sure how to apply to a range of cols] sr_df['340.0'] = sr_df['340.0'].apply(lambda x: (x - x.mean()) / (x.std())) I am very new to python and I am not sure why it is giving me the following error: AttributeError: 'float' object has no attribute 'mean'
tagged with: dataframe
linked to: http://stackoverflow.com/q/24645153
type: Question
tagged with: normalization
has comment: http://stackoverflow.com/comment/89941048
downvote count: 0
has answer: http://stackoverflow.com/a/51487037
linked to: http://stackoverflow.com/q/19782586

http://stackoverflow.com/comment/89962622
score: 0
has text: @MilanoSlesarik can you share nginx config?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51495283

http://stackoverflow.com/comment/90113448
has text: I made a git commit with the requirements.txt and I'm pretty sure that is the problem
score: 0
comment on: http://stackoverflow.com/q/51567483
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89963363
type: Comment
has text: Still horrible performance. Polynomial, where it could be linear.
type: AnswerComment
comment on: http://stackoverflow.com/a/51497684
score: 0

http://stackoverflow.com/a/51571826
has comment: http://stackoverflow.com/comment/90109965
answers question: http://stackoverflow.com/q/51571652
has comment: http://stackoverflow.com/comment/90110321
has body: $ sudo find / -name "collections.py" /home/deep/cocoapi/PythonAPI/Detectron/detectron/utils/collections.py I think, here might lie the culprit. There is a module in your detectron package that is named "collections". I guess, somehow this collections module is imported before the standard collections module is imported. All modules are stored in memory by their names, after import. So when a different package does again an import of "collections" it will just (because of the name clash) get the wrong module. And because this does not contain namedtuple, you get the error. Remedy: either rename the collections module or make sure that it is always imported with package (fully qualified) Ergo: don't use the names of standard modules for your modules -- it is just dangerous.
type: Answer
has comment: http://stackoverflow.com/comment/90109954
score: 2
accepted answer of: http://stackoverflow.com/q/51571652
upvote count: 2
has comment: http://stackoverflow.com/comment/90109718
has comment: http://stackoverflow.com/comment/90110429
has comment: http://stackoverflow.com/comment/90109986
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89947795
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51489464
has text: It sounds like you're trying to layer relational logic on top of a non-relational database. You will almost always have better results going the other way.

http://stackoverflow.com/comment/90050113
has text: The idea, IIUC, with `mmap` isn't just an change in the interface, but you are transferring data directly into your process's address space, bypassing any buffers in the file-system layer. I've also observed non-trivial differences in speed between `m.read(d)` and `m[x:x+d]`, where `m` is my `mmap` object.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51540440

http://stackoverflow.com/a/73546289
type: Answer
answers question: http://stackoverflow.com/q/51623208
has body: Firstly, run the following command in the terminal: pip install pynput Then install the package through the PyCharm IDE: In PyCharm, click File > Settings > Project: "projectname" > Python Interpreter > click the + > type "pynput" > click "Install Package"
score: 0

http://stackoverflow.com/a/51610013
answers question: http://stackoverflow.com/q/51609791
score: 1
upvote count: 1
has body: A counter solution also works - from collections import Counter C = Counter() A = ['0', '0', '3', '4', '6', '6', '6', '6', '6', '6', '10', '10', '10'] B = ['1', '10', '2', '5', '0', '3', '4', '7', '8', '9', '6', '11', '12'] C.update(A) C.update(B) D = [k for k, v in C.iteritems() if v == 1] # OP ['11', '12', '1', '2', '5', '7', '9', '8']
has comment: http://stackoverflow.com/comment/90187910
downvote count: 0
type: Answer

http://stackoverflow.com/a/55116335
has body: It's pygtk. Case sensitivity has caused the error probably. This has been deprecated for python3 though and has been replaced by pygi.
answers question: http://stackoverflow.com/q/51485536
upvote count: 1
score: 0
downvote count: 1
type: Answer

http://stackoverflow.com/comment/90135634
score: 0
type: AnswerComment
has text: Use [```tf.constant_initializer(numpy_array)```](https://www.tensorflow.org/api_docs/python/tf/constant_initializer) as the initializer argument in ```tf.get_variable()```
type: Comment
comment on: http://stackoverflow.com/a/51559128

http://stackoverflow.com/comment/90178100
type: Comment
type: QuestionComment
has text: Have you looked at [timeit](https://docs.python.org/2/library/timeit.html) ?
comment on: http://stackoverflow.com/q/51606399
score: 0

http://stackoverflow.com/comment/89990105
type: QuestionComment
has text: Thanks for the help, yes, there is data for Tesla, so I am not sure still where is the problem
score: 0
comment on: http://stackoverflow.com/q/51509600
type: Comment

http://stackoverflow.com/a/51543619
has comment: http://stackoverflow.com/comment/90056050
type: Answer
has comment: http://stackoverflow.com/comment/90055782
upvote count: 2
has body: You can easily do this in few lines of code: import pandas as pd # Uncomment to read from file and comment out a, b vars from pd.DataFrame #a = pd.read_csv('1.csv') #b = pd.read_csv('2.csv') a = pd.DataFrame({'name': ['aaaa', 'bbbb', 'cccc', 'dddd'], 'feature': ['apple', 'mango', 'orange', 'guava'], 'start_date': ['2018-02-10','2018-03-11','2018-04-12','2018-05-13',]}) b = pd.DataFrame({'name': ['aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg'], 'feature': ['apple', 'mango', 'orange', 'guava', 'Avocado', 'Banana','Bilberry',], 'end_date': ['2018-02-13','2018-03-16','2018-04-15','2018-05-18','2018-06-14','2018-07-13','2018-08-09']}) # replace to on=['name', 'feature', 'ipaddress'] if needed. # In example you don't have 'ipaddress', but in your code you have it c = pd.merge(a, b, how='inner', on=['name', 'feature']) c['difference'] = pd.to_datetime(c['end_date']) - pd.to_datetime(c['start_date']) print(c) #Uncomment to save to file #c.to_csv('3.csv') Check variables. It completely same as in your example. print(a) name feature start_date 0 aaaa apple 2018-02-10 1 bbbb mango 2018-03-11 2 cccc orange 2018-04-12 3 dddd guava 2018-05-13 print(b) name feature end_date 0 aaaa apple 2018-02-13 1 bbbb mango 2018-03-16 2 cccc orange 2018-04-15 3 dddd guava 2018-05-18 4 eeee Avocado 2018-06-14 5 ffff Banana 2018-07-13 6 gggg Bilberry 2018-08-09 print(c) name feature start_date end_date difference 0 aaaa apple 2018-02-10 2018-02-13 3 days 1 bbbb mango 2018-03-11 2018-03-16 5 days 2 cccc orange 2018-04-12 2018-04-15 3 days 3 dddd guava 2018-05-13 2018-05-18 5 days Hope this helps!
has comment: http://stackoverflow.com/comment/90057533
has comment: http://stackoverflow.com/comment/90055868
score: 2
has comment: http://stackoverflow.com/comment/90057605
downvote count: 0
has comment: http://stackoverflow.com/comment/90055330
answers question: http://stackoverflow.com/q/51542884

http://stackoverflow.com/q/51572024
possible better answer: http://stackoverflow.com/a/51572085
score: 0
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51572101
linked to: http://stackoverflow.com/q/11474706
has answer: http://stackoverflow.com/a/51572085
type: Question
has comment: http://stackoverflow.com/comment/90110083
has answer: http://stackoverflow.com/a/51572101
has body: Say I have a dictionary of this structure: x = { "a": { "b": { "c": 1 } } } I create a function that accepts a structure like some_func(structure={"a.b.c":2}) I need this function to traverse x and change the value of c to 2. The depth of the dictionary is unknown to the function. So it has to rely on the structure passed to it. How do I do this?
has comment: http://stackoverflow.com/comment/90110206
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/90110546
has title: "Remember" parent keys in python dictionary
upvote count: 2
answer count: 2
downvote count: 2
favorite count: 0

http://stackoverflow.com/a/51492347
score: 0
has body: I've found the answer! It was just a for loop missing for elem in self.canvas.find_withtag("my_tag"): self.canvas.itemconfig(elem, fill='blue')
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51491996
answers question: http://stackoverflow.com/q/51491996

http://stackoverflow.com/q/51484261
has comment: http://stackoverflow.com/comment/89938048
has answer: http://stackoverflow.com/a/51484541
has title: Is there a way to pull corresponding items from different lists in python?
linked to: http://stackoverflow.com/q/1663807
answer count: 2
tagged with: data-structures
favorite count: 0
has body: I'm trying to create a program that will keep track of your party and their health in a tabletop RPG. The best way I can think of so far is to have two separate lists, one with the party members and one with their health, so that when you display the party, it will run a code that looks something like this: for Member in Party: print(str(Member) + ":", str(Health), "HP") Is there a way to pull the corresponding HP for each member from the different lists?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89937459
has comment: http://stackoverflow.com/comment/89938148
has answer: http://stackoverflow.com/a/51484394
upvote count: 2
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89937439
has comment: http://stackoverflow.com/comment/89937701
type: Question
tagged with: indexing

http://stackoverflow.com/q/51567673
score: 0
has comment: http://stackoverflow.com/comment/90109082
has title: Is it acceptable to use global in this case? Is there a more pythonic way to achieve the same result?
answer count: 1
has comment: http://stackoverflow.com/comment/90101989
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51568470
type: UnansweredQuestion
tagged with: python
tagged with: global-variables
type: Question
has body: The code below works, but I see everyone discourage the use of global variables. I see how it can cause problems, so is there a better/more pythonic way to do what the code below does? This code is for a chat moderation bot. As soon as a message is received bot checks if the filter is enabled or not and proceeds with the filtering if the boolean below is set to true. filter_is_enabled = True def toggle_filter(): global filter_is_enabled filter_is_enabled = not filter_is_enabled if filter_is_enabled: bot.say('Chat filter enabled.') else: bot.say('Chat filter disabled.') def check_message(message): if filter_is_enabled: # proceed with the filtration else: # proceed without filtering

http://stackoverflow.com/comment/90001850
has text: There this aweful solution : `last_digits_sum = sum(map(int, a.split('^^^^^^^^^')[-1].split('^^')[0].split('|')))` output : `824824` that will give tou the sum of the last digits. But does it generalize well to your case ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51516628

http://stackoverflow.com/a/51543002
answers question: http://stackoverflow.com/q/51539706
type: AcceptedAnswer
downvote count: 0
has body: import numpy as np import cv2 from multiprocessing import Process def send(): cap_send = cv2.VideoCapture('videotestsrc ! video/x-raw,framerate=20/1 ! videoscale ! videoconvert ! appsink', cv2.CAP_GSTREAMER) out_send = cv2.VideoWriter('appsrc ! videoconvert ! x264enc tune=zerolatency bitrate=500 speed-preset=superfast ! rtph264pay ! udpsink host=127.0.0.1 port=5000',cv2.CAP_GSTREAMER,0, 20, (320,240), True) if not cap_send.isOpened() or not out_send.isOpened(): print('VideoCapture or VideoWriter not opened') exit(0) while True: ret,frame = cap_send.read() if not ret: print('empty frame') break out_send.write(frame) cv2.imshow('send', frame) if cv2.waitKey(1)&amp;0xFF == ord('q'): break cap_send.release() out_send.release() def receive(): cap_receive = cv2.VideoCapture('udpsrc port=5000 caps = "application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264, payload=(int)96" ! rtph264depay ! decodebin ! videoconvert ! appsink', cv2.CAP_GSTREAMER) if not cap_receive.isOpened(): print('VideoCapture not opened') exit(0) while True: ret,frame = cap_receive.read() if not ret: print('empty frame') break cv2.imshow('receive', frame) if cv2.waitKey(1)&amp;0xFF == ord('q'): break cap_receive.release() if __name__ == '__main__': s = Process(target=send) r = Process(target=receive) s.start() r.start() s.join() r.join() cv2.destroyAllWindows()
type: Answer
score: 7
upvote count: 7
accepted answer of: http://stackoverflow.com/q/51539706

http://stackoverflow.com/comment/90201599
score: 0
type: Comment
type: QuestionComment
has text: @Elazar: that's the solution #1 on my list. My question is: can I modify Python3 syntax to read `L`.
comment on: http://stackoverflow.com/q/51616995

http://stackoverflow.com/q/51573824
has title: How to get nth record from result set of aerospike scan() output in Python, without looping through all results?
answer count: 2
has body: A beginner question with python probably. I am able to iterate over the results of aerospike db query like this - client = aerospike.client(config).connect() scan = client.scan('namespace', 'setName') scan.select('PK','expiresIn','clientId','scopes','roles') # scan from aerospike scan.foreach(process_result) def process_result((key, metadata, record)): expiresIn = record.get("expiresIn") Now, all I want to do is get the nth record from this set, without having to iterate through all. I tried looking at Get the nth item of a generator in Python but could not make much sense.
has answer: http://stackoverflow.com/a/51582101
has answer: http://stackoverflow.com/a/51699348
tagged with: aerospike
score: 0
linked to: http://stackoverflow.com/q/2300756
type: UnansweredQuestion
tagged with: python
type: Question

http://stackoverflow.com/comment/90012782
has text: Ah yes, good point, that worked..
comment on: http://stackoverflow.com/q/51521782
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51577648
tagged with: dataframe
type: Question
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/90120657
has comment: http://stackoverflow.com/comment/90120824
tagged with: pandas
has title: Insertion of Series in a DataFrame
tagged with: python
has body: When I try to construct a DataFrame using one series, this series becomes column in DataFrame. #name of series become column. All indexes of series become indexes s= pd.Series({'a':1,'b':2,'c':3}, name='joe') df=pd.DataFrame(s) print(df) joe a 1 b 2 c 3 But when a list of series is provided, all series become rows in DataFrame. # indexes become columns. series name become row name s1= pd.Series({'a':1,'b':2,'c':3}, name='joe') s2=pd.Series({'a':4,'b':5,'c':6}, name='john') slist=[s1,s2] df=pd.DataFrame(slist) print(df) a b c joe 1 2 3 john 4 5 6 Why is this difference in handling? Why can't a series always become row in DataFrame, irrespective of whether a list is provided or a single Series. I am sure Pandas developers didn't just do it on a whim. After the creation of a DataFrame, if I try to append a single Series, then it gets appended as row. import pandas as pd s1= pd.Series({'a':1,'b':2,'c':3}, name='s1') s2=pd.Series({'a':4,'b':5,'c':6}, name='s2') slist=[s1,s2] df=pd.DataFrame(slist) s=pd.Series({'b':1}, name='s3') df=df.append(s) print(df) a b c s1 1.0 2.0 3.0 s2 4.0 5.0 6.0 s3 NaN 1.0 NaN
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51577658

http://stackoverflow.com/comment/90038474
comment on: http://stackoverflow.com/q/51535378
has text: Surely your code is using CPU not GPU. Can you share the code?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90196145
type: Comment
comment on: http://stackoverflow.com/q/51615325
score: 4
type: QuestionComment
has text: Welcome to SO. Please take the time to read [mcve], [ask] and the other links on that page.

http://stackoverflow.com/comment/90012645
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51521626
has text: @rahlf23 - Thanks for the edit, I tried the code but still no coloring :/

http://stackoverflow.com/q/51620828
type: UnansweredQuestion
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/90207162
has comment: http://stackoverflow.com/comment/90207130
has answer: http://stackoverflow.com/a/51620874
tagged with: absolute
type: Question
has comment: http://stackoverflow.com/comment/90212064
tagged with: sorting
has title: How do you sort a multidimensional list by absolute value in python
score: 0
has comment: http://stackoverflow.com/comment/90207187
answer count: 1
has body: I've got a 3 dimensional list, two of the columns include strings, and one an int. How do I sort the second column by absolute value? I've tried: sorted(yestForSort,key=lambda l:l[1], reverse=True) but this doesn't give me absolute value. I've tried: def sorting(numbers_array): return sorted(numbers_array, key = abs(numbers_array)) but this doesn't work on 2 dimensions.

http://stackoverflow.com/q/51591298
downvote count: 1
has comment: http://stackoverflow.com/comment/90147964
linked to: http://stackoverflow.com/q/43134753
duplicate of: http://stackoverflow.com/q/47068709
linked to: http://stackoverflow.com/q/41293077
tagged with: tensorflow
type: Question
answer count: 1
has body: I'm new at machine learning, and relatively new at programming in general. I am trying to install Tensorflow on my machine through Anaconda. It has installed, but when I try to run the following code: import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() print(sess.run(hello)) it gives me the error: Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2. I've done some reading which seems to indicate that I need to install a custom version of TensorFlow that works with my CPU. I also read that one way to go about this was through bazel build. (How to compile Tensorflow with SSE4.2 and AVX instructions?) I downloaded bazel, but now am not able to use the command bazel build to customize TensorFlow for my laptop. I keep getting the error: bazel is not recognised as an internal or external command, despite having moved it to a directory on my %PATH%. Is there an easier way for me to install TensorFlow? If not, if anyone has any insight on why bazel is not being recognised, or if I'm doing something wrong that should be obvious, please let me know. Thanks!
favorite count: 0
tagged with: bazel
score: 0
has title: Errors while installing tensorflow
has answer: http://stackoverflow.com/a/51591507
type: UnansweredQuestion
tagged with: machine-learning
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/47068709

http://stackoverflow.com/a/51501423
has comment: http://stackoverflow.com/comment/89972048
has comment: http://stackoverflow.com/comment/89972030
has comment: http://stackoverflow.com/comment/89980294
has comment: http://stackoverflow.com/comment/89971853
score: 0
answers question: http://stackoverflow.com/q/51501178
has comment: http://stackoverflow.com/comment/89972305
type: Answer
has comment: http://stackoverflow.com/comment/89973318
has comment: http://stackoverflow.com/comment/89971600
has body: The problem is that your user input should be an int. Use this instead :=>"user_input = int(input("Please select one: "))" And also you cannot write an integer to a file so use this: => "readfile.write("user_input")" or convert your user input to string before writing to the file.
has comment: http://stackoverflow.com/comment/89971568
has comment: http://stackoverflow.com/comment/89973529
has comment: http://stackoverflow.com/comment/89973300
has comment: http://stackoverflow.com/comment/89972264
has comment: http://stackoverflow.com/comment/89972555
has comment: http://stackoverflow.com/comment/89972323

http://stackoverflow.com/comment/90231002
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51633095
has text: Updated snippet

http://stackoverflow.com/comment/90079173
has text: Your question is unclear. "are" is in "b" only
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51556272

http://stackoverflow.com/q/51635126
tagged with: calibration
tagged with: python
has comment: http://stackoverflow.com/comment/90239059
answer count: 0
type: UnansweredQuestion
tagged with: probability
upvote count: 1
has body: I am trying to use sklearn's CalibratedClassifierCV() with lightgbm as below: clf = LGBMClassifier( boosting_type= 'gbdt', objective= 'multiclass', num_class=5, metric= 'multi_logloss', learning_rate= 0.05, max_depth= 7, num_leaves= 60, feature_fraction= 0.7, bagging_fraction= 1, bagging_freq= 20, nthread=4, n_estimators=50) calibrated_clf = CalibratedClassifierCV(clf, method='isotonic', cv=5) calibrated_clf.fit(train_df[v1], train_df['label']) However it's throwing me error, because there are some categorical variables, which lightgbm can handle efficiently without having to convert into one hot encoding but CalibratedClassifierCV not. error: ValueError: could not convert string to float: 'RC' It's calling sklearn's validation.py which is throwing error at step, because calling astype float on string object: if dtype_numeric and array.dtype.kind == "O": array = array.astype(np.float64) Is there a way I can handle this problem without converting into numeric variables? I am avoiding converting categories to numeric, as there are more than 10000 categories
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90304775
has title: probability calibration using CalibratedClassifierCV for lightgbm
downvote count: 0
favorite count: 0
tagged with: lightgbm

http://stackoverflow.com/a/51567989
has body: On Mac OS X, the launcher to open any document, URL, etc. is open. To invoke it from Python, try this: import subprocess subprocess.check_call(['open', mypath]) On Linux and other *nix systems, use xdg-open.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51567959

http://stackoverflow.com/a/51626833
has body: So, by treating the input file as a .csv we can easily turn the lines into something easy to work with. For example, 2,Kenny Chong,Core Tech - Rendering, Durango &amp; PC,55,Reopened is read as: ['2', 'Kenny Chong', 'Core Tech - Rendering', 'Durango, PC', '55', 'Reopened'] Then, by replacing all instances of , with _&amp; (space) we would have the line: ['2', 'Kenny Chong', 'Core Tech - Rendering', 'Durango &amp; PC', '55', 'Reopened'] And it replaces multiple instances of ,s within a line, and when finally writing we no longer have the original double quotes. Here is the code, given that in.txt is your input file and it will write to out.txt. import csv with open('in.txt') as infile: reader = csv.reader(infile) with open('out.txt', 'w') as outfile: for line in reader: line = list(map(lambda s: s.replace(',', ' &amp;'), line)) outfile.write(','.join(line) + '\n') The fourth line is outputted as: LTY-168499,[PC][PS4][XB1] Missing textures from Fort Capture NPC face,3,CTU-CharacterTechBacklog,AAA - Character Tech &amp; SOF - UPIs,Durango &amp; Orbis &amp; PC,29,Waiting For
answers question: http://stackoverflow.com/q/51626343
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51626343
type: Answer
has comment: http://stackoverflow.com/comment/90218455
has comment: http://stackoverflow.com/comment/90218494
score: 2
upvote count: 2

http://stackoverflow.com/q/51485084
downvote count: 1
has comment: http://stackoverflow.com/comment/89939789
favorite count: 0
has comment: http://stackoverflow.com/comment/89939768
has body: I'm not a good good coder, but try to upgrade my skill and use good way for structure and pratice. I'm working on ML an use Keras. I try t find the best way to save my results. I got a model, scale parameter for x and y sims data, original features and Y. What is the best pratice to save all that info data? It is possible or good idea to save my model with my scale param togetter? I read csv and turn it to pandas DataFrame, it is better to save DataFrame to work directly with it next time or continu to read csv? Thank a lot for your suggestion an patience for a noob PS: sorry for my poor english, Im working on it too
has comment: http://stackoverflow.com/comment/89939398
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51485224
type: Question
accepted answer: http://stackoverflow.com/a/51487227
tagged with: keras
has answer: http://stackoverflow.com/a/51487227
has title: good pratice to save ML model with scaling and other info required for re-use
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51485224
upvote count: 1

http://stackoverflow.com/q/51485042
possible better answer: http://stackoverflow.com/a/58074847
has body: I'm trying to use set_printoptions from the answer to the question How to pretty-printing a numpy.array without scientific notation and with given precision? But I get this error: Traceback (most recent call last): File "neural_network.py", line 57, in &lt;module&gt; output.set_printoptions(precision=3) AttributeError: 'numpy.ndarray' object has no attribute 'set_printoptions' Apparently, not all numpy arrays are created equal, and what works for a regular numpy.array doesn't work for a numpy.ndarray. How can I format a numpy.ndarray for priting such as to remove scientific notation? UPDATE Changing the call to numpy.set_printoptions() removes the error, but has no effect on the print format of the ndarray contents.
tagged with: arrays
has comment: http://stackoverflow.com/comment/89939637
favorite count: 0
upvote count: 5
downvote count: 0
linked to: http://stackoverflow.com/q/2891790
has comment: http://stackoverflow.com/comment/89940192
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89939435
has answer: http://stackoverflow.com/a/58074847
has title: set_printoptions for numpy array doesn't work for numpy ndarray?
has answer: http://stackoverflow.com/a/51485352
accepted answer: http://stackoverflow.com/a/51485352
type: Question
tagged with: numpy
answer count: 2
score: 5

http://stackoverflow.com/comment/90196795
score: 0
has text: But it does the first 6 dataframes before falling over & it doesn't work without the to_frame bit.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51598416

http://stackoverflow.com/comment/90219490
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51627351
has text: Sure. But since I don't have the full code to test, I will add some pieces for you to debug or test :)
score: 1

http://stackoverflow.com/q/51599936
has comment: http://stackoverflow.com/comment/90167196
has body: I am creating an app to post products to a marketplace. Each product category on this marketplace has a different form for product attributes, for example if it's electronic there are fields for voltage, model number... I get this information via json through the marketplace server. First the user has to write the name of the product and it's main category and the marketplace server predicts their own category and returns to me it's attributes. Here's an example of the response: { "id": "MODEL", "name": "Modelo", "tags": { "hidden": true }, { "id": "PACKAGE_LENGTH", "name": "Comprimento da embalagem", "tags": { "hidden": true, "read_only": true, "variation_attribute": true }, "hierarchy": "ITEM", "relevance": 2, "value_type": "number_unit", "value_max_length": 255, "allowed_units": [ { "id": "km", "name": "km" }, { "id": "polegadas", "name": "polegadas" }, { "id": "ft", "name": "ft" }, { "id": "mm", "name": "mm" }, { "id": "m", "name": "m" }, { "id": "\"", "name": "\"" }, { "id": "in", "name": "in" }, { "id": "cm", "name": "cm" } ], "default_unit": "cm", "attribute_group_id": "OTHERS", "attribute_group_name": "Outros" } So far so good. Now I need to create a dynamic form to be able to add/edit those fields because each category has a different type of attribute, and different amount. Each field needs to have an ID, a type (could be string only, or numbers only) an label, and a max length and if its of value_type number_unit needs a SelectField with the given units. I'm getting this information in a view, and at the same view I create a subclass of a FlaskForm, where I create a list of fields based on the type of the attribute. class DynamicForm(PostProductForm): loaded_attr = json.loads(meli.get(f"/categories/{category}/attributes").content.decode('utf-8')) attribute_fields = [] for attribute in loaded_attr: tags = attribute.get('tags') if not tags.get('read_only'): if attribute.get('value_type') == 'number_unit': attribute_fields.append(IntegerField( attribute['nam…
has answer: http://stackoverflow.com/a/51606934
accepted answer: http://stackoverflow.com/a/51606934
answer count: 1
downvote count: 0
tagged with: flask
has comment: http://stackoverflow.com/comment/90166747
favorite count: 0
has title: How do I bind an flask-wtform UnboundField?
tagged with: python
linked to: http://stackoverflow.com/q/48697016
has comment: http://stackoverflow.com/comment/90167738
type: AnsweredQuestion
tagged with: dynamicform
tagged with: flask-wtforms
upvote count: 3
has comment: http://stackoverflow.com/comment/90168128
tagged with: jinja2
has comment: http://stackoverflow.com/comment/90167622
type: Question
score: 3

seaborn
tags question: http://stackoverflow.com/q/51502927
tags question: http://stackoverflow.com/q/51573606
tag name: seaborn
tags question: http://stackoverflow.com/q/51579215
tags question: http://stackoverflow.com/q/51557180
tags question: http://stackoverflow.com/q/51491487
tags question: http://stackoverflow.com/q/51566331
tags question: http://stackoverflow.com/q/51543359
tags question: http://stackoverflow.com/q/51639481
tags question: http://stackoverflow.com/q/51544577
tags question: http://stackoverflow.com/q/51513570
tags question: http://stackoverflow.com/q/51523852
tags question: http://stackoverflow.com/q/51518103
tags question: http://stackoverflow.com/q/51637246
tags question: http://stackoverflow.com/q/51551891
tags question: http://stackoverflow.com/q/51629256
tags question: http://stackoverflow.com/q/51568083
tags question: http://stackoverflow.com/q/51546293
tags question: http://stackoverflow.com/q/51501801
tags question: http://stackoverflow.com/q/51547442
tags question: http://stackoverflow.com/q/51550507
tags question: http://stackoverflow.com/q/51501708
tags question: http://stackoverflow.com/q/51571625
tags question: http://stackoverflow.com/q/51525284
type: Tag

http://stackoverflow.com/comment/90036460
type: QuestionComment
comment on: http://stackoverflow.com/q/51528295
score: 0
has text: Possible duplicate of [Issue installing Tensorflow -- not a CUDA/CuDNN issue](https://stackoverflow.com/questions/50430086/issue-installing-tensorflow-not-a-cuda-cudnn-issue)
type: Comment

http://stackoverflow.com/q/51526090
answer count: 3
has answer: http://stackoverflow.com/a/51526305
tagged with: datetime
has answer: http://stackoverflow.com/a/51526177
favorite count: 0
has comment: http://stackoverflow.com/comment/90020952
tagged with: time
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51529189
tagged with: gmt
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/51529189
downvote count: 0
has body: How to convert GMT time to string time? it's quite strange, when I print the time in back-end, the time is in string time format, but when I transfer it to the front-end via JSON file, the time has changed to GMT format. Why? Could someone help me? Input: Wed, 25 Jul 2018 19:19:42 GMT Output: 2018-07-25 19:19:42
has title: How to convert GMT time to string time
possible better answer: http://stackoverflow.com/a/51526305

http://stackoverflow.com/q/51536508
has comment: http://stackoverflow.com/comment/90040848
score: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/90040826
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51536704
accepted answer: http://stackoverflow.com/a/51536704
has comment: http://stackoverflow.com/comment/90040702
has title: Get lines where the condition of i and j match
favorite count: 0
has comment: http://stackoverflow.com/comment/90041027
upvote count: 1
tagged with: python
has body: Print each output once: f1=['part3_pl', 'part2_pl', 'part3_pl_to_p', 'part2_pl_to_p', 'part3_pl_to_p_lack', 'part2_pl_to_p_lack'] for i in f1: for j in f1: if i.endswith('pl') and j.endswith('pl_to_p'): print(i,j,i+'_output') Returns: part3_pl part3_pl_to_p part3_pl_output part3_pl part2_pl_to_p part3_pl_output part2_pl part3_pl_to_p part2_pl_output part2_pl part2_pl_to_p part2_pl_output I would like to print each line once. Correct output: part3_pl part3_pl_to_p part3_pl_output part2_pl part2_pl_to_p part2_pl_output
type: AnsweredQuestion

http://stackoverflow.com/q/51529545
has body: I am not sure how to use tolist to achieve the following. I have a dataframe like this: Param_1 Param_2 Param_3 -0.171321 0.0118587 -0.148752 1.93377 0.011752 1.9707 4.10144 0.0112963 4.06861 6.25064 0.0103071 5.83927 What I want is to create separate lists for each of the columns, the list name being the column label. I don't want to keep doing: Param_1 = df["Param_1"].values.tolist() Please let me know if there's a way to do this. Thanks.
tagged with: tolist
upvote count: 1
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/51529649
score: 1
has answer: http://stackoverflow.com/a/51529649
tagged with: dataframe
has answer: http://stackoverflow.com/a/51529623
has answer: http://stackoverflow.com/a/51529568
type: Question
answer count: 3
downvote count: 0
has title: Python Pandas | Create separate lists for each of the columns
favorite count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51529568
tagged with: python

http://stackoverflow.com/comment/89975561
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51499897
has text: @TobiasBrösamle afaik Python doesn't have tail call optimization
type: Comment

http://stackoverflow.com/q/51526720
has comment: http://stackoverflow.com/comment/90022666
type: Question
tagged with: teradata
tagged with: python
has body: I have a below query: import jaydebeapi,pandas as pd cursor = conn.cursor() cursor.execute('''INSERT INTO MD SELECT DISTINCT MD FROM viewshareddim.TMD_VIP WHERE STN_ID=? AND P_T in ? AND ID in ? AND C_ID = ?''', (MD[0],MD[1],MD[2],MD[3])) Values are: MD = [01,(02,05,06),(02,04,05),8] Tried to refer the solution provided here python list but not getting how I can implement the solution for my query. Would appreciate if any guidance can be provided. Tried this: INSERT INTO MD SELECT DISTINCT MD FROM viewshareddim.TMD_VIP WHERE STN_ID=(?) AND P_T in (?) AND ID in (?) AND C_ID = (?), (MD[0],MD[1],MD[2],MD[3]) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/jaydebeapi/__init__.py", line 499, in execute self._set_stmt_parms(self._prep, parameters) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/jaydebeapi/__init__.py", line 490, in _set_stmt_parms prep_stmt.setObject(i + 1, parameters[i]) RuntimeError: No matching overloads found for setObject in find. at native/common/jp_method.cpp:127
has title: Python: Passing list in sql query as parameters
score: 0
linked to: http://stackoverflow.com/q/283645
answer count: 1
has comment: http://stackoverflow.com/comment/90055017
has answer: http://stackoverflow.com/a/51527155
has comment: http://stackoverflow.com/comment/90022415
has comment: http://stackoverflow.com/comment/90024597
type: UnansweredQuestion
tagged with: sql

http://stackoverflow.com/comment/90119593
has text: @santosmarco_: Looks like the issue is the fact that the list in the `Station` constructor comes from a default argument. That's always going to use the same list object. Check out the answers in the duplicate question and you'll find how you can fix the issue.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51576862

http://stackoverflow.com/comment/90089609
score: 1
type: AnswerComment
has text: A "collimated lens" will re move depth perception, and can lead to correct measurements on screen, as another alternative.
type: Comment
comment on: http://stackoverflow.com/a/51561235

dataframe
tags question: http://stackoverflow.com/q/51548583
tags question: http://stackoverflow.com/q/51500889
tags question: http://stackoverflow.com/q/51558341
tags question: http://stackoverflow.com/q/51537673
tags question: http://stackoverflow.com/q/51499385
tags question: http://stackoverflow.com/q/51502263
tags question: http://stackoverflow.com/q/51559204
tags question: http://stackoverflow.com/q/51575420
tags question: http://stackoverflow.com/q/51608587
tags question: http://stackoverflow.com/q/51499723
tags question: http://stackoverflow.com/q/51483096
tags question: http://stackoverflow.com/q/51536641
tags question: http://stackoverflow.com/q/51618239
tags question: http://stackoverflow.com/q/51530947
tags question: http://stackoverflow.com/q/51526805
tags question: http://stackoverflow.com/q/51589210
tags question: http://stackoverflow.com/q/51513861
tags question: http://stackoverflow.com/q/51487444
tags question: http://stackoverflow.com/q/51594400
tags question: http://stackoverflow.com/q/51582031
tags question: http://stackoverflow.com/q/51536090
tags question: http://stackoverflow.com/q/51570764
tags question: http://stackoverflow.com/q/51509915
tags question: http://stackoverflow.com/q/51534522
tags question: http://stackoverflow.com/q/51522308
tags question: http://stackoverflow.com/q/51611378
tags question: http://stackoverflow.com/q/51523674
tags question: http://stackoverflow.com/q/51614511
tags question: http://stackoverflow.com/q/51544356
tags question: http://stackoverflow.com/q/51606538
tags question: http://stackoverflow.com/q/51620138
tags question: http://stackoverflow.com/q/51630140
tags question: http://stackoverflow.com/q/51577205
tags question: http://stackoverflow.com/q/51614014
tags question: http://stackoverflow.com/q/51515446
tags question: http://stackoverflow.com/q/51610726
tags question: http://stackoverflow.com/q/51601139
tags question: http://stackoverflow.com/q/51542880
tags question: http://stackoverflow.com/q/51566264
tags question: http://stackoverflow.com/q/51613505
tags question: http://stackoverflow.com/q/51611533
tags question: http://stackoverflow.com/q/51619245
tags question: http://stackoverflow.com/q/51527802
tags question: http://stackoverflow.com/q/51582764
tags question: http://stackoverflow.com/q/51526846
tags question: http://stackoverflow.com/q/51566566
tags question: http://stackoverflow.com/q/51495800
tags question: http://stackoverflow.com/q/51540495
tags question: http://stackoverflow.com/q/51583365
tags question: http://stackoverflow.com/q/51520410
tags question: http://stackoverflow.com/q/51623779
tags question: http://stackoverflow.com/q/51577648
tags question: http://stackoverflow.com/q/51595819
tags question: http://stackoverflow.com/q/51574119
tags question: http://stackoverflow.com/q/51528625
tags question: http://stackoverflow.com/q/51536159
tags question: http://stackoverflow.com/q/51576967
tags question: http://stackoverflow.com/q/51503848
tags question: http://stackoverflow.com/q/51619164
tags question: http://stackoverflow.com/q/51524909
tags question: http://stackoverflow.com/q/51622738
tags question: http://stackoverflow.com/q/51571121
tags question: http://stackoverflow.com/q/51540847
tags question: http://stackoverflow.com/q/51550341
tags question: http://stackoverflow.com/q/51546293
tags question: http://stackoverflow.com/q/51545651
tags question: http://stackoverflow.com/q/51576982
tags question: http://stackoverflow.com/q/51621945
tags question: http://stackoverflow.com/q/51564120
tags question: http://stackoverflow.com/q/51547857
tags question: http://stackoverflow.com/q/51537149
tags question: http://stackoverflow.com/q/51592393
tags question: http://stackoverflow.com/q/51591589
tags question: http://stackoverflow.com/q/51548416
tags question: http://stackoverflow.com/q/51573267
tags question: http://stackoverflow.com/q/51622604
tags question: http://stackoverflow.com/q/51621431
tags question: http://stackoverflow.com/q/51503770
tags question: http://stackoverflow.com/q/51490578
tags question: http://stackoverflow.com/q/51522019

3d-model
type: Tag
tag name: 3d-model
tags question: http://stackoverflow.com/q/51558072

http://stackoverflow.com/q/51606048
favorite count: 0
accepted answer: http://stackoverflow.com/a/51606730
tagged with: python
has title: Python Open CV overlay image on contour of a big image
tagged with: opencv
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90177569
type: Question
has answer: http://stackoverflow.com/a/51606730
downvote count: 0
has body: I have a big image of shape where i'm looking to overlap an image on a shape based on the contour I have this image I have this contur where it is detecting the shape and color of the image I want to place an image on this shape I want to custom resize the image Out Put Desired:- Code:- if color == "blue" and shape == "pentagon": A_img = cv2.imread("frame.png") print(A_img) x_offset=y_offset=50 B_img[y_offset:y_offset+A_img.shape[0], x_offset:x_offset+A_img.shape[1]] = A_img That code is not working the monkey is getting printed on the top left
has comment: http://stackoverflow.com/comment/90178331
answer count: 1

http://stackoverflow.com/q/51609917
has body: I am using expand and glob_wildcards in my snakamake script. I have two subdirectories in my directoty libraries with fastq forward and reverse files structured like follows : libraries: - MMETSP1: - SRR19_1 - SRR19_2 - MMETSP2: - SRR20_1 - SRR20_2 I am obtaining all the combinations possible in the two directories with the zip option of expand. But what i wanted is just a list of the forward files with comma seperated (ex: SRR19_1, SRR20_1) and and so for the reverse files (ex: SRR19_2, SRR20_2). And when i remove the zip option ia have this error: MissingInputException in line 159 of /projet/fr2424/sib/gniang/script/snakemake/scripts/dntap_test.py: Missing input files for rule trinity: /projet/fr2424/sib/gniang/script/snakemake/libraries/MMESTP1/SRR1300320_1.fastq.gz /projet/fr2424/sib/gniang/script/snakemake/libraries/MMESTP1/SRR1300320_2.fastq.gz /projet/fr2424/sib/gniang/script/snakemake/libraries/MMETSP2/SRR1300319_2.fastq.gz /projet/fr2424/sib/gniang/script/snakemake/libraries/MMETSP2/SRR1300319_1.fastq.gz I am using this script: #!/usr/bin/python # Imports import os import glob import sys # Get current working directory dir_path = os.getcwd() # User defined ouput directory OUT_DIR = config["directories"]["outdir"] # User defined input directory LIBRARY_DIR = config["directories"]["libraries"] # Relative output directories TRINITY_DIR = OUT_DIR + "trinity_out" # Wildcards for input files (LIBRARY, FASTQ, SENS) = glob_wildcards(LIBRARY_DIR + "{mmetsp}/{reads}_{type}.fastq.gz") # ALL rule all: input: trinity_out = TRINITY_DIR + "/Trinity.fasta", forward = directory(TRIMMOMATIC_DIR + "/forward.trimmomatic.paired.fastq"), reverse = directory(TRIMMOMATIC_DIR + "/reverse.trimmomatic.paired.fastq") # TRINITY: This rule is use to de novo assemble filtered FASTQ files into # contigs. rule trinity: input: forward = expand(LIBRARY_DIR + "{mmetsp}" + "/" + "{reads}_1.fastq.gz", mmetsp=LIBRARY, reads=FASTQ), reverse = expand(LIBRARY_DIR + "{mmetsp}" + "/" + "{reads}_2.fas…
answer count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90196117
score: 0
tagged with: snakemake
has comment: http://stackoverflow.com/comment/90261739
has comment: http://stackoverflow.com/comment/90201310
has comment: http://stackoverflow.com/comment/90195330
type: UnansweredQuestion
has title: Snakemake: Zip option in expand not working

http://stackoverflow.com/q/51494479
tagged with: tkinter
type: UnansweredQuestion
has body: Been stuck on this one for a while now please help as im bit of a noob none the less here is the code from tkinter import* ###title/info root = Tk() root.configure(background="black") root.title("C02 caculator") root.resizable(1,1) root.columnconfigure(0,weight=1) root.columnconfigure(1,weight=1) introtext = Label(root, text=" C02 Calculator \n" 'Made by: Ronan Shade \n' 'Date: 18/7/2018 \n ' "\n This calculator is made to find out the O/A c02 output from any given product, \n" "using a list of modified and combined formulas . Simply weigh (in grams) the \n" "wight of each core part of the product and determine what marital the part \n" "made of. Enter the findings into the calculator and it will give you a output.\n" "\n Data used to make the formula can be found at the following: \n" "http://www.lowtechmagazine.com/what-is-the-embodied-energy-of-materials.html \n" "https://www.unitjuggler.com/convert-energy-from-kgSKE-to-MJ.html \n" "https://carbonpositivelife.com/co2-per-kwh-of-electricity/ \n" "http://web.mit.edu/ebm/www/publications.htm \n" ,background="black",foreground="grey90") introtext.grid(row=1,column=0, sticky=E) root.mainloop() ### here is where the real work starts ### def final_calculation(): entryField.delete(0,'end') Steal = float(entrySteal.get()) Steal_recycled= float(entryRecycledSteal.get()) Wood = float(entryWood.get()) Aluminum_recycled = float(entryAluminumRrecycled.get()) Aluminum = float(entryAluminum.get()) Iorn = float(entryIron.get()) Glass = float(entryGlass.get()) Paper = float(entryPaper.get()) Plastics = float(entryPlastics.get()) Copper = float(entryCopper.get()) Silicon = float(entrySilicon.get()) Nickel = float(entryNickel.get()) Titanium = float(entryTitanium.get()) Electronic_grade_silicon= float(entryElectronicGradeSilicon.get()) output_wood = (Wood *wood_c02) output_steal = (Steal * steal_c02 ) output_Steal_recycled = (Steal_recycled*Steal_recycled_c02) output_Aluminum = (Aluminum*Aluminum_c02) output_Aluminum_recycled = (Alu…
tagged with: error-handling
type: Question
has comment: http://stackoverflow.com/comment/89970595
linked to: http://stackoverflow.com/q/4140437
linked to: http://stackoverflow.com/q/22402548
score: 0
answer count: 1
has title: Set Python3 input To a default number when no input is given
has comment: http://stackoverflow.com/comment/89957659
has answer: http://stackoverflow.com/a/51495051
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/89959663

http://stackoverflow.com/comment/89973015
score: 0
type: QuestionComment
type: Comment
has text: What do you see for `type(log_df['Product'])` ?
comment on: http://stackoverflow.com/q/51502263

http://stackoverflow.com/comment/90020836
has text: @DSM, yes, exactly!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51522976

http://stackoverflow.com/q/51567177
type: Question
has body: Python 3 I'm using Tkinter and am getting unexpected results. What I'm trying to do is have different labels, buttons, and entry boxes to better practice my little known Tkinter skills. This is my code: from tkinter import * def display_music(event): music = favoriteMusician.get() outputEntry.delete(0, 'end') outputEntry.insert(0, 'Your favorite musician is %s' % music) def divide(event): answer = str(int(num1Entry.get())/int(num2Entry.get())) divideEntry.delete(0, 'end') divideEntry.insert(0, answer) root = Tk() Label(root, text='Who is your favorite musician?').grid(row=0, column=0, sticky=W) favoriteMusician = Entry(root) favoriteMusician.grid(row=0, column=2, sticky=W) b1 = Button(root, text='Output:') b1.bind('&lt;Button-1&gt;', display_music) b1.grid(row=1, column=0, sticky=W) outputEntry = Entry(root) outputEntry.grid(row=1, column=1, columnspan=2, sticky=W) num1Entry = Entry(root) num1Entry.grid(row=2, column=0, sticky=W) Label(root, text='/').grid(row=2, column=1, sticky=W) num2Entry = Entry(root) num2Entry.grid(row=2, column=2, sticky=W) b2 = Button(root, text='=') b2.bind('&lt;Button-1&gt;', divide) b2.grid(row=2, column=3, sticky=W) divideEntry = Entry(root) divideEntry.grid(row=2, column=4, sticky=W) root.mainloop() But when I run the code. There are layout issues, I wish everything was aligned, but not everything is, and there are big spaces that I don’t know how to get rid of. Here's how it currently looks: I understand this has to do with Tkinter deciding the cell sizes (for grid()) based on the size of the existent cells. I have done research, but can't find answers. Aside from the answer, I would be fine with feedback on how to write better code, and also maybe some resources to learn python for free.
score: 0
accepted answer: http://stackoverflow.com/a/51572277
answer count: 2
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51572277
tagged with: python
possible better answer: http://stackoverflow.com/a/51571631
type: AnsweredQuestion
tagged with: tkinter
has answer: http://stackoverflow.com/a/51571631
has title: Gaps In Grid Spaces - TKInter

http://stackoverflow.com/a/51566093
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51565221
type: Answer
has comment: http://stackoverflow.com/comment/90103967
accepted answer of: http://stackoverflow.com/q/51565221
has body: A good old loop may be? s = ','.join(data.columns) + '\n,' for i in range(len(data.columns)): if i != len(data.columns) - 1: s = s + ','.join((data[data.columns[i]].values).astype(str)) + '\n' else: s = s + ','.join((data[data.columns[i]].values).astype(str)) You get 'a,b\n,A A,B B\n3,4'
has comment: http://stackoverflow.com/comment/90109292

http://stackoverflow.com/q/51613131
answer count: 1
has answer: http://stackoverflow.com/a/51621676
favorite count: 0
has body: I am trying to start my journey into building Python extension with SWIG, but I immediately find one error. Probably the solution is very simple, but I haven't found a solution yet. I would like to wrap a simple C add() function: /* sample.h */ extern int add(int, int); My sample.i file is: // sample.i - Swig interface %module sample %{ #include "sample.h" %} My setup.py file is: # setup.py from distutils.core import setup, Extension setup(name='sample', py_modules=['sample.py'], ext_modules=[ Extension('_sample', ['sample_wrap.c'], include_dirs = [], define_macros = [], undef_macros = [], library_dirs = [], libraries = ['sample'] ) ] ) Then I try to get the extension module compiled by running: python setup.py build_ext --inplace But I get an error from linker stating that sample.lib is missing.
type: UnansweredQuestion
score: -3
tagged with: python
downvote count: 3
type: Question
has title: build error with SWIG
tagged with: swig
upvote count: 0
has comment: http://stackoverflow.com/comment/90202320

http://stackoverflow.com/q/51635177
accepted answer: http://stackoverflow.com/a/51635247
favorite count: 0
has title: Is there any Python implementation of set() with key argument?
tagged with: python
has answer: http://stackoverflow.com/a/51635247
answer count: 4
possible better answer: http://stackoverflow.com/a/51635422
tagged with: set
upvote count: 17
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51635422
has body: Question I would like to know if there are any python functions that implement set() with a key argument, analogous to e.g. the key in sorted(iterable, *, key=None, reverse=False)? I think this feature would be useful for certain cases, especially when comparing custom objects without having to change its hash() function. Desired effect Example 1 iterable = [1.0, 1.5, 2.0, 2.5] x = set(iterable) # yields {1.0, 1.5, 2.0, 2.5} y = set(iterable, key=math.floor) # yields {1.0, 2.0} Example 2 iterable = ['abc', 'ade', 'bbc', 'abc', 'bfg'] x = set(iterable) # yields {'abc', 'ade', 'bbc', 'bfg'} y = set(iterable, key=lambda x: x[0]) # yields {'abc', 'bbc'} Which to choose I could imagine that this would not be implemented due to the difficulty of choosing which object is selected if a duplicate is found. However, this could be overcome by some strategy, e.g. 'choose first', 'choose random', 'choose last'. Answer Thank you for all of your responses, the most elegant solution for this problem was suggested by Daniel Roseman: key = math.floor # Or any desired key function y = set({key(i): i for i in iterable}.values())
score: 17
downvote count: 0
has answer: http://stackoverflow.com/a/51636313
has answer: http://stackoverflow.com/a/51635468

http://stackoverflow.com/q/51533163
has comment: http://stackoverflow.com/comment/90035362
type: Question
has comment: http://stackoverflow.com/comment/90036836
has comment: http://stackoverflow.com/comment/90037189
upvote count: 1
tagged with: python
has body: I have this list. I want to make a for loop that will use in a function combinations of these files in the list. I am not sure how to make these combinations that for each 'check' it will take the correct combination. The function if it wasn't for the loop it would look like this: erase('check3_dwg_Polyline','check3_dwg_Polyline_feat_to_polyg_feat_to_line','output_name') What I've tried: Here's the list. li=['check3_dwg_Polyline', 'check2_dwg_Polyline', 'check3_dwg_Polyline_feat_to_polyg',# this will not be needed to extracted 'check2_dwg_Polyline_feat_to_polyg',# &gt;&gt; &gt;&gt; 'check3_dwg_Polyline_feat_to_polyg_feat_to_line', 'check2_dwg_Polyline_feat_to_polyg_feat_to_line'] start with this: a=[li[i:i+3] for i in range(0, len(li), 3)] where returns: [['check3_dwg_Polyline', 'check2_dwg_Polyline', 'check3_dwg_Polyline_feat_to_polyg'], ['check2_dwg_Polyline_feat_to_polyg', 'check3_dwg_Polyline_feat_to_polyg_feat_to_line', 'check2_dwg_Polyline_feat_to_polyg_feat_to_line']] Finally: for base, base_f, base_line in a: print(base, base_line, base + "_output") gives: check3_dwg_Polyline check3_dwg_Polyline_feat_to_polyg check3_dwg_Polyline_output check2_dwg_Polyline_feat_to_polyg check2_dwg_Polyline_feat_to_polyg_feat_to_line check2_dwg_Polyline_feat_to_polyg_output Other method: base = [f for f in li if not f.endswith(("_polyg", "_to_line"))] base_f = {f.strip("_feat_to_polyg"): f for f in li if f.endswith("_polyg")} base_line = {f.strip("_feat_to_polyg_feat_to_line"): f for f in li if f.endswith("_to_line")} [(b, base_f[b], base_line[b]) for b in base] gives: KeyError: 'check3_dwg_Polyline' I have tried sorting the list but it just ruins it in a different way when put through the processes mentioned above. The ideal result is this when trying this: for base, base_f, base_line in a: print(base, base_line, base + "_output") to give this: check3_dwg_Polyline check3_dwg_Polyline_feat_to_polyg_feat_to_line check3_dwg_Polyline_output check2_dwg_Polyline check2_dwg_Polyline…
has comment: http://stackoverflow.com/comment/90034396
answer count: 1
has title: Get certain files from list by pattern
tagged with: list
has comment: http://stackoverflow.com/comment/90037031
has comment: http://stackoverflow.com/comment/90034804
score: 0
has comment: http://stackoverflow.com/comment/90034588
downvote count: 1
has comment: http://stackoverflow.com/comment/90034892
has comment: http://stackoverflow.com/comment/90035032
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1038824
has comment: http://stackoverflow.com/comment/90038356
has comment: http://stackoverflow.com/comment/90035587
has comment: http://stackoverflow.com/comment/90038156
has comment: http://stackoverflow.com/comment/90034475
has comment: http://stackoverflow.com/comment/90036357
has comment: http://stackoverflow.com/comment/90034502
has answer: http://stackoverflow.com/a/51535384
has comment: http://stackoverflow.com/comment/90034611
favorite count: 0

http://stackoverflow.com/a/51563853
score: 0
has comment: http://stackoverflow.com/comment/90102927
type: Answer
has body: dibery's answer looks great but since you tagged python as well I will provide a simple script that does your job. with open("file.xml", "r") as r: lines = r.readlines() gotcha = False # Just a flag to know if we catched the field with open("file.xml", "w") as w: for k in range(len(lines)): if ' ' in lines[k]: w.write(" \n') gotcha = False # We have done our job, this avoids commenting every other ' ' field Output some lines some lines
has comment: http://stackoverflow.com/comment/90115193
answers question: http://stackoverflow.com/q/51559363

http://stackoverflow.com/comment/90192636
type: AnswerComment
has text: @NI6 If you want to use `pip` another option would be to rename `mv setup.py setup_all.py` (as well as the `import` statements accordingly: `from setup_all import setup`) and then create a symlink before installing with pip: `ln -s setup_foo.py setup.py && pip install -e .`. pip always installs from `setup.py`, this is (at least *was*) apparently [hard coded](https://stackoverflow.com/a/38957066/3767239).
comment on: http://stackoverflow.com/a/51610734
type: Comment
score: 1

http://stackoverflow.com/comment/90162811
score: 0
type: Comment
has text: thank you a lot, that helped, and my apologies for the inconvenience regarding format..
type: AnswerComment
comment on: http://stackoverflow.com/a/51597896

http://stackoverflow.com/comment/90205097
has text: In Python 3.8 you will have assignment expressions: https://www.python.org/dev/peps/pep-0572/
comment on: http://stackoverflow.com/q/51619754
type: QuestionComment
type: Comment
score: 1

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/51637222
tags question: http://stackoverflow.com/q/51623226
tags question: http://stackoverflow.com/q/51597380
tags question: http://stackoverflow.com/q/51518279
tags question: http://stackoverflow.com/q/51613969
tags question: http://stackoverflow.com/q/51488199
type: Tag
tags question: http://stackoverflow.com/q/51608952
tags question: http://stackoverflow.com/q/51506508
tags question: http://stackoverflow.com/q/51533765
tags question: http://stackoverflow.com/q/51613845
tags question: http://stackoverflow.com/q/51541377
tags question: http://stackoverflow.com/q/51600579
tags question: http://stackoverflow.com/q/51549424
tags question: http://stackoverflow.com/q/51620610
tags question: http://stackoverflow.com/q/51573592

scikit-learn
tags question: http://stackoverflow.com/q/51622144
tags question: http://stackoverflow.com/q/51636617
tags question: http://stackoverflow.com/q/51538375
tags question: http://stackoverflow.com/q/51541943
tags question: http://stackoverflow.com/q/51483951
tags question: http://stackoverflow.com/q/51515165
tags question: http://stackoverflow.com/q/51613425
tags question: http://stackoverflow.com/q/51503889
tags question: http://stackoverflow.com/q/51540214
tags question: http://stackoverflow.com/q/51543158
tags question: http://stackoverflow.com/q/51544794
tags question: http://stackoverflow.com/q/51632697
tags question: http://stackoverflow.com/q/51629153
tags question: http://stackoverflow.com/q/51487682
tags question: http://stackoverflow.com/q/51600829
tags question: http://stackoverflow.com/q/51607239
tags question: http://stackoverflow.com/q/51627721
tags question: http://stackoverflow.com/q/51545562
tags question: http://stackoverflow.com/q/51531255
tags question: http://stackoverflow.com/q/51571488
tags question: http://stackoverflow.com/q/51482918
tags question: http://stackoverflow.com/q/51521351
tags question: http://stackoverflow.com/q/51614938
tags question: http://stackoverflow.com/q/51498712
tag name: scikit-learn
tags question: http://stackoverflow.com/q/51502950
tags question: http://stackoverflow.com/q/51528579
tags question: http://stackoverflow.com/q/51487549
tags question: http://stackoverflow.com/q/51549641
tags question: http://stackoverflow.com/q/51622522
type: Tag
tags question: http://stackoverflow.com/q/51598382
tags question: http://stackoverflow.com/q/51497938
tags question: http://stackoverflow.com/q/51636330
tags question: http://stackoverflow.com/q/51485167
tags question: http://stackoverflow.com/q/51618576
tags question: http://stackoverflow.com/q/51582726
tags question: http://stackoverflow.com/q/51627218
tags question: http://stackoverflow.com/q/51576272
tags question: http://stackoverflow.com/q/51552438
tags question: http://stackoverflow.com/q/51636383
tags question: http://stackoverflow.com/q/51527725
tags question: http://stackoverflow.com/q/51619180
tags question: http://stackoverflow.com/q/51510679
tags question: http://stackoverflow.com/q/51621307
tags question: http://stackoverflow.com/q/51523999
tags question: http://stackoverflow.com/q/51497681
tags question: http://stackoverflow.com/q/51525043
tags question: http://stackoverflow.com/q/51613004
tags question: http://stackoverflow.com/q/51527163
tags question: http://stackoverflow.com/q/51495819

http://stackoverflow.com/q/51613385
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90191902
tagged with: email
tagged with: ms-office
has comment: http://stackoverflow.com/comment/90192727
has title: socket.error: [Errno 10060]: Unable send an email from outlook using python
has answer: http://stackoverflow.com/a/51631005
tagged with: python
has comment: http://stackoverflow.com/comment/90191978
type: AnsweredQuestion
has body: I've below code which was working fine for months. Now, it is giving me the error below, socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond sender = 'myemail@email.com' receiver = ['myemail@email.com',] msg = MIMEMultipart() print("Sending an email to {} ...".format(receiver)) msg['From'] = sender msg['To'] = ", ".join(receiver) msg['Subject'] = 'Automation Testing' body = 'Hello,' msg.attach(MIMEText(body, 'plain')) # filename = 'Fidelity-Success' + timestamp + '.png' attachment = open('C:\\mydrive\\{}'.format(filename), 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) # part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= " + filename) msg.attach(part) server = smtplib.SMTP('mail.email.com', 587, timeout=120) #server = smtplib.SMTP_SSL('mail.email.com', 93, timeout=120) server.starttls() server.login(sender, "password") text = msg.as_string() server.sendmail(sender, receiver, text) # server.quit() time.sleep(4) print("Email sent.") I tried various ports and timeout but no luck. I am not sure why it stopped working all of a sudden. Any help is really appreciated.
has comment: http://stackoverflow.com/comment/90192342
score: 0
type: Question
tagged with: outlook
has comment: http://stackoverflow.com/comment/90192586
accepted answer: http://stackoverflow.com/a/51631005
answer count: 1

http://stackoverflow.com/a/51593250
answers question: http://stackoverflow.com/q/51593227
has comment: http://stackoverflow.com/comment/90152167
score: 0
type: Answer
has body: you need to import Sample from the other file and then call Sample. calculate

http://stackoverflow.com/a/51486313
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51486233
has body: concurrent.futures is not specifically thread based (there are thread and process based executors available), nor is it specifically about async I/O; it's general parallelism. You could parallelize I/O with it, but it's the worker tasks that are async, with the I/O being a specific thing that can be parallelized. As it happens, for I/O, you would want to use the ThreadPoolExecutor; CPython's GIL isn't a problem for I/O bound tasks, and the IPC necessary to return results from a ProcessPoolExecutor's worker processes would largely eliminate the benefits of parallelizing the I/O. I just wanted to be clear that concurrent.futures is not purely about threads. POSIX AIO is, at least on Linux, just a user space library wrapping threads (roughly equivalent to using concurrent.futures.ThreadPoolExecutor to perform your I/O tasks), per the NOTES in the man page you linked: The current Linux POSIX AIO implementation is provided in user space by glibc. This has a number of limitations, most notably that maintaining multiple threads to perform I/O operations is expensive and scales poorly. Work has been in progress for some time on a kernel state-machine-based implementation of asynchronous I/O (see io_submit(2), io_setup(2), io_cancel(2), io_destroy(2), io_getevents(2)), but this implementation hasn't yet matured to the point where the POSIX AIO implementation can be completely reimplemented using the kernel system calls. Point is, in both cases, it's fundamentally about dispatching I/O requests in background threads with handles of some sort to allow polling and retrieval of results. Kernel supported async I/O could avoid or limit threading by any of the following: Internally managing the I/O request queues, perhaps merely dispatching them serially, working with the disk driver to order the requests such that the head seeks across them and pulls them efficiently Dispatching in parallel, and responding to device interrupts to signal completion Using a shared thread pool (simil…
has comment: http://stackoverflow.com/comment/89942040
accepted answer of: http://stackoverflow.com/q/51486233

http://stackoverflow.com/comment/90123014
has text: All of them (the content from all the charts) are perfectly coming through. You are the wizard sir Andersson!!
type: Comment
comment on: http://stackoverflow.com/a/51578860
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89965423
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51498159
has text: OK, try test it by `np.random.seed(123) N = 1000000 L = list('abcde') df = pd.DataFrame({'diff': np.random.randint(10000,size=N), 'window':np.random.randint(10000,size=N)}) df = df.sort_values(['window','diff']).set_index(['window'])`
type: AnswerComment

http://stackoverflow.com/comment/90004592
score: 0
has text: Thank you very much
type: Comment
comment on: http://stackoverflow.com/q/51495819
type: QuestionComment

http://stackoverflow.com/comment/90066502
type: QuestionComment
score: 1
has text: Related, but not sure if it's a dup: [Strings in BigEndianStructure](https://stackoverflow.com/questions/17559176/strings-in-bigendianstructure/17559594#17559594)
comment on: http://stackoverflow.com/q/51549340
type: Comment

http://stackoverflow.com/q/51548416
has title: How do I convert a PivotTable that was made into Pandas / Numpy in a DataFrame?
tagged with: numpy
tagged with: dataframe
type: UnansweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/90064717
has answer: http://stackoverflow.com/a/51548561
type: Question
tagged with: pivot-table
score: 0
has body: In python3 and pandas I have this dataframe: despesas_atuais_final.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 82318 entries, 0 to 82317 Data columns (total 18 columns): Ano 82318 non-null object CNPJ 82318 non-null object Deputado 82318 non-null object Fornecedor 82318 non-null object Matricula 82318 non-null int64 Mes 82318 non-null int64 Tipo 82318 non-null object Valor 82318 non-null float64 cnpj_raiz_fornecedor 82318 non-null object codigo_unico 82318 non-null object nome_deputado 82318 non-null object uf 82318 non-null object nome_completo 82318 non-null object sequencial 82318 non-null object cpf 82318 non-null object nome_urna 82318 non-null object partido_eleicao 82318 non-null object situacao 82318 non-null object dtypes: float64(1), int64(2), object(15) memory usage: 11.9+ MB The column "Valor" are expense values. The column "nome_deputado" has names of people who made expenses. The "Ano" is the year of the expense. And "Mes" is the month of the expense, in numbers. I made a PivotTable to know how much each person's monthly expenditure each year: pd.pivot_table(despesas_atuais_final,index=["nome_deputado","Ano", "Mes"], values=["Valor"], aggfunc=np.sum) Valor nome_deputado Ano Mes ABELARDO CAMARINHA 2015 3 3,345.40 4 4,843.97 5 15,738.48 6 18,245.08 7 23,953.70 8 27,587.43 9 27,058.59 10 24,117.43 11 20,984.07 2016 2 12,008.00 3 28,415.86 4 24,187.94 5 27,776.08 6 26,755.00 7 26,478.03 8 29,930.60 ... Please, there is a way to turn this PivotTable into a dataframe? Like this: nome_deputado Ano Mes Valor ABELARDO CAMARINHA 2015 3 3,345.40 ABELARDO CAMARINHA 2015 4 4,843.97 ABELARDO CAMARINHA 2015 5 15,738.48 ...
tagged with: python
answer count: 1

http://stackoverflow.com/comment/90117430
type: Comment
type: QuestionComment
has text: >`def _train_input_fn(): return input_fn(record_file="C:/Users/Desktop/cnn/record/train.record", batch_size=32, num_epochs=50, shuffle=True)` >`def _eval_input_fn(): return input_fn( record_file="C:/Users/Desktop/cnn/record/evaluate.record", batch_size=2, num_epochs=1, shuffle=False)` >`def _predict_input_fn(): return input_fn( record_file='C:/Users/Desktop/cnn/record/test.record', batch_size=2, num_epochs=1, shuffle=False)`
comment on: http://stackoverflow.com/q/51569370
score: 0

http://stackoverflow.com/comment/89978186
has text: Thanks, that was helpful! The 'my_id' variable is found inside a function I defined. When I try to call it in the URL it say that 'my_id' is not defined. What should I do to make the value of 'my_id' the same from inside and outside the function?
comment on: http://stackoverflow.com/a/51504354
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51553324
has comment: http://stackoverflow.com/comment/90073714
has body: You should only call random.seed(0) once in the program. By seeding every time you are reseting the pseudo random number generator and forcing it to produce the same number. random.seed(0) while(True): if bet == 0: #a bet of $0 ends the program ... You can read more about random seeding here.
has comment: http://stackoverflow.com/comment/90073644
type: Answer
has comment: http://stackoverflow.com/comment/90073763
answers question: http://stackoverflow.com/q/51553280
score: 0

http://stackoverflow.com/comment/90045337
comment on: http://stackoverflow.com/a/51529325
type: AnswerComment
has text: Thank your for your reply, however, I am not looking specifically into PB, this is just one example given in the twisted developer guideline that I wanted some further information for.
score: 0
type: Comment

http://stackoverflow.com/comment/90124011
type: AnswerComment
comment on: http://stackoverflow.com/a/51576892
type: Comment
has text: Awesome answer! I would upvote if I could. TYSM, I'll get on finding a new source
score: 0

http://stackoverflow.com/a/51529724
accepted answer of: http://stackoverflow.com/q/51529641
score: 5
has body: You can't pass a table name as a parameter to cursor.execute(). Whenever a parameter is a string it quotes it when it substitutes into the query. Use a normal string formatting method, e.g. cursor.execute("SELECT * FROM %(tablename)s" % {"tablename": "activity"})
upvote count: 5
has comment: http://stackoverflow.com/comment/117534831
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51529641
type: Answer

http://stackoverflow.com/comment/90065314
type: Comment
comment on: http://stackoverflow.com/q/51548652
type: QuestionComment
score: 0
has text: How big is the zip file? Recommendation, break out the zip processing from Lambda as a function. You can then add the Lambda front end to call your function. This way you can test on your desktop first.

http://stackoverflow.com/q/51505468
has answer: http://stackoverflow.com/a/51505551
accepted answer: http://stackoverflow.com/a/51505592
has title: Python dictionaries: why and when I have to use sometimes ":" and sometimes "=" between the key and the value?
has body: I am studying the use of dictionaries in Python and I am getting more and more confusing about the symbol I have to use to separate the key from the value, as well as the "" for the key. Normally, I write something like: user = {"name": "John", "surname": "Doe", "age": 34, "gender": "Male"} However, why Have I to write: user = dict(name="Jack") ...with an "=" between the key (written without " ") and the value? I have another example: def favourite_colour (**args): for name, colour in args.items(): print (f"{person}'s favourite colour is {colour}.") favourite_colour(Jude="green", Giulio="orange", Chiara="black") Is there a logic explanation, please?
tagged with: python
favorite count: 0
tagged with: python-3.x
downvote count: 2
tagged with: dictionary
has answer: http://stackoverflow.com/a/51505592
type: AnsweredQuestion
upvote count: 3
score: 1
type: Question
possible better answer: http://stackoverflow.com/a/51505551
answer count: 2

http://stackoverflow.com/q/51525961
answer count: 4
has comment: http://stackoverflow.com/comment/90020689
type: AnsweredQuestion
has title: How to count unique words from a text file after a specific string in every line?
has answer: http://stackoverflow.com/a/51526049
has body: Python-noob here: I have a text file that looks like this: {'{http://www.omg.org/XMI}id': '18836', 'sofa': '12', 'begin': '27', 'end': '30', 'Character': 'Jonathan'} {'{http://www.omg.org/XMI}id': '18836', 'sofa': '12', 'begin': '27', 'end': '30', 'Character': 'Jonathan'} {'{http://www.omg.org/XMI}id': '18828', 'sofa': '12', 'begin': '31', 'end': '37', 'Character': 'Joyce'} {'{http://www.omg.org/XMI}id': '18828', 'sofa': '12', 'begin': '31', 'end': '37', 'Character': 'Joyce'} {'{http://www.omg.org/XMI}id': '18918', 'sofa': '12', 'begin': '81', 'end': '95', 'Character': 'Will'} {'{http://www.omg.org/XMI}id': '19012', 'sofa': '12', 'begin': '155', 'end': '158', 'Character': 'Jonathan'} {'{http://www.omg.org/XMI}id': '19050', 'sofa': '12', 'begin': '239', 'end': '242', 'Character': 'Nancy'} {'{http://www.omg.org/XMI}id': '19111', 'sofa': '12', 'begin': '845', 'end': '850', 'Character': 'Steve'} etc. I would like to be able to count the unique characters' names and count each of their occurances. As in: ignore everything in every line until the string 'Character': and therefore considering only the character's name. So far I have this code, after trying many other approaches, including RegEx, but without the wanted results (it prints and counts everything): import re from collections import Counter import tkFileDialog filename = tkFileDialog.askopenfilename() f = open(filename, "r") lines = f.readlines() f.close() cnt = Counter() for line in lines: cnt[line.split("'Character':", 2)] +=1 print cnt print sum(cnt.values()) An optimal output would be like so: Jonathan: 3 Joyce: 2 Will: 1 Nancy: 1 Steve: 1 Any kind of help or hints would be appreciated! EDIT: The text file above was generated from an .xmi file that has information in a way that is not easily readable. As I mentioned in a comment for one of the answers below: This was my first-try approach to represent wanted combined information visually. I am not sure if there's a better way to represent such data other tha…
tagged with: file
has comment: http://stackoverflow.com/comment/90021179
has comment: http://stackoverflow.com/comment/90020702
type: Question
has comment: http://stackoverflow.com/comment/90020733
score: 0
has comment: http://stackoverflow.com/comment/90021003
accepted answer: http://stackoverflow.com/a/51526049
has answer: http://stackoverflow.com/a/51528664
possible better answer: http://stackoverflow.com/a/51526171
tagged with: unique
has answer: http://stackoverflow.com/a/51526171
has comment: http://stackoverflow.com/comment/90020930
has answer: http://stackoverflow.com/a/51526014
tagged with: count
tagged with: python
tagged with: regex

http://stackoverflow.com/a/55111310
score: 1
type: Answer
upvote count: 1
has body: I had a similar problem.. the system can't find the specific files. After I print out the exact file name string read by the system, I found out that there are some '\n' in the file name... Problem solved after I do line.rstrip() .
answers question: http://stackoverflow.com/q/51567728
downvote count: 0

http://stackoverflow.com/comment/90165200
has text: That's awesome thank you :) I don't know why I didn't think of this solution as it's fairly obvious. I suppose I was stuck on making requests to my server with get instead of using built in scrapy function. `response.body_as_unicode()` was a new one to me thank you. I have a couple questions. Why did you set `priority=-100` in the requests? And instead of using `yield {'scrapy':'item'}` I am creating an additional request to server with get and a payload parameter.. How can I send the dict back to the server using a yield statement and possibly another function? Thank you :)
type: Comment
comment on: http://stackoverflow.com/a/51586754
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89945924
score: 0
type: Comment
type: QuestionComment
has text: You don't seem to have actually configured a test suite in your `setup.py`.
comment on: http://stackoverflow.com/q/51488471

http://stackoverflow.com/comment/90010849
type: QuestionComment
type: Comment
has text: It would tell you how many results there were, yes. DynamoDB is not like a traditional database though. Your speed is limited by your throughput. Is doesn't matter if you return the whole items or the count, the throughput is the same. So just returning Count won't make your Query faster.
comment on: http://stackoverflow.com/q/51506863
score: 0

http://stackoverflow.com/comment/90126625
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51567190
has text: `shell=/bin/bash` `shellcmdflag=-c`

http://stackoverflow.com/comment/90068861
comment on: http://stackoverflow.com/q/51550781
score: 0
type: QuestionComment
type: Comment
has text: What are you expecting it to do? Don't expect anyone to go off-site to answer your question.

http://stackoverflow.com/comment/90386405
has text: Any update to this question? I get the same error message.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51514246
score: 1

http://stackoverflow.com/q/51533808
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90037368
score: 0
has body: I have a made a function in which I am taking value from user and want to send that value to another function for verification. But the problem is that I am unable to take value from user because that part of code is not running. The interpreter takes me directly to else part of the while loop. Here is my code: from userAccountDatabase import * FirstName = "" LastName = "" dateOfBirth = "" userDetails = [] def userDetailsValidation(fieldvalue, fieldName, database): for entry in database: if fieldName in entry and entry[fieldName] == fieldvalue: print("correct value") return True else: return False def userInputs(FirstName, LastName, dateOfBirth): FirstName = str(input("Enter First Name").upper()) # This part of code is not running while True: if(userDetailsValidation(FirstName, "FirstName", userAccountDetails)) == True: userDetails.append(FirstName) break # directly take me to this else: print('Enter valid First Name') FirstName = str(input("Enter First Name").upper()) userInputs(FirstName, LastName, dateOfBirth)
tagged with: loops
has comment: http://stackoverflow.com/comment/90037960
has comment: http://stackoverflow.com/comment/90037691
has comment: http://stackoverflow.com/comment/90038661
has comment: http://stackoverflow.com/comment/90037494
has comment: http://stackoverflow.com/comment/90035215
tagged with: function
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90035221
has comment: http://stackoverflow.com/comment/90038256
has comment: http://stackoverflow.com/comment/90037870
has comment: http://stackoverflow.com/comment/90035220
type: Question
has title: Unable to take input from user in python
tagged with: python

http://stackoverflow.com/a/51622244
score: 0
has body: Assuming from gurobipy import * m = Model() If you create a gurobi tupledict for your variables with x = m.addVars(nx, vtype=GRB.INTEGER, name="x") y = m.addVars(ny, vtype=GRB.INTEGER, name="y") # ...your constraints and objective here.. then you can directly call the attributes for your variables (in your case the .X attribute for the variable value in the current solution). Using a list comprehension it could be done with: m.optimize() if m.status == GRB.OPTIMAL: indices = [i for i in range(ny) if y[i].X &gt; 0] where nx and ny are the number of your variables.
type: Answer
answers question: http://stackoverflow.com/q/51487704

http://stackoverflow.com/q/51567190
has answer: http://stackoverflow.com/a/51582486
accepted answer: http://stackoverflow.com/a/51582486
answer count: 1
has comment: http://stackoverflow.com/comment/90126625
tagged with: shell
tagged with: macos
has body: In my macOS environment, my locale environment variables include an encoding $ locale LANG="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_CTYPE="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_ALL="en_US.UTF-8" However, if I open vim then run locale, the encoding is missing! :!locale LANG="en_US" LC_COLLATE="en_US" LC_CTYPE="en_US" LC_MESSAGES="en_US" LC_MONETARY="en_US" LC_NUMERIC="en_US" LC_TIME="en_US" LC_ALL="en_US" Press ENTER or type command to continue This causes a problem when running python programs from vim return io.open(self.dotenv_path) E LookupError: unknown encoding: Looking for ideas on how to fix vim's behavior so that it no longer strips the encoding information from the environment
has comment: http://stackoverflow.com/comment/90106224
tagged with: python
tagged with: vim
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90126670
tagged with: encoding
score: 0
has title: macOS vim locale different than shell

http://stackoverflow.com/a/51562787
answers question: http://stackoverflow.com/q/51547926
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51547926
has body: I know is insane to store files in mysql, but I only work as a monkey code in this project. Finally i used MYSQL LOAD_FILE() function I uploaded my jpgs to the server and imported to mysql using: MYSQL LOAD_FILE() There are thoundsands of files to uplodad, so I created a python script to create the sql code and store it in sql file. # coding=utf-8 #! python3 # crea el comando mysql para importar los archivos .jpg a mysql # para cada libro crea un archivo sql # para cada archivo crea un comando insert # INSERT INTO archivo SET libro_fk =,orden =,nombre =,archivo =,mime_type ="image/jpeg",numero_pagina =,libro_completo =0; import os libros = [ "K0LEM", "K3J2S" ] ids = [ "2390", "2399" ] total = len(libros) #para cada libro... for i in range(total): #crearemos un archivo sql para cada libro archivo_destino = ".\\archivos_sql\\" + ids[i] + ".sql" archivo = open(archivo_destino, 'w') carpeta_a_explorar = ".\\libros_nuevos_jpg\\" + libros[i] + "\\" archivos = os.listdir(carpeta_a_explorar) #crear una lista con los archivos archivos.sort() #ordena la lista cuantos_archivos = len(archivos) #cuantos archivos # # para cada archivo encontrado se creara un insert... # for jpg_file in range(cuantos_archivos): archivo.write("INSERT INTO archivo SET libro_fk ="+ ids[i] +",orden = "+str(jpg_file)+",nombre ='"+ archivos[jpg_file] +"',archivo = LOAD_FILE('/var/lib/mysql-files/"+ libros[i] +"/"+ archivos[jpg_file] +"'),mime_type ='image/jpeg',numero_pagina = "+str(jpg_file)+",libro_completo =0;") archivo.write("\n") archivo.close() The result is a sql file with an insert command per line using MYSQL LOAD_FILE() INSERT INTO archivo SET libro_fk =2390,orden = 0,nombre ='000.jpg',archivo = LOAD_FILE('/var/lib/mysql-files/K0LEM/000.jpg'),mime_type ='image/jpeg',numero_pagina = 0,libro_completo =0; INSERT INTO archivo SET libro_fk =2390,orden = 1,nombre ='001.jpg',archivo = LOAD_FILE('/var/lib/mysql-files/K0LEM/001.jpg'),mime_type ='image/jpeg',numero_pagina = 1,libro_completo =0; INSERT I…

http://stackoverflow.com/a/51636791
answers question: http://stackoverflow.com/q/51636068
upvote count: 2
has body: the pass instruction will be justified in something like this: class MyException(Exception): pass Or when writing tests, while the functionality is not yet ready. In my opinion, for readability, you always need to get rid of unnecessary branches. And the code: age = 32 if age &gt; 30: print("You are older than 30") looks much better and more readable.
has comment: http://stackoverflow.com/comment/90237982
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90067911
has text: try to re-build the container/image
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51550260

http://stackoverflow.com/q/51557613
has comment: http://stackoverflow.com/comment/90083628
tagged with: hdf
has comment: http://stackoverflow.com/comment/90087172
has comment: http://stackoverflow.com/comment/90083517
has comment: http://stackoverflow.com/comment/90082068
answer count: 3
tagged with: pyhdf
has comment: http://stackoverflow.com/comment/90082000
has comment: http://stackoverflow.com/comment/90103805
accepted answer: http://stackoverflow.com/a/51572065
downvote count: 0
score: 1
favorite count: 0
has body: I have a hdf file and want to extract data from it. For some reason i cant able to extract latitude and longitude values: the code that i tried is : from pyhdf import SD hdf = SD.SD('MOD10C2.A2001033.006.2016092173057.hdf') data = hdf.select('Eight_Day_CMG_Snow_Cover') lat = (hdf.select('Latitude'))[:] it gives me an error: HDF4Error: select: non-existent dataset I tried with: lat = (hdf.select('Lat'))[:] still does not help! data can be found in this link any help will be highly appreciated! data format looks like: and the error I got is: --------------------------------------------------------------------------- HDF4Error Traceback (most recent call last) ~/anaconda3/lib/python3.6/site-packages/pyhdf/SD.py in select(self, name_or_index) 1635 try: -&gt; 1636 idx = self.nametoindex(name_or_index) 1637 except HDF4Error: ~/anaconda3/lib/python3.6/site-packages/pyhdf/SD.py in nametoindex(self, sds_name) 1528 sds_idx = _C.SDnametoindex(self._id, sds_name) -&gt; 1529 _checkErr('nametoindex', sds_idx, 'non existent SDS') 1530 return sds_idx ~/anaconda3/lib/python3.6/site-packages/pyhdf/error.py in _checkErr(procName, val, msg) 22 err = "%s : %s" % (procName, msg) ---&gt; 23 raise HDF4Error(err) HDF4Error: nametoindex : non existent SDS During handling of the above exception, another exception occurred: HDF4Error Traceback (most recent call last) &lt;ipython-input-11-21e6a4fdf8eb&gt; in &lt;module&gt;() ----&gt; 1 hdf.select('Lat') ~/anaconda3/lib/python3.6/site-packages/pyhdf/SD.py in select(self, name_or_index) 1636 idx = self.nametoindex(name_or_index) 1637 except HDF4Error: -&gt; 1638 raise HDF4Error("select: non-existent dataset") 1639 id = _C.SDselect(self._id, idx) 1640 _checkErr('select', id, "cannot execute") HDF4Error: select: non-existent dataset
has comment: http://stackoverflow.com/comment/90097845
possible better answer: http://stackoverflow.com/a/58867234
has answer: http://stackoverflow.com/a/58867234
has comment: http://stackoverflow.com/comment/90103687
tagged with: python
has comment: http://stackoverflow.com/comment/90103737
has title: lat,lon information from hdf file python
has comment: http://stackoverflow.com/comment/90085739
linked to: http://stackoverflow.com/q/49670685
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90103767
has comment: http://stackoverflow.com/comment/90103628
has comment: http://stackoverflow.com/comment/90103887
upvote count: 1
has comment: http://stackoverflow.com/comment/90548236
has answer: http://stackoverflow.com/a/51572065
has answer: http://stackoverflow.com/a/64601471
has comment: http://stackoverflow.com/comment/90103733
type: Question

http://stackoverflow.com/comment/90046436
type: Comment
has text: @AdrienPacifico, I added a separate solution if you wish to use categorical data.
type: AnswerComment
comment on: http://stackoverflow.com/a/51536792
score: 0

http://stackoverflow.com/q/51547926
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51562787
tagged with: mysql
tagged with: http://stackoverflow.com/tag/jpeg
downvote count: 1
type: Question
score: -1
has comment: http://stackoverflow.com/comment/90063686
has comment: http://stackoverflow.com/comment/90064393
accepted answer: http://stackoverflow.com/a/51562787
has title: Convert jpg images to blob and store it in a .sql file
has comment: http://stackoverflow.com/comment/90064089
upvote count: 0
answer count: 1
has body: I store jpg images into a mysql database. I use the BLOB type to store the jpg images in the mysql database. I use mysqldump to generate a .sql file. I use the .sql file as backup and restore the database. How can I convert a jpg directly to a .sql file? I have tried this python code: import os import base64 archivo_destino = ".\\portada_sql\\archivo.sql" imagen_origen = ".\\libros_nuevos_jpg\\03000\\000.jpg" archivo = open(archivo_destino, 'w') imageFile = open(imagen_origen, "rb") mi_blob = base64.b64encode(imageFile.read()) archivo.write("INSERT INTO libro_portada VALUES ('"+mi_blob+"');") archivo.close() But it does not work. It is possible to create a sql file with a image stored as blob usign python? I try to avoid: upload the jpg to the server import jpg to mysql export mysql to .sql file I want to generate directly the .sql file. It is possible? 1. Magnus: I mentioned php because I can use php too, if this is possible with php. 2. Eric: From the python code mentioned above, I get: INSERT INTO libro_portada VALUES ('b'/9j/4RivRXhpZgAATU0AKgAAAAgABwESAAMAAAABAAEAAAE''); From mysqldump I get: INSERT INTO libro_portada VALUES ('ÿ\؀ÿ\ကJExif\0\0MM\0*\0\0\0\0\0\0\0\0\0\0\0\Z\0\0\0\0\0\0\0b');
has comment: http://stackoverflow.com/comment/90065738
has comment: http://stackoverflow.com/comment/90064156
has comment: http://stackoverflow.com/comment/90063811
favorite count: 0
tagged with: python
tagged with: php

http://stackoverflow.com/comment/89949076
comment on: http://stackoverflow.com/a/51490012
type: AnswerComment
type: Comment
has text: @AdamSmith The last thing I will say is that the answer should not only serve the asker but the community, and many take as a basis the answers of users with high reputation, if you take my advice or not your decision, goodbye :)
score: 0

http://stackoverflow.com/a/51488826
score: 1
type: Answer
upvote count: 1
has body: well if you are using windows you could try using python windows API to detect a key press. pip install pypiwin32 import win32api def keypress(key): state = win32api.GetAsyncKeyState(ord(key)) if(state &lt; 0 or state == 1): return True
has comment: http://stackoverflow.com/comment/89977176
downvote count: 0
answers question: http://stackoverflow.com/q/51486099

http://stackoverflow.com/q/51552597
accepted answer: http://stackoverflow.com/a/51552771
score: 0
answer count: 1
tagged with: global
tagged with: multiprocess
tagged with: textbox
has answer: http://stackoverflow.com/a/51552771
tagged with: python
type: AnsweredQuestion
has body: I have the following simple code. There is one button and entry widget. When I clicked button, changeText read entry_widget value and assign to 'var'. mainWindow and InfiniteLoop are running same time. But in InfiniteLoop variable var's value doesn't change. How to change its value? import tkinter as Tk from multiprocessing import Manager, Process import time var = 'Unchanged' root = Tk.Tk() root.geometry('740x306') root.title("Performance") id_label = Tk.Label(master=root, text="Id: ") id_label.pack() entry_widget = Tk.Entry(master=root, font=30) entry_widget.pack() def changeText(): global var var = entry_widget.get() #var is changed here. example var's value is: a print_var() # var = a and printing a. def print_var(): print(var) # var's value is a and its working here. def aaa(): id_label.config(font=30) id_label.place(x=10, y=5) entry_widget.place(x=33, y=5) sumbit_button = Tk.Button(master=root, text='Sumbit', command=changeText) sumbit_button.pack() sumbit_button.place(x=250, y=2) Tk.mainloop() def forLoop(): while True: time.sleep(0.1) print_var() #doesn't work here. print Unchanged if __name__ == '__main__': p1 = Process(target=aaa) p1.start() p2 = Process(target=forLoop) p2.start() p1.join() p2.join()
has title: How to update global variable in infinite loop using multiprocess
type: Question

http://stackoverflow.com/a/51634394
has body: I haven't tested this code but I feel that this should work. import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer df = pd.DataFrame() while True: if not len(df): # When you dataframe is populated for the very first time tfidf = TfidfVectorizer() matrix_1 = tfidf.fit_transform(df['text'].iloc[last_len:]) last_len = len(df) else: # When you dataframe is populated again and again # If you have to use earlier fitted model matrix_1 = np.vstack(matrix_1, tfidf.transform(df['text'].iloc[last_len:])) # If you have to update tf-idf every time which is kinda doesn't make sense matrix_1 = np.vstack(matrix_1, tfidf.fit_transform(df['text'].iloc[last_len:])) last_len = len(df) # TO-DO Some break condition according to your case ##### If the duration between dataframe updates is longer than you can use pickle on matrix_1 to store intermediate results. However what I feel is using tfidf.fit_transform(df['text']) again and again on different inputs will not give you any meaningful results or may be I misunderstood. Cheers!!
has comment: http://stackoverflow.com/comment/90255583
answers question: http://stackoverflow.com/q/51633775
has comment: http://stackoverflow.com/comment/90246262
score: 0
has comment: http://stackoverflow.com/comment/90255491
has comment: http://stackoverflow.com/comment/90253517
type: Answer

http://stackoverflow.com/q/51546893
tagged with: pagination
has body: I learned the pagination basics for Django from this link: https://simpleisbetterthancomplex.com/tutorial/2016/08/03/how-to-paginate-with-django.html However! the only problem I have is that I want to paginate without changing url. By that, I mean I need to paginate a table while there are multiple tables in a html page. How do i paginate only one table??? My code: This is the basic structure of the html template: ... {% for post_status in post.statusPage %} {{ post_status.status_time }} {{ post_status.repost_count }} {{ post_status.comment_count }} {{ post_status.like_count }} {% endfor %} {% if post.statusPage.has_other_pages %} {% if post.statusPage.has_previous %} {% else %} {% endif %} {% for i in post.statusPage.paginator.page_range %} {% if post.statusPage.number == i %} {{ i }} {% else %} {{ i }} {% endif %} {% endfor %} {% if post.statusPage.has_next %} {% else %} {% endif %} {% endif %} In side the template, there are multiple post objects post Each post has its own table and paginator: post.statusPage is the page object of the post.
tagged with: html-table
answer count: 2
has answer: http://stackoverflow.com/a/51621192
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
score: 0
has title: Django: Pagination without changing url?
type: Question
has answer: http://stackoverflow.com/a/51551041

http://stackoverflow.com/a/51621765
has body: This is a well known side effect of using Tk more than once. Use Tk to create the first window, and use Toplevel to make additional windows. It works the same but you don't need a mainloop call. Also, imports always go on the top, never in a function, and don't initialize and layout a widget on the same line (leads to common bugs). import tkinter total = 0 def round1(): t =tkinter.Toplevel() t.title('Round 1') t.geometry('1000x800') v1 = tkinter.IntVar() def marks(): global total if v1.get() == 1: total = total + 10 print("total", total) l1 = tkinter.Label(t,text = "Q 1 - Is python a case sensitive language?") l1.grid(row = 1) r1 = tkinter.Radiobutton(t,text = "A - true",variable = v1,value = 1) r1.grid(row = 2) r2 = tkinter.Radiobutton(t,text = "B - false",variable = v1,value = 2) r2.grid(row = 3) b = tkinter.Button(t, text = 'Submit',command = marks) b.place(x = 300, y = 300) def call(): t = tkinter.Tk() t.title('Instruction') t.geometry('1000x800') b1 = tkinter.Button(t, text = 'next',command = round1) b1.pack() t.mainloop() call()
answers question: http://stackoverflow.com/q/51621278
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/90135077
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51584754
has text: Dont you mean `{'Header2':{A:1, B:2, C:3},'Header3':{A:10, B:20, C:30}}` ?

http://stackoverflow.com/q/51580422
has comment: http://stackoverflow.com/comment/90126187
favorite count: 0
tagged with: python
duplicate of: http://stackoverflow.com/q/7207309
has title: Run a script in Python in parallel
answer count: 0
score: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has body: I have a folder where files are created all the time, once the file is the size of a 100 megabytes it means that it is ready to be loaded to the Database. The loading process should eventually be done in parallel. Five files at the same time. In Powershell I did this easily by invoke-parallel command. I wrote a script that opens a connection to the DB, runs procedures and executes a BULK INSERT command that uploads the file to the database. import pymssql import os try: # Open DB Connection conn = pymssql.connect(server=server, database=Database, timeout=60) c1 = conn.cursor(as_dict=True) #Run First procedure with the File Name Variable c1.callproc("First.procedure", (FileName ,)) # Recieve Variables from the First Procedure for row in c1: NewFileId= row['FileId'] DestinationTableName= row['DestinationTableName'] conn.commit() # Upload the CSV file to the DB string = "BULK INSERT DestinationTableName FROM '{CSV FILE}' WITH( FIELDTERMINATOR = ',', DATAFILETYPE = 'CHAR');" c1.execute(string) conn.commit() #Run the Second procedure with the File ID and Table Name Variables c1.callproc("2nd.procedure", (FileId, DestinationTableName,)) conn.commit() conn.close() f.close() except pymssql.Error as e: File = open("Error.txt", "a") File.write(repr(e)) I want to run the script in parallel, by sending five filenames at a time. Any recommendations for implementation through Python?
type: Question
has comment: http://stackoverflow.com/comment/90126272

http://stackoverflow.com/a/51608871
answers question: http://stackoverflow.com/q/51608587
downvote count: 0
has body: Create a rolling sum width a width of 5, look at all columns from the 5th to the end and select them if the values are always 3 or above: rolling_sum = df.rolling(5, min_periods=1, axis=1).sum() select = (rolling_sum.iloc[:, 4:] &gt;= 3).all(axis=1) In [92]: df Out[92]: 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0 1 1 0 0 2 0 1 0 1 1 0 0 1 0 0 3 0 1 1 1 0 1 1 1 1 1 4 0 1 0 1 1 1 0 0 1 1 5 0 0 1 1 1 0 1 1 1 0 In [94]: (df.rolling(5, min_periods=1, axis=1).sum().iloc[:, 4:] &gt;= 3).all(axis=1) Out[94]: 0 False 1 False 2 False 3 True 4 True 5 True dtype: bool
upvote count: 3
has comment: http://stackoverflow.com/comment/90191963
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51608587
score: 3

http://stackoverflow.com/a/51604466
score: -1
has body: If you just need the frames(jpegs)then you can use ffmpeg video filter option and extract the frames at a given frame rate(fps) ffmpeg -i "Compton.mp4" -vf fps=1 frame%04d.jpg -hide_banner This will extract one frame a second. You can tweak it based on how frequently your lyrics change in the video. If you want to use it in python then ffmpeg-python is a great tool. Hope it helps.
type: Answer
answers question: http://stackoverflow.com/q/51604394
downvote count: 1
has comment: http://stackoverflow.com/comment/90180947
upvote count: 0

http://stackoverflow.com/comment/90052499
type: Comment
comment on: http://stackoverflow.com/a/51526049
type: AnswerComment
has text: Let me rephrase: how can I enumerate the results of the Counter() as used by you ? I would like to be able to print the number of items (here: Characters) and know that there are e.g. 5 different characters with so and so occurrences.
score: 0

http://stackoverflow.com/comment/90019005
has text: look at [this](https://www.quora.com/What-is-one-hot-encoding-and-when-is-it-used-in-data-science). the gist being that one-hot encoding helps prevent ordinality of categorical variables.
type: Comment
comment on: http://stackoverflow.com/q/51525043
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90188617
type: Comment
type: QuestionComment
has text: jsonfile = open('fileJ.json', 'w') cursor = conn.cursor(pymysql.cursors.DictCursor) cursor.execute('SELECT report_id,message FROM reports') result_set = cursor.fetchall() field_names = [val[0] for val in cursor.description] for val in result_set: out = json.dumps(val, sort_keys=True, indent=4, separators=(',', ': ')) jsonfile.write(out)
comment on: http://stackoverflow.com/q/51611500
score: 0

http://stackoverflow.com/q/51516128
tagged with: tkinter
tagged with: subprocess
type: Question
score: 0
possible better answer: http://stackoverflow.com/a/51532599
answer count: 2
has body: I am struggling with my implementation of subprocess when created exe with pyInstaller. I have a program that has a gui (tkinter) where multiple buttons have their subprocess.popen(). there is a command over ssh sent to a network device which needs some time to finish. In pyCharm this works smooth. When I create the exe with pyInstaller, I get the following error: Exception in Tkinter callback Traceback (most recent call last): File "tkinter\__init__.py", line 1699, in __call__ File "gui.py" in line 197 in wrapper File "subprocess.py", line 707, in __init__ File "subprocess.py", line 990, in _execute_child FileNotFoundError: [WinError 2] The system cannot find the file specified key not found: process1 The corresponding code snipped of gui.py line 197 is: proc = subprocess.Popen(['python', r'commands/pec_cmd.py', str(cmd), pec_ip, '1', '0', '0', '0', '0'], startupinfo=subprocess.STARTUPINFO(), env=os.environ, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) later on I store the process in a dict, which is initialized earlier with subproccesses = {}: subprocesses['process' + str(i)] = proc Any idea or help why I get this FileNotFoundError? When run from PyCharm it works, but as soon as the exe is created (--onedir and --onefile tried), it fails
has title: Pyinstaller with Subprocess.popen fails as exe
tagged with: pyinstaller
tagged with: python
has answer: http://stackoverflow.com/a/51517112
accepted answer: http://stackoverflow.com/a/51517112
has answer: http://stackoverflow.com/a/51532599
type: AnsweredQuestion

http://stackoverflow.com/comment/90152086
type: QuestionComment
comment on: http://stackoverflow.com/q/51592560
score: 1
has text: @superhawk610 No, it does not decrease the time. I have to reboot actually to recover.
type: Comment

http://stackoverflow.com/comment/90192564
has text: That says *arr* is not defined, not numpy.
comment on: http://stackoverflow.com/q/51613670
score: 5
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90203103
type: QuestionComment
comment on: http://stackoverflow.com/q/51618235
has text: You could set up a background thread that uses a `signal` to interrupt the main thread—unless the code that you’re `exec`ing could change the signal handlers. But `multiprocessing` is probably a better solution, and not significantly more complicated.
score: 0
type: Comment

http://stackoverflow.com/comment/90057882
score: 7
type: AnswerComment
comment on: http://stackoverflow.com/a/51530110
type: Comment
has text: This is the best answer yet, the "dis" and "ast" answers obscure what is going on behind uncommon notations, this shows it clearly in normal python.

http://stackoverflow.com/a/51569391
has comment: http://stackoverflow.com/comment/90105300
accepted answer of: http://stackoverflow.com/q/51569216
type: Answer
has body: This is an example with buzzer in another thread: from threading import Event, Thread from imutils.video import FPS import numpy as np import argparse import imutils import time import cv2 import random program_ending_event = Event() buzz = False def buzzer_script(): program_ending_event.wait() if buzz: pass #Here you put your logic for the buzzer or whathave you #Rember to return from this or the program will not exit buzz_thread = Thread(target=buzzer_script) buzz_thread.start() ap = argparse.ArgumentParser() ap.add_argument("-p", "--prototxt", required=True, help="pridej k argumentu -p path k prototxt souboru") ap.add_argument("-m", "--model", required=True, help="pridej path k trenovacimu modelu") ap.add_argument("-c", "--confidence", type=float, default=0.2, help="minimalni sance (na odstraneni tzv slabych detekci") args = vars(ap.parse_args()) # "nacteni" hoangAI :D print("Loading hoangAI(TM) V.1.0.0") time.sleep(2.0) # nacteme si list stitku veci, ktere byly pouzity pri detekcnim treningu hoangAI, a pak nahodne vybereme barvu pro objektove ramecky CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"] CLASSES_RANDOM = CLASSES[random.randint(0, len(CLASSES) - 1)] print("vygoogli si" + CLASSES_RANDOM) COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3)) # nacteme si serializovany model caffe print("[INFO] nacitani modelu...") net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"]) # zacatek video snimani # a take zacneme pocitat fps print("[INFO] video snimani zacina...TED") vs = VideoStream(src=0).start() time.sleep(2.0) fps = FPS().start() # cyklus/smycka pres ramecek vystupu videa while True: # vezmeme ramecek z threadovaneho video vystupu a omezime sirku ramecku na 400 pixelu(aby to nebylo moc narocne na vykon) frame = vs.read() frame = imutils.resize(frame, width=400) # vezmem roz…
answers question: http://stackoverflow.com/q/51569216
has comment: http://stackoverflow.com/comment/90105463
downvote count: 2
has comment: http://stackoverflow.com/comment/90105438
has comment: http://stackoverflow.com/comment/90105375
score: -2
has comment: http://stackoverflow.com/comment/90105220
upvote count: 0
has comment: http://stackoverflow.com/comment/90105266
type: AcceptedAnswer

http://stackoverflow.com/q/51494140
answer count: 2
tagged with: beautifulsoup
has body: I have used the following code to access the description that is posted bellow. Here is the code: import requests from bs4 import BeautifulSoup resp = requests.get('https://www.meteoclimatic.net/feed/rss/ESCYL2400000024153A') soup = BeautifulSoup(resp.content, features='xml') items = soup.findAll('item') print(items[0].description) I have obtained the following XML sample: &lt;description&gt; &amp;lt;ul&amp;gt; &amp;lt;li&amp;gt;&amp;lt;img src="http://meteoclimatic.net/img/sem_tpv.png" style="width: 12px; height: 12px; border: 0px;" alt="***" /&amp;gt; &amp;lt;a href="http://www.meteoclimatic.net/perfil/ESCYL2400000024153A"&amp;gt;Sta Mar&amp;amp;#237;a del Condado&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt; &amp;lt;ul&amp;gt; &amp;lt;li&amp;gt; Actualizado: 24-07-2018 08:20 UTC&amp;lt;/li&amp;gt; &amp;lt;li&amp;gt;Temperatura: &amp;lt;b&amp;gt;23,6&amp;lt;/b&amp;gt; &amp;amp;#186;C ( M&amp;amp;#225;x.: &amp;lt;b style="color: red"&amp;gt;23,6&amp;lt;/b&amp;gt; / M&amp;amp;#237;n.: &amp;lt;b style="color: blue"&amp;gt;12,1&amp;lt;/b&amp;gt; )&amp;lt;/li&amp;gt; &amp;lt;li&amp;gt;Humedad: &amp;lt;b&amp;gt;54,0&amp;lt;/b&amp;gt; % ( M&amp;amp;#225;x.: &amp;lt;b style="color: red"&amp;gt;91,0&amp;lt;/b&amp;gt; / M&amp;amp;#237;n.: &amp;lt;b style="color: blue"&amp;gt;54,0&amp;lt;/b&amp;gt; )&amp;lt;/li&amp;gt; &amp;lt;li&amp;gt;Bar&amp;amp;#243;metro: &amp;lt;b&amp;gt;1021,0&amp;lt;/b&amp;gt; hPa ( M&amp;amp;#225;x.: &amp;lt;b style="color: red"&amp;gt;1021,2&amp;lt;/b&amp;gt; / M&amp;amp;#237;n.: &amp;lt;b style="color: blue"&amp;gt;1019,9&amp;lt;/b&amp;gt; )&amp;lt;/li&amp;gt; &amp;lt;li&amp;gt;Viento: &amp;lt;b&amp;gt;1,0&amp;lt;/b&amp;gt; km/h ( M&amp;amp;#225;x.: &amp;lt;b style="color: red"&amp;gt;9,0&amp;lt;/b&amp;gt; )&amp;lt;/li&amp;gt; &amp;lt;li&amp;gt;Direcci&amp;amp;#243;n del viento: &amp;lt;b&amp;gt;170&amp;lt;/b&amp;gt; - S&amp;lt;/li&amp;gt; &amp;lt;li&amp;gt;Precip.: &amp;lt;b&amp;gt;0,0&amp;lt;/b&amp;gt; mm&amp;lt;/li&amp;gt; &amp;lt;/ul&amp;gt; &amp;lt;/u…
has answer: http://stackoverflow.com/a/51494645
tagged with: python
has title: Python BeautifulSoup extraction
possible better answer: http://stackoverflow.com/a/51494559
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51494645
has answer: http://stackoverflow.com/a/51494559
type: Question
has comment: http://stackoverflow.com/comment/89956996
score: 0

http://stackoverflow.com/q/51490371
has body: I have a successfull running image recognition script. All I want is that on successful image recognition it saves the captured frame with the current timestamp into the file name. here is my code #!C:\Users\Gurminders\AppData\Local\Programs\Python\Python35-32\python.exe print("Content-type: text/html\n\n"); # Import OpenCV2 for image processing import cv2 import mysql.connector import numpy as np import os import sys import datetime import time import cgitb cgitb.enable() # put the database inputs here cnx = mysql.connector.connect(user='root', password='', host='localhost', database='image') cursor = cnx.cursor() def assure_path_exists(path): dir = os.path.dirname(path) if not os.path.exists(dir): os.makedirs(dir) # Create Local Binary Patterns Histograms for face recognization recognizer = cv2.face.LBPHFaceRecognizer_create() assure_path_exists("trainer/") # Load the trained mode recognizer.read('trainer/trainer.yml') # Load prebuilt model for Frontal Face cascadePath = "haarcascade_frontalface_default.xml" # Create classifier from prebuilt model faceCascade = cv2.CascadeClassifier(cascadePath); # Set the font style font = cv2.FONT_HERSHEY_SIMPLEX # Initialize and start the video frame capture cam = cv2.VideoCapture(0) check = "1" #sys.argv[1] int_check = int(check) print(int_check + 5) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y %H:%M:%S') # Loop while True: # Read the video frame ret, im =cam.read() # Convert the captured frame into grayscale gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) # Get all face from the video frame faces = faceCascade.detectMultiScale(gray, 1.2,5) # For each face in faces for(x,y,w,h) in faces: # Create rectangle around the face cv2.rectangle(im, (x-20,y-20), (x+w+20,y+h+20), (0,255,0), 4) # Recognize the face belongs to which ID Id, confidence = recognizer.predict(gray[y:y+h,x:x+w]) # Check the ID if exist if(Id == int_check): confi = round(100 - confidence,2) if(confi &gt;20): # create table face with two…
type: Question
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51738735
accepted answer: http://stackoverflow.com/a/51738735
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89952750
favorite count: 0
has comment: http://stackoverflow.com/comment/90437695
tagged with: python
has title: cv2.imwrite() not writing the timestamp into frame
score: 1
has comment: http://stackoverflow.com/comment/89952150
upvote count: 1

http://stackoverflow.com/q/51485603
type: AnsweredQuestion
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51485851
has comment: http://stackoverflow.com/comment/89940530
has answer: http://stackoverflow.com/a/51486444
accepted answer: http://stackoverflow.com/a/51486444
type: Question
has body: I obtain a structured numpy array from the following code: data = np.genfromtxt(fname, dtype = None, comments = '#', skip_header=1, usecols=(ucols)) where the first column is the indices of the rest of the data set in a scrambled order (which I wish to preserve). I would like to convert the structured array into a Pandas dataframe with the scrambled indices as the callable indices of the dataframe. EDIT: import numpy as np test = np.array([(45,1,'mars',1,1),(67,1,'pluto',1,1),(12,1,'saturn',1,1)],dtype='i,f,U10,i,f') creates a numpy structured array, calling the first entry gives: In [5]: test[0] Out[5]: (45, 1., 'mars', 1, 1.) calling the entire array: In [6]: test Out[6]: array([(45, 1., 'mars', 1, 1.), (67, 1., 'pluto', 1, 1.), (12, 1., 'saturn', 1, 1.)], dtype=[('f0', '&lt;i4'), ('f1', '&lt;f4'), ('f2', '&lt;U10'), ('f3', '&lt;i4'), ('f4', '&lt;f4')]) I want to turn this structured array into a pandas dataframe, and then in this example let 45,67,12 be the callable indices to access the data in the 'rows' of the array.
has answer: http://stackoverflow.com/a/51485851
has comment: http://stackoverflow.com/comment/89941819
upvote count: 4
tagged with: numpy
answer count: 2
downvote count: 0
score: 4
favorite count: 0
tagged with: pandas
tagged with: python
has title: Converting Numpy Structured Array to Pandas Dataframes

http://stackoverflow.com/comment/89979645
score: 1
has text: This is pretty much the stated use case for class methods: alternate constructors for a class. (Something like `from_file` would be a better name, though.)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51505334

http://stackoverflow.com/comment/90062675
type: AnswerComment
comment on: http://stackoverflow.com/a/51547456
type: Comment
has text: What question is this the answer to? (I'm serious, I'd like to know what OP wants to do.)
score: 1

http://stackoverflow.com/a/51511900
accepted answer of: http://stackoverflow.com/q/51511802
type: Answer
upvote count: 6
score: 6
has body: import sys val = None print(sys.getsizeof(val)) Answer: 16 val = [] print(sys.getsizeof(val)) Answer: 72 val = [None] print(sys.getsizeof(val)) Answer: 80 so [None]*1000 = 1000* 8 + 72 = 8072 Note: No of bytes may vary depending on the environment
answers question: http://stackoverflow.com/q/51511802
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89992475
downvote count: 0
has comment: http://stackoverflow.com/comment/89992491

http://stackoverflow.com/q/51577886
has comment: http://stackoverflow.com/comment/90148864
tagged with: web-scraping
has answer: http://stackoverflow.com/a/51578216
tagged with: scrapy
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90162376
answer count: 1
has body: I'm trying to scrape data from https://www.grailed.com/ using the Scrapy framework in Python, but when I'm in the scrapy shell and trying to learn how to extract the data, with response.css("my css path") or response.xpath("my xpath") I always get empty lists. Then, when I fetch and view the response in the shell for https://www.grailed.com, I get an almost blank page that does not contain the data that I would like to scrape (items, price, etc). In this case, would Scrapy still work for my purposes? If not, are there any alternatives? Thanks!
tagged with: python
accepted answer: http://stackoverflow.com/a/51578216
type: AnsweredQuestion
has title: Not able to load and scrape data from webpage using Scrapy

http://stackoverflow.com/a/51516988
score: 8
has body: Even I also had the same issue. I have fixed this by removing include_granted_scopes='true', in the flow.authorization_url
has comment: http://stackoverflow.com/comment/90009725
answers question: http://stackoverflow.com/q/51499034
downvote count: 0
upvote count: 8
type: Answer

http://stackoverflow.com/a/51618308
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51617433
score: 3
has comment: http://stackoverflow.com/comment/90223916
has body: You are trying to execute a Robot script directly with a Python interpreter. Python interpreters only understand Python code, not Robot syntax. you need to execute your Robot scripts through the robot runner. see: http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#executing-robot-framework
upvote count: 3
has comment: http://stackoverflow.com/comment/90241872
has comment: http://stackoverflow.com/comment/90233537

http://stackoverflow.com/a/51885963
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51567750
has body: I have fixed the issue. it was the equal sign (start&lt;=end). for page in range(len(information)): pdf_writer = PyPDF2.PdfFileWriter() start = information[page][1] end = information[page][2] while start&lt;=end: pdf_writer.addPage(pdfReader.getPage(start-1)) start+=1 if not os.path.exists(savepath): os.makedirs(savepath) output_filename = '{}_{}_page_{}.pdf'.format(information[page][0],information[page][1], information[page][2]) with open(output_filename,'wb') as out: pdf_writer.write(out)
answers question: http://stackoverflow.com/q/51567750
score: 15
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/98574804
type: Answer
upvote count: 15

http://stackoverflow.com/comment/90051558
has text: can you include the code you've tried so far to achieve this?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51541929
score: 2

http://stackoverflow.com/a/51511766
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51509892
type: AcceptedAnswer
downvote count: 0
has body: You were right, it was some odd numeric reason. Change this line: total += (-1)**i * comb(m, i, exact=True) * ((m-i)/k)**n to this: total += (-1)**i * comb(m, i, exact=True) * ((m-i)**n)/(k**n) For some reason, if you force a different operation order, things come out nicely. You might have to spend some more time figuring out how to modify your "log'd" version, but given that the change above fixes things, you might just want to discard the "log'd" version altogether. Hope it helps!
has comment: http://stackoverflow.com/comment/90027162
type: Answer
answers question: http://stackoverflow.com/q/51509892

http://stackoverflow.com/comment/89985260
has text: I'm sorry I do not understand what you are saying. I'll update my answer to make it more clear
comment on: http://stackoverflow.com/a/51508051
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90165929
type: QuestionComment
comment on: http://stackoverflow.com/q/51586711
type: Comment
has text: Yes, `type(firstargument)` in `__new__` will return `type`, since the first argument is a *class*, which is just an object of type `type`. The *instance doesn't exist at this point*, indeed, `__new__` is tasked with creating the instance. Have you looked at abernart's answer? I am still unsure what you mean by namespace here.
score: 0

http://stackoverflow.com/comment/89982578
has text: SAD is sum of absolute difference i.e. `sum(|x[n] - y[n]|)` right? Aren't you speaking about SSD (sum of *squared* difference `sum((x[n] - y[n])^2)`)? Could you add a link or a paragraph explaining why "The minimum of the SAD distance is the maximum of the correlation."?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51505602

http://stackoverflow.com/q/51630585
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90227927
favorite count: 0
tagged with: python
tagged with: tkinter
has body: I am trying to position the 'YES' and 'NO' buttons lower. If I setrow = to different numbers it would kind of work, but every time I set row = the same number for both, it just brings them back to their original positions. May someone please explain why this happens? Images NO.grid(row = 3, column = 5),YES.grid(row = 3, column = 7) NO.grid(row = 9, column = 5), YES.grid(row = 10, column = 7) NO.grid(row = 10, column = 7), YES.grid(row = 10, column = 7) #Intro l = Label(win, text = "Welcome to a simple number game.\n Would you like to play?", font=('Snap ITC', 30), bg='yellow', fg='slateblue') l.grid(row = 2, column = 5, columnspan=5) #Play or not buttons(YES/NO) NO = Button(win, text = 'NO', command=clicked, relief=RAISED, padx=30, pady=1 ) NO.config(bg='DodgerBlue2', fg='spring green', font=('Snap ITC', 10), bd=6) NO.grid(row = 10, column = 5) YES = Button(win, text = 'YES', command=clicked1, relief=RAISED, padx=30, pady=1) YES.config(bg='DodgerBlue2', fg='spring green', font=('Snap ITC', 10), bd=6) YES.grid(row = 10, column = 7)
has answer: http://stackoverflow.com/a/51632119
has comment: http://stackoverflow.com/comment/90227562
has comment: http://stackoverflow.com/comment/90226683
downvote count: 1
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51632119
score: -1
has title: Having trouble setting positions of buttons in python, tkinter
has comment: http://stackoverflow.com/comment/90228047

http://stackoverflow.com/comment/90048218
comment on: http://stackoverflow.com/a/51511769
type: AnswerComment
score: 0
type: Comment
has text: "access the actual last weight value" - as far as i know, this isn't possible in Keras loss function. "multiply it by a factor" - a constant? "mean square error loss" - of y_pred_fac and y_pred or y_true?

http://stackoverflow.com/comment/90034502
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51533163
has text: What's the “correct” combination?
type: Comment

http://stackoverflow.com/a/51586293
has body: let's start from the top: think=input ("Think of an animal. Type ready when you want to begin") think=think.upper() #FUR if think=="READY" : fur=input ("Does it have fur?") else : print ("I'll be waiting") if user enter anything else except "ready" for the first input which is stored in "think" then if condition will be false and your program straightly will go to else part so in the second part: if fur=="YES" : legs=input ("Does it walk on four legs?") : elif fur=="NO" : reptile=input ("Is it a reptile?") it'll crash your program cause there is no variable called fur and you want to compare it with something. for situation like this(waiting till user enter your expected input) it'll be better to use an infinite loop and when user entered your expecting input get out from that using break. so you must change first part to: think=input ("Think of an animal. Type ready when you want to begin") think=think.upper() #THINK while True: if think=="READY" : fur=input ("Does it have fur?") break else : print ("I'll be waiting") for other parts the exact thing as above may occur again( for instance as you mentioned if user say "YES" to "Does it walk on four legs?" again you don't have any variable called reptile which you want to compare it with something else in next lines) I suggest to use nested conditions: #FUR if fur=="YES" : legs=input ("Does it walk on four legs?") #LEGS if legs=="YES" : pet=input ("Do people own it as a pet?") elif legs=="NO" : marsupial=input("Is it a marsupial?") elif fur=="NO" : reptile=input ("Is it a reptile?") #REPTILE if reptile=="YES" : shell=input ("Does it have a shell?") if reptile=="NO" : fly=input ("Can it fly?") also don't forget to: 1-clear the : in this part of your code legs=input ("Does it walk on four legs?") : 2-if you want to get a newline after asking something from user such as in first line, \n must be useful think=input ("Think of an animal. Type ready when you want to begin\n") or even can use print for the string(cause print…
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51583897
answers question: http://stackoverflow.com/q/51583897
score: 1

http://stackoverflow.com/q/51562221
score: 11
type: AnsweredQuestion
has title: python multiprocessing - OverflowError('cannot serialize a bytes object larger than 4GiB')
linked to: http://stackoverflow.com/q/47776486
tagged with: python-multiprocessing
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90093250
possible better answer: http://stackoverflow.com/a/68126065
tagged with: pandas
has answer: http://stackoverflow.com/a/68126065
downvote count: 1
favorite count: 0
upvote count: 12
linked to: http://stackoverflow.com/q/29704139
has body: We are running a script using the multiprocessing library (python 3.6), where a big pd.DataFrame is passed as an argument to a function : from multiprocessing import Pool import time def my_function(big_df): # do something time consuming time.sleep(50) if __name__ == '__main__': with Pool(10) as p: res = {} output = {} for id, big_df in some_dict_of_big_dfs: res[id] = p.apply_async(my_function,(big_df ,)) output = {id : res[id].get() for id in id_list} The problem is that we are getting an error from the pickle library. Reason: 'OverflowError('cannot serialize a bytes objects larger than 4GiB',)' We are aware than pickle v4 can serialize larger objects question related, link, but we don't know how to modify the protocol that multiprocessing is using. does anybody know what to do? Thanks !!
linked to: http://stackoverflow.com/q/45119053
has answer: http://stackoverflow.com/a/51568084
tagged with: pickle
accepted answer: http://stackoverflow.com/a/51568084
tagged with: python

http://stackoverflow.com/q/51565978
has comment: http://stackoverflow.com/comment/90115487
type: Question
has comment: http://stackoverflow.com/comment/90098875
has answer: http://stackoverflow.com/a/59461516
has comment: http://stackoverflow.com/comment/90100297
tagged with: pandas
has body: I have a DataFrame in Pandas with a column called "duration" given in minutes. I want to get a new column that gives the duration in Hours:Minutes ( HH:MM ).
possible better answer: http://stackoverflow.com/a/51566057
favorite count: 0
has title: Converting a column of minutes to hours and minutes in Python
upvote count: 10
tagged with: python
has answer: http://stackoverflow.com/a/51566057
answer count: 4
accepted answer: http://stackoverflow.com/a/51566287
has comment: http://stackoverflow.com/comment/90098969
downvote count: 0
has answer: http://stackoverflow.com/a/65422487
has comment: http://stackoverflow.com/comment/90098951
has comment: http://stackoverflow.com/comment/90099219
has answer: http://stackoverflow.com/a/51566287
linked to: http://stackoverflow.com/q/20291883
type: AnsweredQuestion
tagged with: time-series
has comment: http://stackoverflow.com/comment/90099375
score: 10

http://stackoverflow.com/q/51578842
has answer: http://stackoverflow.com/a/51579345
answer count: 1
tagged with: flask
tagged with: flask-sqlalchemy
has body: My app is working on my main PC. I tried to clone the app to my laptop (I tried to initialize it on PC in a different directory and the problem was the same so the problem isn't with the laptop) and when initializing the db with flask db init I got the following error: sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: race [SQL: 'SELECT race.id AS race_id, race.name AS race_name \nFROM race'] (Background on this error at: http://sqlalche.me/e/e3q8) What I'm trying to do is in one of my forms to include a wtforms RadioField with choices based on the race table in db. So for every row in that table I want one choice in the selection. The important part of the form looks like this: class RegistrationForm(FlaskForm): race = RadioField('Race', validators=[InputRequired('Choose a race.')], choices=races, coerce=int) And the races variable is outside the form like this (before the form itself): with create_app().app_context(): races = [(race.id, race.name.capitalize()) for race in Race.query.all()] I figured that this last line is the problem from the call stack: Traceback (most recent call last): File "/home/dareon4/workspace/test/venv/bin/flask", line 11, in &lt;module&gt; sys.exit(main()) File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/flask/cli.py", line 894, in main cli.main(args=args, prog_name=name) File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/flask/cli.py", line 557, in main return super(FlaskGroup, self).main(*args, **kwargs) File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/click/core.py", line 697, in main rv = self.invoke(ctx) File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/click/core.py", line 1066, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/dareon4/workspace/test/venv/lib64/python3.6/site-packages/click/core.py", line 1066, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/dareon4/work…
has title: Flask-SQLAlchemy wtform based on db
score: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51579345
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/comment/89983892
type: QuestionComment
comment on: http://stackoverflow.com/q/51507395
type: Comment
score: 0
has text: Your python file takes in the input from your javascript/html file?

http://stackoverflow.com/q/51621477
tagged with: large-data
answer count: 0
type: UnansweredQuestion
tagged with: hdf5
upvote count: 7
has body: I am having trouble writing a data_generator for using with fit_generator in Keras. I have an HDF5 file with 4-dimensional numpy arrays (3-D data, with an extra single dimension from processing) stored as separate datasets. Each data-set is of the form (xxx, 512, 512, 1) where xxx is the number of slices in that particular dataset. I have a large amount of data (500 3-D images, each with ~300 slices, total ~50 GB, much larger than the RAM I have). When I run my code, it shows Epoch 1/250 and then the ram starts filling up and it gives a memory error. How do I go about writing a data_generator for this? What other methods can I look into? Here is my code: import scipy.io as sio import numpy as np import os import pandas import pickle import random import keras from keras.models import Sequential, Model from keras.layers import Conv2D, MaxPool2D, GlobalAveragePooling2D from keras.layers import Dense, Dropout, Flatten, Activation from keras.utils import np_utils from keras.applications.resnet50 import ResNet50 from keras.preprocessing import image from keras.applications.resnet50 import preprocess_input, decode_predictions from keras.backend import tf as ktf import h5py with open('categs/database.pickle', 'rb') as f: a=pickle.load(f) def generate_data(a, batch_size): while True: key=random.choice(list(a.keys())) # X_train= np.load(key+'.npy') with open('categs/'+key+'.pickle', 'rb') as labels, h5py.File('datafile.hdf5', mode='r') as f: X_train= np.asarray(f[key]) Y_train=pickle.load(labels) X_train1=np.zeros((X_train.shape[0], X_train.shape[1], X_train.shape[2],3)) for i in range(1,X_train.shape[0]-1): X_train1[i,:,:,1]=X_train[i,:,:,0] X_train1[i,:,:,0]=X_train[i-1, :, :, 0] X_train1[i, :, :,2]=X_train[i+1, :, :, 0] X_train=X_train1 X_train1=[] Y_train=np_utils.to_categorical(Y_train) yield X_train, Y_train base_model=ResNet50(include_top=False, weights='imagenet', input_tensor=None, input_shape=(512,512,3), pooling=None) x=base_model.output x = GlobalAveragePooling2D…
type: Question
score: 7
has comment: http://stackoverflow.com/comment/90211991
has title: Using a data generator for HDF5 file in Python and Keras
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/90039262
has text: A tuple and a scalar are fundamentally different objects. A tuple (even a len-1 tuple) is a sequence, while a scalar is a single value. What you have now is fine, and clarity is best when you have dictionaries with non-standardised keys. You could change your dict key to `(1,)`.
score: 0
comment on: http://stackoverflow.com/q/51535473
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51567675
has answer: http://stackoverflow.com/a/51567724
downvote count: 1
type: Question
tagged with: for-loop
has body: I created a function that copies a list and returns the new list. For some reason the function returns a list with double the length of the original list. Why does the list that is returned have double the length of the original? first = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def kopi(alist = [], blist = []): for element in alist: blist.append(element) return blist print(kopi(alist = first)) print("length:", len(kopi(alist = first))) I also know that the easier way to copy a list is: import copy as cp first = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] second = cp.copy(first) print(second) print("length:", len(second)) So why does the kopi function create a list with double the size? I'd also like to know how the copy.copy() works in python if possible.
tagged with: function
score: -1
tagged with: copy
has comment: http://stackoverflow.com/comment/90101764
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Why does my copy function create lists with double the length of the original list?
tagged with: list

http://stackoverflow.com/q/51588683
tagged with: opencv3.0
score: 0
has answer: http://stackoverflow.com/a/51598581
answer count: 1
tagged with: opencv
has title: opencv-python: haveOpenCL return False
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90145263
tagged with: python-3.x
type: Question
tagged with: opencl
has comment: http://stackoverflow.com/comment/90145013
tagged with: python
has body: Should return True if the the prebuilt binaries are compiled with OpenCL support. I've seen many examples where it just works out of the box. So my assumption is that the binaries are built with OpenCL support. So why might it not be working for me? Also it works from C++ for OpenCV installed from source. So my computer has OpenCV runtime installed: [ INFO:0] Initialize OpenCL runtime... opencv-python version: 3.4.2

http://stackoverflow.com/q/51622248
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
score: 1
has comment: http://stackoverflow.com/comment/90210324
has comment: http://stackoverflow.com/comment/90210365
has answer: http://stackoverflow.com/a/51622660
tagged with: google-app-engine
has body: I have been struggling with SQLAlchemy and getting it to work with google app engine. Of course it works locally :eyeroll:. I can't figure it out for the life of me. here's the logs: 2018-07-31 15:50:10.109 CDT Traceback (most recent call last): 2018-07-31 15:50:10.109 CDT File "/base/data/home/apps/s~projectname/20180731t154917.411530389303386639/lib/flask/app.py", line 1982, in wsgi_app 2018-07-31 15:50:10.109 CDT response = self.full_dispatch_request() 2018-07-31 15:50:10.110 CDT File "/base/data/home/apps/s~projectname/20180731t154917.411530389303386639/lib/flask/app.py", line 1614, in full_dispatch_request 2018-07-31 15:50:10.110 CDT rv = self.handle_user_exception(e) 2018-07-31 15:50:10.110 CDT File "/base/data/home/apps/s~projectname/20180731t154917.411530389303386639/lib/flask/app.py", line 1517, in handle_user_exception 2018-07-31 15:50:10.110 CDT reraise(exc_type, exc_value, tb) 2018-07-31 15:50:10.110 CDT File "/base/data/home/apps/s~projectname/20180731t154917.411530389303386639/lib/flask/app.py", line 1612, in full_dispatch_request 2018-07-31 15:50:10.110 CDT rv = self.dispatch_request() 2018-07-31 15:50:10.110 CDT File "/base/data/home/apps/s~projectname/20180731t154917.411530389303386639/lib/flask/app.py", line 1598, in dispatch_request 2018-07-31 15:50:10.110 CDT return self.view_functions[rule.endpoint](**req.view_args) 2018-07-31 15:50:10.110 CDT File "/base/data/home/apps/s~projectname/20180731t154917.411530389303386639/main.py", line 133, in signup 2018-07-31 15:50:10.110 CDT db.session.add(new_user) 2018-07-31 15:50:10.110 CDT File "/base/data/home/apps/s~projectname/20180731t154917.411530389303386639/lib/sqlalchemy/orm/scoping.py", line 153, in do 2018-07-31 15:50:10.110 CDT return getattr(self.registry(), name)(*args, **kwargs) 2018-07-31 15:50:10.110 CDT File "/base/data/home/apps/s~projectname/20180731t154917.411530389303386639/lib/sqlalchemy/util/_collections.py", line 1001, in __call__ 2018-07-31 15:50:10.110 CDT return self.registry.setde…
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90210265
answer count: 1
has title: ValueError: invalid literal for int() with base 10: 'password' using SQLALCHEMY with google app engine
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/90210304
has comment: http://stackoverflow.com/comment/90210499
accepted answer: http://stackoverflow.com/a/51622660

http://stackoverflow.com/comment/90022730
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51527078
has text: This assumes that `sys.argv` didn't have any other arguments in it yet. Replacing the contents, rather than `extend`ing, is likely more reliable.

http://stackoverflow.com/comment/90004663
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51517668
has text: @ng.newbie what I mean is that it looks as if you're using string formatting but not on a string with placeholders, unless `url.get('url')` returns a string that contains 2 '{}' that would eventually be replaced by the `.format(foo, bar)`

http://stackoverflow.com/comment/90209496
has text: Excellent! Seeing `Series` processes over loops is a learning process!
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51621787

http://stackoverflow.com/comment/89947916
comment on: http://stackoverflow.com/q/51489198
has text: Alright! I've just cut it down and narrowed!
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/51603959
duplicate of: http://stackoverflow.com/q/35084574
tagged with: search
type: Question
linked to: http://stackoverflow.com/q/35084574
upvote count: 1
answer count: 1
tagged with: bar-chart
downvote count: 0
tagged with: histogram
has comment: http://stackoverflow.com/comment/90185964
has body: I'm trying to create a histogram of the number of month / day pairs. So, I have an array which consists of the following: date_patterns = [(12,1,1992), (1,4,1993), (1,5,1993), (1,6,1993), (1,4,1994), (1,5,1994), (2,9,1995), (3,4,1995), (1,4,1996)] I'd like this histogram indexed by just the month and day so: (12,1) = 1 (1,4) = 3 (1,5) = 2 (1,6) = 1 (2,9) = 1 (3, 4) = 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/51607747
accepted answer: http://stackoverflow.com/a/51607747
has comment: http://stackoverflow.com/comment/90173910
has title: histogram indexed by month and day
has comment: http://stackoverflow.com/comment/90174657
type: AnsweredQuestion
score: 1
tagged with: matplotlib

http://stackoverflow.com/q/51613291
tagged with: python
linked to: http://stackoverflow.com/q/15268953
has body: I am trying to install pdfminer from GitHub, and I am encountering some errors. This threw an error: pip install git+git://github.com/pdfminer/pdfminer.six This threw an error: pip install git+https://github.com/pdfminer/pdfminer.six This threw an error: git clone https://github.com/pdfminer/pdfminer.six I googled for a solution online and found the ideas, listed above, from here: How to install Python package from GitHub? Those commands seemed to work for several other people, but these don't work for me. I am trying to run these three commands in the Anaconda Prompt. I am using Python 3.6. Maybe something is not configured correctly on my side, but I can't imagine what it is. Or, is it something else? BTW, here are the errors that I get: (base) C:\Users\Excel&gt;pip install https://github.com/pdfminer/pdfminer.six Collecting https://github.com/pdfminer/pdfminer.six Downloading https://github.com/pdfminer/pdfminer.six \ 102kB 1.3MB/s Cannot unpack file C:\Users\Excel\AppData\Local\Temp\pip-unpack-6kqx4igo\pdfmi ner.six (downloaded from C:\Users\Excel\AppData\Local\Temp\pip-req-build-2bpsgsh 0, content-type: text/html; charset=utf-8); cannot detect archive format Cannot determine archive format of C:\Users\Excel\AppData\Local\Temp\pip-req-bui ld-2bpsgsh0 (base) C:\Users\Excel&gt;pip install git+https://github.com/pdfminer/pdfminer.six Collecting git+https://github.com/pdfminer/pdfminer.six Cloning https://github.com/pdfminer/pdfminer.six to c:\users\excel\appdata\loc al\temp\pip-req-build-iqvj3zbl Error [WinError 2] The system cannot find the file specified while executing c ommand git clone -q https://github.com/pdfminer/pdfminer.six C:\Users\Excel\AppD ata\Local\Temp\pip-req-build-iqvj3zbl Cannot find command 'git' - do you have 'git' installed and in your PATH? (base) C:\Users\Excel&gt;git clone https://github.com/pdfminer/pdfminer.six 'git' is not recognized as an internal or external command, operable program or batch file.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90192317
has comment: http://stackoverflow.com/comment/90191716
has title: Trying to install a tool from GitHub, but getting lots of errors
has answer: http://stackoverflow.com/a/51613528
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51613528
upvote count: 0
score: -1
linked to: http://stackoverflow.com/q/26620312
has comment: http://stackoverflow.com/comment/90192282
has comment: http://stackoverflow.com/comment/90191900
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/90186688
comment on: http://stackoverflow.com/q/51611011
score: 2
has text: Well, a plain request to that URL returns 200, not 30x. In other words, that page does not redirect at an HTTP level. *Maybe* the server is detecting the user agent and chooses not to redirect non-browser agents; try spoofing your user agent. If that's not it, the redirect is done via Javascript or meta tag client-side, at which point it's up to you how you want to parse and emulate that…
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90332711
type: Comment
has text: Nice, you could get to the data with `df.set_index('color').eq('Yes').mean(level='color').T` too.
comment on: http://stackoverflow.com/a/51576588
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89961874
comment on: http://stackoverflow.com/q/51496267
score: 0
has text: my input is 371 and output i get is the statement written in else block of my code on my jupyter notebook
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90117398
score: 0
comment on: http://stackoverflow.com/q/51574191
type: Comment
type: QuestionComment
has text: See the [`DataFrame.query()` implementation](https://github.com/pandas-dev/pandas/blob/master/pandas/core/frame.py#L2937-L2955); note the `res = self.eval(expr, **kwargs)` line.

http://stackoverflow.com/a/51522949
has comment: http://stackoverflow.com/comment/90015772
downvote count: 0
has body: You are missing a parameter, the request variable. It works like this: render(request, 'template.html', context) So its reading your pk as the template name in this case.
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90014846
has comment: http://stackoverflow.com/comment/90014806
answers question: http://stackoverflow.com/q/51522826

http://stackoverflow.com/comment/90049890
type: Comment
type: QuestionComment
has text: yep - notice where that `dtype` changes and where your error is occurring
score: 0
comment on: http://stackoverflow.com/q/51539803

http://stackoverflow.com/comment/90084282
comment on: http://stackoverflow.com/q/51558719
score: 0
type: Comment
type: QuestionComment
has text: Simply remove the `to_field`, since `id` is the primary key, it should do that automatically. But I don't know if you will be able to migrate this automatically...

http://stackoverflow.com/a/51538899
has comment: http://stackoverflow.com/comment/90058959
answers question: http://stackoverflow.com/q/51528769
has body: I think the file is tab-separated, so you should split it by '\t' instead of ' ' transactions = data.map(lambda line: line.strip().split('\t'))
score: 0
has comment: http://stackoverflow.com/comment/90058800
type: Answer

http://stackoverflow.com/comment/90095383
type: AnswerComment
comment on: http://stackoverflow.com/a/51539497
type: Comment
has text: @Andrej_Kesely Thank you again for your response! I'm also trying to write the filename to my csv and I'm getting the following error when doing so. I've updated my code above. for i in range(vt_result_file): NameError: name 'vt_result_file' is not defined
score: 0

http://stackoverflow.com/comment/90126395
score: 2
has text: The second time you `.read()` a file, you've already reached the end of it and the result is an empty string. Also note that you're not checking that the password is the one that matches the nickname, and you shouldn't store passwords in plain text.
comment on: http://stackoverflow.com/q/51580525
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51553043
has comment: http://stackoverflow.com/comment/90082580
has body: Just use "Resample With Dataset" filter in ParaView. Open ParaView Open a StructuredGrid file file with the geometry you want it to have Open your UnstructuredGrid file Add a "Resample with dataset" filter Select structured data as source input Apply
type: Answer
has comment: http://stackoverflow.com/comment/90143451
has comment: http://stackoverflow.com/comment/90087187
has comment: http://stackoverflow.com/comment/90608873
answers question: http://stackoverflow.com/q/51547212
score: 0
has comment: http://stackoverflow.com/comment/90079954

http://stackoverflow.com/comment/89990034
has text: I don't think you can use IronPython 2.7.8 with CPython3, but [this answer](https://stackoverflow.com/a/37541483/5320906) looks like a solution for the `_functools` problem.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51506948

http://stackoverflow.com/comment/90153832
comment on: http://stackoverflow.com/a/51592397
type: Comment
has text: i would like to open a photo from a path for example `img = Image.open('photo.jpg')`, `resize 'img = img.resize((width,height),Image.NEAREST)` and then to reuse that image `nimg = openpyxl.drawing.image.Image(nimg)` and in the final to add the photo `ws.add_image(nimg,'F10'')`
score: 0
type: AnswerComment

http://stackoverflow.com/a/51547507
downvote count: 0
type: Answer
has body: If all you want to do is to change the format of the dates in the dictionaries you could simply: for d in diction: d['date'] = '{}-{}-{}'.format(d['date'][6:10], d['date'][3:5], d['date'][:2]) No need for pandas and converting data twice.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51547201

http://stackoverflow.com/comment/90201279
has text: @G_M Friendly one-liner. Performance is a concern? It can be reused: `beF = [w for w in be if w != '']`
type: Comment
comment on: http://stackoverflow.com/a/51617770
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90216867
type: AnswerComment
has text: IMHO, _everyone_ that uses TimSort should know that it's very good with lists that contain ascending runs, but I'm happy to inform them when it appears that they aren't aware of this lovely feature. :) Eg, [here](https://stackoverflow.com/q/47240184/4014959) and [here](https://chat.stackoverflow.com/transcript/message/42718973#42718973).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51623477

http://stackoverflow.com/a/51621128
score: 2
upvote count: 2
has body: Disclaimer: I don't really know pytorch, but i'm guessing based on other libraries and general standard practice as i know it. I believe it's the outputs of the last layer, which would be that fc2 linear transformation. So, the predicted category would be category 5, having the highest value. You could think of it as being a sort of 'raw' probability distribution-esque range, that is commonly then squashed into the range (0,1] via softmax.
accepted answer of: http://stackoverflow.com/q/51620964
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51620964

http://stackoverflow.com/a/51598416
score: 2
has body: Just iterate your dictionary keys and modify the dataframe for each key sequentially. Here's some pseudo-code to demonstrate how you can do this: for k in Di_N: Di_N[k] = pd.pivot_table(Di_N[k], values='Thing', ...).fillna(0) .... df_3 = .... df_4 = pd.DataFrame(Di_N[k].values - .... ) Di_N[k]['Unusualness'] = df_4.sum(axis=1) There are a few bits you don't need to include in your loop, e.g. definition of fun() and numerics. Put these outside your loop, you can still reference these objects within your loop. In addition, you can use pd.DataFrame.select_dtypes to select numeric columns: num_cols = df_4.select_dtypes(include=numerics).columns df_4[num_cols] = df_4[num_cols].abs()
has comment: http://stackoverflow.com/comment/90196826
has comment: http://stackoverflow.com/comment/90186934
accepted answer of: http://stackoverflow.com/q/51598223
has comment: http://stackoverflow.com/comment/90196715
has comment: http://stackoverflow.com/comment/90266184
answers question: http://stackoverflow.com/q/51598223
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90196627
has comment: http://stackoverflow.com/comment/90196795
type: Answer
upvote count: 2

http://stackoverflow.com/a/51571668
has body: Why not just a for loop? new_list = [] for char in lis: if char == '' and new_list[-1] == '': continue new_list.append(char) Outputs ['h', 'e', 'l', 'l', '', 'o', '', 'w']
score: 0
answers question: http://stackoverflow.com/q/51571362
type: Answer

http://stackoverflow.com/comment/89971789
comment on: http://stackoverflow.com/a/51501308
score: 1
type: AnswerComment
type: Comment
has text: @superv could you please update your original question with what you mean by "not run at all"?

http://stackoverflow.com/comment/90105314
has text: I have tried to extract the contents of the webpage with BeautifulSoup and urllib2/urllib.requests but when I tried it didn't work.
comment on: http://stackoverflow.com/q/51568529
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90152152
has text: This is an approach that worked for me for a similar issue, so I mentioned it.
comment on: http://stackoverflow.com/a/51593194
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90178333
type: AnswerComment
score: 0
type: Comment
has text: Excellent, I've learnt a lot from your numerous `pandas` answers in SO and it must be rubbing off because I was damn close to the same answer. Only difference I used `count().rename(...)` instead of `size().to_frame(...)` the latter being better (and I didn't think to `reindex()`). Is there any advantage to using `.ne()` over `!=` for the `cumsum()`?
comment on: http://stackoverflow.com/a/51606125

http://stackoverflow.com/comment/89974588
type: Comment
has text: you can add the "format()" method mentioned by @jonrsharpe in your answer.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51502776

plotly
tags question: http://stackoverflow.com/q/51557847
type: Tag
tags question: http://stackoverflow.com/q/51522500
tags question: http://stackoverflow.com/q/51546855
tags question: http://stackoverflow.com/q/51525276
tag name: plotly
tags question: http://stackoverflow.com/q/51620933
tags question: http://stackoverflow.com/q/51531289
tags question: http://stackoverflow.com/q/51599712
tags question: http://stackoverflow.com/q/51526969
tags question: http://stackoverflow.com/q/51585164
tags question: http://stackoverflow.com/q/51498121
tags question: http://stackoverflow.com/q/51588060
tags question: http://stackoverflow.com/q/51522463
tags question: http://stackoverflow.com/q/51521791
tags question: http://stackoverflow.com/q/51514840
tags question: http://stackoverflow.com/q/51525797

http://stackoverflow.com/a/51486553
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51486510
downvote count: 0
answers question: http://stackoverflow.com/q/51486510
has body: Combine dictionary construction and list comprehension: [dict(zip(lst1, l)) for l in lst2]
type: AcceptedAnswer
type: Answer
score: 3

http://stackoverflow.com/comment/113043115
comment on: http://stackoverflow.com/a/61254099
type: AnswerComment
type: Comment
has text: Just tested this (Win 10) and further found it didn't matter the messagebox type as the sound was determined from the icon messagebox.showinfo("test","Testing",icon="question") is silent. The icons 'info' and 'warning' cause the bell sound and 'error' causes the error sound.
score: 3

http://stackoverflow.com/comment/90172861
score: 0
comment on: http://stackoverflow.com/q/51603358
has text: `ordering = ["id"],` is the same as `ordering = (["id"],)`. You are in fact creating a tuple of lists.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51579215
tagged with: seaborn
tagged with: legend
has title: Remove seaborn lineplot legend title
score: 67
tagged with: python
answer count: 4
downvote count: 0
type: AnsweredQuestion
tagged with: line-plot
accepted answer: http://stackoverflow.com/a/51579663
has body: I would like to remove the title from my seaborn lineplot legend. I tried using this answer to no avail: import matplotlib.pyplot as plt import seaborn as sns; sns.set() fmri = sns.load_dataset("fmri") fig, ax = plt.subplots() g = sns.lineplot(x="timepoint", y="signal", hue="event", data=fmri, ax=ax) ax.legend().set_title('') I get the same if I try to set the title to None. Interestingly, setting the title to something else seems to prepend to the existing title: ax.legend().set_title('Something else') It almost looks like seaborn is treating the title as a hidden legend entry. How can I resolve this?
tagged with: matplotlib
upvote count: 67
has answer: http://stackoverflow.com/a/64346251
has answer: http://stackoverflow.com/a/56925686
type: Question
has answer: http://stackoverflow.com/a/51579663
possible better answer: http://stackoverflow.com/a/64346251
linked to: http://stackoverflow.com/q/5735208
has answer: http://stackoverflow.com/a/78819212
linked to: http://stackoverflow.com/q/43151440
favorite count: 0

http://stackoverflow.com/comment/90105652
score: 0
type: Comment
has text: After changing to `np.genfromtxt` got new error `ValueError: shape mismatch: objects cannot be broadcast to a single shape`.
type: AnswerComment
comment on: http://stackoverflow.com/a/51569704

http://stackoverflow.com/q/51524441
answer count: 1
downvote count: 1
favorite count: 0
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/51527498
has title: Django IntegryError Response does not work
type: AnsweredQuestion
upvote count: 0
tagged with: django-views
has comment: http://stackoverflow.com/comment/90018165
has comment: http://stackoverflow.com/comment/90019557
has body: i am writing a rest api where users are able to register, login and add keyword. But the keyword will only be added if they equals to one of the AllowedKeyword Model. I have done all so far, but i have to catch the IntegrityError if the combination of keyword and owner already exists. But if i try a api call it response the keyword i wanted to add (but he does not save it, which is correct) instead of Response the error. Here is the relevant code: apy.py class KeywordViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, ] serializer_class = KeywordSerializer def get_queryset(self): return self.request.user.keywords.all() def perform_create(self, serializer): try: serializer.save(owner=self.request.user) except IntegrityError as e: return Response({ "IntegrityError": "This combination already exists." }) serializers.py def allow_keyword(key): if AllowedKeyword.objects.filter(allowed_keyword=key).exists(): return key else: raise serializers.ValidationError('This Keyword ist not allowed') class KeywordSerializer(serializers.ModelSerializer): #keyword = serializers.StringRelatedField() keyword = serializers.CharField(max_length=255, validators=[allow_keyword]) class Meta: model = Keyword fields = ('id', 'keyword', ) models.py class AllowedKeyword(models.Model): allowed_keyword = models.CharField(max_length=255, null=True, default=None, blank=True) def __str__(self): return str(self.allowed_keyword) class Keyword(models.Model): keyword = models.CharField(max_length=255, null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='keywords') def __str__(self): return str(self.keyword) class Meta: unique_together = ('keyword', 'owner') Output if keyword is not in AllowedKeyword { "keyword": [ "This Keyword ist not allowed" ] } Output if keyword is unique and in AllowedKeyword { "id": 11, "keyword": "bitcoin" } Outout if keyword already exists in Keyword and is in AllowedKeyword { "keyword": "bitcoin" } => But s…
has answer: http://stackoverflow.com/a/51527498
type: Question
has comment: http://stackoverflow.com/comment/90019630
has comment: http://stackoverflow.com/comment/90017949
has comment: http://stackoverflow.com/comment/90019309
has comment: http://stackoverflow.com/comment/90018340
tagged with: django-models
score: -1
tagged with: django-rest-framework

http://stackoverflow.com/comment/90051720
score: 1
has text: The error message seems clear enough: your arbitrary user ID isn’t in `/etc/passwd` in the container.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51541415

http://stackoverflow.com/q/51616983
accepted answer: http://stackoverflow.com/a/51617226
upvote count: 1
favorite count: 0
has title: Change a thread argument python?
tagged with: multithreading
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has body: Hello python newbie with a question. So I've got a function that queries a device for its state and waits for a specific response, then takes a screen shot. def waitTrig(filename): while(True): trig = my_instrument.query(':TRIGger:STATE?') t = unicode('TRIG\n') if trig == t: print trig captureScreen(filename) time.sleep(0.5) break else: time.sleep(0.5) pass return 'TRIGED' I then made this a thread so it could run while I'm doing some other stuff. The code below is in another py file that imports a py file with the function, I don't think that matters much but anyways. waitTrigThread = threading.Thread(target=tek.waitTrig ,args=['EUREKA']) waitTrigThread.run() I check with an isAlive() after the while loop is broken and the screenshot is taken and it returns false. I was wondering if its possible to run the thread again, but with a different argument (saved screenshot filename). One potential solution I can see is having the filename be a variable and pass zero arguments, then just change the variable before I run the thread again, but this seems less than ideal and I don't even know if it will work.
has answer: http://stackoverflow.com/a/51617209
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51617209
has answer: http://stackoverflow.com/a/51617226

dockerpy
tags question: http://stackoverflow.com/q/51629194
tags question: http://stackoverflow.com/q/51585732
tag name: dockerpy
type: Tag

http://stackoverflow.com/a/51576886
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has body: index assignment to list requires the list to hold a value at that index. you cannot print int + str you cannot compare int with str --> here I chose to cast the random code into str Some typos included a misplaced quote, some other typos that I do not remember, and an Oxford comma. I have not checked the logic of your game, but you are now able to run and test it. (note that 10 colors are a lot for mastermind, the original had 5, or maybe 6, tops) Here is your code with the above corrections: import random s = [0]*4 s[0] = str(random.randint(0, 9)) s[1] = str(random.randint(0, 9)) s[2] = str(random.randint(0, 9)) s[3] = str(random.randint(0, 9)) board = (s[0] + ' | ' + s[1] + ' | ' + s[2] + ' | ' + s[3]) # user guess a number u1 = input('Your Name') pig = 0 cow = 0 match = 0 while match != 4: uu = int(input("Enter a number 0-9")) #user input if uu == s[0]: s[0].replace(uu) cow += 1 elif uu == s[1]: s[1].replace(uu) cow += 1 elif uu == s[2]: s[2].replace(uu) cow += 1 elif uu == s[3]: s[3].replace(uu) cow += 1 else: print('Wrong') pig = 0 continue print(str(u1) + ' Your cows ' + str(cow) + ", and pigs " + str(pig))
accepted answer of: http://stackoverflow.com/q/51576786
answers question: http://stackoverflow.com/q/51576786
upvote count: 1

http://stackoverflow.com/comment/89990631
type: Comment
comment on: http://stackoverflow.com/q/51508549
has text: Here is the response which looks like something screwed up: https://pastebin.com/CKx0kJ4w
score: 0
type: QuestionComment

http://stackoverflow.com/a/56169151
type: Answer
answers question: http://stackoverflow.com/q/51626638
score: 0
has body: try pip3 install torchvision --no-deps

http://stackoverflow.com/comment/90235070
comment on: http://stackoverflow.com/q/51621706
has text: I don't think we can keep guessing, you should make a self-contained example that demonstrates your problem, and include it in your question. Else it will be just too many questions trying to debug your problem.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90026271
score: 0
type: QuestionComment
type: Comment
has text: If you want to "start the whole thing again", then you have to put "the whole thing" inside the `while` loop, not just the last few lines.
comment on: http://stackoverflow.com/q/51528810

http://stackoverflow.com/a/51569289
has comment: http://stackoverflow.com/comment/90106129
has comment: http://stackoverflow.com/comment/90104890
answers question: http://stackoverflow.com/q/51569207
score: 0
has body: There are many possible solutions. In my opininion this is the easiest: import heapq list1 = [2,5,7] list2=[4,6,9] counter1=0 counter2=0 sum1=0 sum2=0 full_list = list1 + list2 three_largest = heapq.nlargest(3,full_list) for n in three_largest: if n in list1: list1.remove(n) counter1+=1 sum1+=n else: list2.remove(n) counter2+=1 sum2+=n print(counter1) print(counter2) print(sum1) print(sum2) Note that you made a mistake in your example for the values you provide. 9 is in list2 EDIT Here is an example that deals with N highest numbers in M lists: import heapq from typing import List list_of_lists = [[1,2,3,4],[4,3,7,12],[8,8,10,1]] def quick_metric(n_highest,lists:List[List[int]]): counters = [0 for i in range(len(lists))] sums = [0 for i in range(len(lists))] flat_list = [item for sublist in lists for item in sublist] highest = heapq.nlargest(n_highest, flat_list) for n in highest: for x_list in lists: if n in x_list: x_list.remove(n) counters[lists.index(x_list)]+=1 sums[lists.index(x_list)]+=n break print(counters) print(sums) print(highest) quick_metric(3,list_of_lists) Output: [0, 1, 2] [0, 12, 18] [12, 10, 8]
has comment: http://stackoverflow.com/comment/90104721
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90105003
has comment: http://stackoverflow.com/comment/90104692
type: Answer
accepted answer of: http://stackoverflow.com/q/51569207

http://stackoverflow.com/q/51507799
possible better answer: http://stackoverflow.com/a/51509118
favorite count: 0
has title: Is there something similar to the "find" command in Python?
has comment: http://stackoverflow.com/comment/113207166
tagged with: python
type: AnsweredQuestion
has body: On Linux there's a command called "find" where you can search for specific filenames. Is there any way I can search for a specific method when using dir()? For example, when I do: a = ["hey", "bro", "you're", "awesome"] dir(a) The result is: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] Can I do a dir(a) | find iter to get the result ____iter____? Is there any quick way to do a search in this way in Python?
upvote count: 0
accepted answer: http://stackoverflow.com/a/51507829
has comment: http://stackoverflow.com/comment/89984691
has answer: http://stackoverflow.com/a/51509118
type: Question
has comment: http://stackoverflow.com/comment/89984786
has answer: http://stackoverflow.com/a/51507829
score: -1
answer count: 2
tagged with: iterator
has comment: http://stackoverflow.com/comment/89984692
downvote count: 1

http://stackoverflow.com/a/51530109
type: Answer
has body: Does it actually hit the database that many times? I have not looked at the raw SQL but according to the documentation it is equivalent to the LIMIT clause and it also states "Generally, slicing a QuerySet returns a new QuerySet – it doesn’t evaluate the query". https://docs.djangoproject.com/en/2.0/topics/db/queries/#limiting-querysets I would be curious to see the raw SQL if you are looking at it and it does NOT do this as I use this paradigm.
answers question: http://stackoverflow.com/q/51509141
has comment: http://stackoverflow.com/comment/90064078
score: 0

http://stackoverflow.com/comment/90668976
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51536478
type: Comment
has text: I used a bounty to attract readers, but to no success. The points from a bounty were gone, even without an answer! Can you drop me a line at my email or twitter?

periodicity
tag name: periodicity
tags question: http://stackoverflow.com/q/51628094
type: Tag

http://stackoverflow.com/a/51505109
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51502959
type: Answer
answers question: http://stackoverflow.com/q/51502959
has body: To answer my own question, it looks like query shouldn't be used at all (regardless of using MultiIndex columns) for selecting certain columns, based on the answer(s) here: Select columns using pandas dataframe.query()
downvote count: 0
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/51484357
upvote count: 1
has body: When using dataframes, there are usually better ways to go about tasks then iterating through the dataframe. For example, in your case, you can create your series like this: time_series = (df.set_index(pd.date_range(pd.to_datetime(df.start).iloc[0], periods = len(df), freq='H')))['target'] &gt;&gt;&gt; time_series 2016-09-01 00:00:00 4.370279 2016-09-01 01:00:00 1.367778 2016-09-01 02:00:00 0.385834 Freq: H, Name: target, dtype: float64 &gt;&gt;&gt; type(time_series) &lt;class 'pandas.core.series.Series'&gt; Essentially, this says: "set the index to be a date range incremented hourly from your first date, then take the target column"
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51483774
answers question: http://stackoverflow.com/q/51483774
type: Answer
has comment: http://stackoverflow.com/comment/89937691
score: 1

http://stackoverflow.com/comment/90130320
comment on: http://stackoverflow.com/q/51582436
score: 0
has text: For using `type`, may be you can look into similar discussion in https://stackoverflow.com/a/10568115/5916727
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90123829
type: QuestionComment
comment on: http://stackoverflow.com/q/51571609
has text: Hi Andrej, it is because the paragraph C and D are under , which are also contained in Rule 2 . The reason why I want to extract these pairs is because contents C and D should also be related to the topic of their , and even heading texts. Thanks!
score: 0
type: Comment

http://stackoverflow.com/comment/90104127
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51568990
has text: For `sqlite3.connect()` start out using the actual filename (e.g. `example.db`) as the argument. Same for `environ.get()` use the actual filename, not the `sqlite:///` address.
type: Comment

http://stackoverflow.com/a/51576011
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51575793
answers question: http://stackoverflow.com/q/51575793
upvote count: 1
has comment: http://stackoverflow.com/comment/90117732
has body: Lets start with what 2D lists really are. A 2D list is simply a list of lists. With a normal list, you can do things like my_list[0] = 4 For a 2D list, each element is a list- list_of_lists[4] = ["a","b"] In this case list_of_list[4][0] returns "a", because we are really doing (list_of_list[4])[0]. You can think of the something[i][j] notation to being equivalent to Coordinate Plane: 'something', Position: (i, j), with i and j being x and y values. With that out of the way, lets consider making 2D lists. Since every "row" in your 2D list consists of a list, you need to first populate your original list with empty lists. Something like list_of_lists = [] for i in range(depth): list_of_lists.append([]) This will allow you to assign to append to any row of your 2D list, within range of [0,depth). You cannot simply use tempGen = [["*"]* MAX_COL] * MAX_ROW as your original post does, because every row of your 2D list will be a reference to the same exact list, and thus changing one row affects all rows identically. If you also want to access each element without appending, consider filling the original list with something like [0] * width or [None] * width, instead of the empty list []. Now lets say you have a 2D list built, you populated it with some data, and now you would like to shift all elements rightwards. You can write a function to do this def right_shift(my_list): for row_num in range(len(my_list)): # for each list in our list of lists row = my_list[row_num] for col_num in range(len(row)-2, -1, -1): # skip the last element, and iterate backwards row[col_num + 1] = row[col_num] # assign the (col_num+1)th element to equal the col_num 'th element in that row. return my_list Just write the logic to handle one row, and then extend that logic to all other rows of your list of lists (usually with just a for loop). For good measure, lets cover printing your 2D array- def print_matrix(list_of_lists): for row in list_of_lists: print("".join(map(str, row))) # here map(str…

http://stackoverflow.com/q/51531697
has answer: http://stackoverflow.com/a/51531736
favorite count: 0
type: Question
tagged with: python
answer count: 1
upvote count: 6
has title: more than one value with comma in dataframe pandas
has body: colum 1, colum2 a,b,c 30 b,c,f 40 a,g,z 50 . . . Using above dataframe with col1,2 I'd like to have dataframe as below dataframe with col3, 4. Additionally, col1 consists of values with commas. col4 consists of sum of col2 following col3. column3, column4 a 80 b 70 c 70 f 40 g 50 z 50
accepted answer: http://stackoverflow.com/a/51531736
downvote count: 0
score: 6
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/a/51531820
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51531680
has comment: http://stackoverflow.com/comment/90043495
has body: import tkinter as tk if __name__ == '__main__': root = tk.Tk() topframe = tk.Frame(root) topframe.pack() bottomframe = tk.Frame(root) bottomframe.pack(side=tk.BOTTOM) button1 = tk.Button(topframe, text="Hello boys", fg="green").place(x=140, y=380) button2 = tk.Button(topframe, text="How are you", fg="red").place(x=140, y=380) button3 = tk.Button(bottomframe, text="We are fine", fg="blue").place(x=140, y=380) root.mainloop()

http://stackoverflow.com/q/51585300
type: UnansweredQuestion
tagged with: pyqt5
upvote count: 1
tagged with: embed
type: Question
linked to: http://stackoverflow.com/q/41474647
has comment: http://stackoverflow.com/comment/90144592
score: 1
linked to: http://stackoverflow.com/q/29357442
has comment: http://stackoverflow.com/comment/105887364
linked to: http://stackoverflow.com/q/58816766
downvote count: 0
has comment: http://stackoverflow.com/comment/90165552
has title: PyQt5: Looking for example of Embedding external app window in Application
has comment: http://stackoverflow.com/comment/90144333
has body: I have a largeish application I'm developing in Python3 using PyQt5. I want to do something very much like what is being done here in PyQt4: # -*- coding: utf-8 -*- import atexit from PyQt4.QtCore import * from PyQt4.QtGui import * class XTerm(QX11EmbedContainer): def __init__(self, parent, xterm_cmd="xterm"): QX11EmbedContainer.__init__(self, parent) self.xterm_cmd = xterm_cmd self.process = QProcess(self) self.connect(self.process, SIGNAL("finished(int, QProcess::ExitStatus)"), self.on_term_close) atexit.register(self.kill) def kill(self): self.process.kill() self.process.waitForFinished() def sizeHint(self): size = QSize(400, 300) return size.expandedTo(QApplication.globalStrut()) def show_term(self): args = [ "-into", str(self.winId()), "-bg", "#000000", # self.palette().color(QPalette.Background).name(), "-fg", "#f0f0f0", # self.palette().color(QPalette.Foreground).name(), # border "-b", "0", "-w", "0", # blink cursor "-bc", ] self.process.start(self.xterm_cmd, args) if self.process.error() == QProcess.FailedToStart: print "xterm not installed" def on_term_close(self, exit_code, exit_status): print "close", exit_code, exit_status self.close() (from https://bitbucket.org/henning/pyqtwi...11/terminal.py) which is: Embed an X11 shell terminal (xterm) into a tab of my application. I understand that QX11EmbedContainer is not in PyQt5, and that some usage of createWindowContainer may be the new approach, but I cannot find any example of this in action to follow. I would ideally like to see the above code ported to a fully functional example using PyQt5 conventions and methods, but any assistance in any form will be helpful. I have looked at Embedding external program inside pyqt5, but there is only a win32 solution there, and I need to run on Linux and MacOS, with windows being an unnecessary nicety, if there was a generalized solution to fit all 3. It feels like this is close, but I cannot find the appropriate replacement for the win32gui module to use in a general …
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90164782
has comment: http://stackoverflow.com/comment/105896551
has comment: http://stackoverflow.com/comment/90170090
has comment: http://stackoverflow.com/comment/90146360
has comment: http://stackoverflow.com/comment/90173038
answer count: 0

http://stackoverflow.com/q/51530592
has body: I cloned tensorflow 1.1.0，modified the ./configure file, enable the mkl option: ## Set up MKL related environment settings if true; then # modify this to be true. while [ "$TF_NEED_MKL" == "" ]; do fromuser="" read -p "Do you wish to build TensorFlow with MKL support? [y/N] " INPUT fromuser="1" case $INPUT in [Yy]* ) echo "MKL support will be enabled for TensorFlow"; TF_NEED_MKL=1;; [Nn]* ) echo "No MKL support will be enabled for TensorFlow"; TF_NEED_MKL=0;; "" ) echo "No MKL support will be enabled for TensorFlow"; TF_NEED_MKL=0;; * ) echo "Invalid selection: " $INPUT;; esac done then use ./configure command: $ ./configure Please specify the location of python. [Default is /usr/local/bin/python]: Do you wish to build TensorFlow with MKL support? [y/N] No MKL support will be enabled for TensorFlow Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -march=native]: ^C root@4be8a8788f34:/tensor/tensorflow# ./configure Please specify the location of python. [Default is /usr/local/bin/python]: Do you wish to build TensorFlow with MKL support? [y/N] y MKL support will be enabled for TensorFlow Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -march=native]: Do you wish to use jemalloc as the malloc implementation? [Y/n] jemalloc enabled Do you wish to build TensorFlow with Google Cloud Platform support? [y/N] No Google Cloud Platform support will be enabled for TensorFlow Do you wish to build TensorFlow with Hadoop File System support? [y/N] No Hadoop File System support will be enabled for TensorFlow Do you wish to build TensorFlow with the XLA just-in-time compiler (experimental)? [y/N] No XLA support will be enabled for TensorFlow Found possible Python library paths: /usr/local/lib/python2.7/site-packages /tensor/target/applib-runtime-tensorflow-mkl-with-cpu-without-numpy Please input the desired Python library path to use. Default is…
linked to: http://stackoverflow.com/q/41310637
type: UnansweredQuestion
score: 2
downvote count: 0
tagged with: intel-mkl
favorite count: 0
has title: InvalidArgumentError (see above for traceback): No OpKernel was registered to support Op 'MklConv2DWithBias' with these attrs
linked to: http://stackoverflow.com/q/48009243
type: Question
has answer: http://stackoverflow.com/a/54228348
tagged with: python
upvote count: 2
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/90022888
type: QuestionComment
comment on: http://stackoverflow.com/q/51527011
score: 0
has text: Can you try explicitly recasting `dt1` and `dt0` as `np.timedelta64()` before summing? Those numpy objects should be able to be added...if you get an error with `dt2 = np.timedelta64(dt0) + np.timedelta64(dt1)` then you should try updating numpy.
type: Comment

http://stackoverflow.com/comment/89940282
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51485352
has text: May be the calling style is little different.... here I found a sample in below repository https://github.com/numpy/numpy/blob/master/numpy/core/arrayprint.py look for "np.set_printoptions"

http://stackoverflow.com/comment/90149310
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51590521
has text: @Roby Whoops sorry, just realised I copied the wrong matrix at the output (the code is still fine...), fixed now.

http://stackoverflow.com/a/51582697
has comment: http://stackoverflow.com/comment/90135353
type: AcceptedAnswer
has body: request.FILES is a dictionary-like object containing all uploaded files and the uploadcsvfile is the key in which you are making a POST request. Hence, request.FILES['uploadcsvfile'] will hold the particular file as InMemoryUploadedFile and it has a variable .name which holds the filename Try this, file_name = request.FILES['uploadcsvfile'].name Reference uploadfile.name request.FILES
type: Answer
accepted answer of: http://stackoverflow.com/q/51580691
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51580691
upvote count: 2

http://stackoverflow.com/a/51565604
answers question: http://stackoverflow.com/q/51565499
score: 3
type: AcceptedAnswer
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51565499
has body: First try to put it in English terms first, then translate to Python. You have a top-level list. You want the prof-name from each of its sublists. Each sublist has two sub-sublists. You only want the first sub-sublist. Each sub-sublist has a bunch of strings, either 6 or 8. Either way, you only want the fourth one. Each of those is pretty easy to translate into Python: Each sublist: for sublst in lst. The first element of each sublist: sublst[0]. The fourth element of each sub-sublist: sublst[0][3]. Putting it together: [sublst[0][3] for sublst in lst] That English description works for your example, so the code works for your example. If it's not the right set of rules to apply, come up with a different set of rules that do, and they'll be just as easy to translate. For example, maybe you don't want the fourth one, you want the ones that start with prof-? In that case: Each sublist. First sub-sublist. Each element of the sub-sublist that starts with Prof-. The last one is a bit tricky—we can't just do element.startswith('Prof-'), because some of the elements are integers. So let's write a function: def prof(element): return isinstance(element, str) and element.startswith('Prof-') Now: for sublst in lst sublst[0] for element in sublst[0] if prof(element) Putting that together: [element for sublst in lst for element in sublst[0] if prof(element)] But maybe that's too dense. Once you've got three clauses in a comprehension, it gets hard to reason about it. Maybe we should first flatten it, then filter it: elements = (element for sublst in lst for element in sublst[0]) profs = [element for element in elements if prof(element)] A bit longer, but hopefully easier to understand.
downvote count: 0
has comment: http://stackoverflow.com/comment/90098057

http://stackoverflow.com/comment/90127891
has text: Can you explain what is wrong with the way the OP uses 'get()'?
comment on: http://stackoverflow.com/a/51581320
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51546108
type: UnansweredQuestion
tagged with: django
score: 2
has answer: http://stackoverflow.com/a/51547081
type: Question
tagged with: hadoop
downvote count: 0
tagged with: hdfs
linked to: http://stackoverflow.com/q/36379232
has answer: http://stackoverflow.com/a/51548097
has body: Is it possible to save files in Hadoop without saving them in local file system? I would like to do something like shown below however I would like to save file directly in HDFS. At the moment I save files in documents directory and only then I can save them in HDFS for instance using hadoop fs -put. class DataUploadView(GenericAPIView): def post(self, request): myfile = request.FILES['photo'] fs = FileSystemStorage(location='documents/') filename = fs.save(myfile.name, myfile) local_path = 'my/path/documents/' + str(myfile.name) hdfs_path = '/user/user1/' + str(myfile.name) run(['hadoop', 'fs', '-put', local_path, hdfs_path], shell=True)
favorite count: 0
has title: Is it possible to save files in Hadoop without saving them in local file system?
answer count: 3
has comment: http://stackoverflow.com/comment/90063876
tagged with: python
has answer: http://stackoverflow.com/a/51638023
linked to: http://stackoverflow.com/q/21754728
upvote count: 2

http://stackoverflow.com/q/51613667
type: Question
has comment: http://stackoverflow.com/comment/90192575
has answer: http://stackoverflow.com/a/51613829
score: -1
tagged with: flask
has comment: http://stackoverflow.com/comment/90234862
has title: Python Output in localhost even after defining app route to '/hello'
upvote count: 1
answer count: 1
favorite count: 0
has body: Here's the code:- from flask import Flask app= Flask(__name__) @app.route('/hello') def hello_world() : return 'hello World' app.add_url_rule('/','hello','hello_world') if __name__== '__main__': app.run(debug=True) Please see if u can find an error, please type the correct code in the answer
type: UnansweredQuestion
tagged with: python
downvote count: 2

http://stackoverflow.com/q/51568499
tagged with: image
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/90103430
answer count: 1
tagged with: arrays
has body: I am stuck trying to figure out how to avoid doing 2 loops while doing some analysis on an image. Its a square image (same dimension in the x and y). The current way its set up its that for each pixel, in the array "stars", the first coordinate is the x position, the second coordinate is the y position, and the third coordinate is the brightness of the pixel. I know there must be a far far superior way to set this up but every thing I try just works when i=j (giving me essentially only the diagonal of this matrix). How do I do this better?! def firstmoment(stars,bins): xsum=0.0 ysum=0.0 itot=0.0 for i in range(0, bins): for j in range(0, bins): xsum=xsum+stars[i][j][0]*stars[i][j][2] ysum=ysum+stars[i][j][1]*stars[i][j][2] itot=itot+stars[i][j][2] x0=xsum/itot y0=ysum/itot return x0, y0, itot
has title: Avoiding loops over 2D array using numpy
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90103334
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/51568753
accepted answer: http://stackoverflow.com/a/51568753
has comment: http://stackoverflow.com/comment/90103600

http://stackoverflow.com/a/51582794
has body: Underfitting occurs when both the training and testing accuracies are low. This signifies a systematic problem with your model, i.e the data would fit better with a polynomial model but you're using a linear model. So a ~66% accuracy for both training and testing is considered underfitting because they are both very low. In general, high error on both sets indicates underfitting. Overfitting occurs when you have relatively high accuracy on training, but lower on testing. This signifies that your model has fit too much towards your training data, and does not generalize well to other data. In general, low error on training and higher error on testing indicates overfitting.
answers question: http://stackoverflow.com/q/51582726
type: Answer
has comment: http://stackoverflow.com/comment/90130906
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90130933
downvote count: 0

http://stackoverflow.com/q/51491019
has comment: http://stackoverflow.com/comment/89951578
score: 0
has answer: http://stackoverflow.com/a/51492097
tagged with: http://stackoverflow.com/tag/json
type: Question
has answer: http://stackoverflow.com/a/51491192
has comment: http://stackoverflow.com/comment/89952354
has body: I have two JSON, I want to combine into one. JSON 1 [ { "city":"Aberdeen", "year":1996, "occupancy_change":null, "effective_rent_change":null }, { "city":"Aberdeen", "year":1997, "occupancy_change":null, "effective_rent_change":null }, { "city":"Ambler", "year":1996, "occupancy_change":1.65, "effective_rent_change":4.37 }, { "city":"Ambler", "year":1997, "occupancy_change":1.17, "effective_rent_change":-0.25 } ] JSON 2 [ { "year":1996, "pma_occupancy_change":null, "pma_effective_rent_change":null }, { "year":1997, "pma_occupancy_change":null, "pma_effective_rent_change":null } ] I want to combine two json into one, I want to get into the format below. [ { "year":1996, "pma_occupancy_change":null, "pma_effective_rent_change":null, "city":"Aberdeen", "occupancy_change":null, "effective_rent_change":null, "city":"Ambler", "occupancy_change":1.65, "effective_rent_change":4.37 }, { "year":1997, "pma_occupancy_change":null, "pma_effective_rent_change":null, "city":"Aberdeen", "occupancy_change":null, "effective_rent_change":null "city":"Ambler", "occupancy_change":1.17, "effective_rent_change":-0.25 } ] Here is what I have tried so far, but it didn't work for me. from collections import defaultdict null = None d = defaultdict(dict) for l in (city_li, pma_li): for elem in l: d[elem['year']].update(elem) l3 = d.values() print l3
answer count: 3
has comment: http://stackoverflow.com/comment/89950665
has answer: http://stackoverflow.com/a/51492940
has title: Combining two JSON into one using Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89954025
tagged with: python
has comment: http://stackoverflow.com/comment/89950752

http://stackoverflow.com/a/51625581
answers question: http://stackoverflow.com/q/51621842
accepted answer of: http://stackoverflow.com/q/51621842
upvote count: 2
type: AcceptedAnswer
has body: Here is the summary of this approach: Scan horizontally row by row Scan vertically col by col Prepare a list of potential points Group points by distance Find the bounding box around the sub-grouped points Compute the rectangles and ignore those ones touch the boundaries of the image. Source Code: First of all, import the required libraries. import numpy as np import cv2 Secondly, define a function that compute the distance between two points and, more importantly, it allows you to decide whether you want to print "too easy" in the terminal. def too_easy_distance(pt1, pt2, is_print=False): if is_print: print ("too easy!") return ((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2) ** 0.5 Thirdly, load image and find out the width and height. img = cv2.imread("broken_rect.png", 0) height, width = img.shape[:2] active_threshold = 25 # adjust this parameter based on the thickness of borders potential_pts = [] Now, scan the image horizontally row by row. for i in range(height): if len (np.where(img[i:i+1,:]==0)[1] ) &lt; active_threshold: continue is_start = False is_real_start = False for j in range(width): if img[i,j] == 0 and is_start is False: is_start = True continue # Enter the valid region if is_start and is_real_start is False: if img[i,j] == 255: is_real_start = True else: is_real_start = False if is_real_start: if img[i,j] == 255: potential_pts.append((j, i)) else: is_real_start = False Then, scan the image vertically column by column. for j in range(width): if len (np.where(img[:, j:j+1]==0)[1] ) &lt; active_threshold: continue is_start = False is_real_start = False for i in range(height): if img[i,j] == 0 and is_start is False: is_start = True continue # Enter the valid region if is_start and is_real_start is False: if img[i,j] == 255: is_real_start = True else: is_real_start = False if is_real_start: if img[i,j] == 255: potential_pts.append((j, i)) else: is_real_start = False Finally, sort the list and display the result image. grouped_pts = [] #list of list f…
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90221114
downvote count: 0
has comment: http://stackoverflow.com/comment/90215831
has comment: http://stackoverflow.com/comment/90215890

http://stackoverflow.com/comment/90220606
type: QuestionComment
comment on: http://stackoverflow.com/q/51626953
score: 0
type: Comment
has text: @clemens I know what you mean, sorry. So I should start from row 1?

http://stackoverflow.com/q/51605307
tagged with: date
has title: using beautifulsoup and regex to get date from string, getting None at the moment
score: 0
has comment: http://stackoverflow.com/comment/90176563
has comment: http://stackoverflow.com/comment/90176088
has comment: http://stackoverflow.com/comment/90243476
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
tagged with: regex
has body: So when I write out my text I'm able to capture the date in the following format: text = "The event takes place from May 14-June 11, 2018" match = re.search(r'(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\s+\d{1,2}\-(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\s+\d{1,2},\s+\d{4}', text).group() print(match) 'May 14-June 11, 2018' But what I really want is to use beautifulsoup and regex to extract the date from anywhere in the html page but I can't seem to replicate my success above although the text definitely exists in the html. I'm a novice, so maybe I'm missing something obvious. open_page = driver.get(url) html_source = driver.page_source soup = BeautifulSoup(html_source, 'html.parser') date = soup.find(text=re.compile('(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\s+\d{1,2}\-(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\s+\d{1,2},\s+\d{4}')) print(date) 'None' I also tried: html_source = driver.page_source soup = BeautifulSoup(html_source, 'html.parser') text = soup.get_text().strip() match = re.search(r'(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\s+\d{1,2}\-(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\s+\d{1,2},\s+\d{4}', text) print(match) 'None' The HTML is: &lt;div class="event--date"&gt; The event takes place from May 14-June 11, 2018 &lt;/div&gt; But I don't want to rely on tags because I will be doing this across domains. And when I print soup = BeautifulSoup(html_source, 'html.parser') text = soup.get_text().strip() print(text) '@charset "UTF-8";[ng\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.…
has comment: http://stackoverflow.com/comment/90177352
answer count: 0
has comment: http://stackoverflow.com/comment/90176270
type: Question
has comment: http://stackoverflow.com/comment/90176286
has comment: http://stackoverflow.com/comment/90176203

http://stackoverflow.com/comment/89970789
has text: You're awesome! Thanks a ton!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51491949
type: Comment

http://stackoverflow.com/comment/90197510
has text: Thanks, javascript being run makes sense. Its annoying though. Will have to learn to use selenium. Also their searches seem to be limited for some urls. Not working for youtube but is for imdb.
type: QuestionComment
comment on: http://stackoverflow.com/q/51615479
type: Comment
score: 0

http://stackoverflow.com/q/51617162
answer count: 2
has title: Python kubernetes module has no attribute 'api_key'
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/59463739
has answer: http://stackoverflow.com/a/51617803
has answer: http://stackoverflow.com/a/59463739
type: Question
tagged with: kubernetes
tagged with: python
accepted answer: http://stackoverflow.com/a/51617803
has body: I have installed the python kubernetes module via the instructions here https://github.com/kubernetes-client/python/blob/master/kubernetes/README.md via pip install, but i still can not seem to run through their example since i get an attribute error. Code: from __future__ import print_function import time import kubernetes.client from kubernetes.client.rest import ApiException from pprint import pprint # Configure API key authorization: BearerToken kubernetes.client.configuration.api_key['authorization'] = 'YOUR_API_KEY' # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed # kubernetes.client.configuration.api_key_prefix['authorization'] = 'Bearer' # create an instance of the API class api_instance = kubernetes.client.AdmissionregistrationApi() try: api_response = api_instance.get_api_group() pprint(api_response) except ApiException as e: print("Exception when calling AdmissionregistrationApi-&gt;get_api_group: %s\n" % e) Error: Traceback (most recent call last): File "&lt;pyshell#3&gt;", line 1, in &lt;module&gt; kubernetes.client.configuration.api_key['authorization'] = 'YOUR_API_KEY' AttributeError: module 'kubernetes.client.configuration' has no attribute 'api_key'
score: 0

http://stackoverflow.com/comment/90145102
type: Comment
comment on: http://stackoverflow.com/a/51589891
has text: can you also help with the first subquestion? `1.Print the name of the folder and subfolder that is empty. and check if it is empty `
type: AnswerComment
score: 0

http://stackoverflow.com/a/51592924
has comment: http://stackoverflow.com/comment/90154984
has comment: http://stackoverflow.com/comment/90153043
has comment: http://stackoverflow.com/comment/90156612
has comment: http://stackoverflow.com/comment/90154901
downvote count: 0
has comment: http://stackoverflow.com/comment/90154513
type: Answer
has comment: http://stackoverflow.com/comment/90155404
answers question: http://stackoverflow.com/q/51590108
has comment: http://stackoverflow.com/comment/90155197
score: 1
has comment: http://stackoverflow.com/comment/90154923
has comment: http://stackoverflow.com/comment/90154588
has comment: http://stackoverflow.com/comment/90152794
upvote count: 1
has body: The "g" must be an available GraphTraversalSource on the server you are connecting to at 'ws://localhost:8182/gremlin. The way in which you create "g" is dependent upon the graph database you are using. If you are using the open source Gremlin Server then, you configure that GraphTraversalSource by way an initialization script for the server as described in the "Starting Gremlin Server" section of the documentation. You can see an example of the creation of "g" in the sample script that ships with Gremlin Server also seen here. Neptune, CosmosDB, DSE Graph and perhaps JanusGraph on Compose have their own specific methods for "g" - you'd want to consult their documentation for more details.
has comment: http://stackoverflow.com/comment/90152389
has comment: http://stackoverflow.com/comment/90155272

http://stackoverflow.com/comment/90103562
comment on: http://stackoverflow.com/q/51568417
score: 0
has text: What command do you use to "start up dev_appserver.py directly in the terminal"?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90020689
has text: Your text file seems like it's in json format. Which using the json package would probably make it easier to read the key/value pairs then the actual text data.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51525961

http://stackoverflow.com/a/51528100
has body: Try this: Set your schedule_interval to None without the '', or simply do not specify schedule_interval in your DAG. It is set to None as a default. More information on that here: airflow docs -- search for schedule_interval Set orchestration for your tasks at the bottom of the dag. Like so: import datetime from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.dummy_operator import DummyOperator default_args = { 'owner': 'me' } bash_command = """ echo "this is a test task" """ with DAG('schedule_test', default_args=default_args, start_date = datetime(2018, 7, 24), schedule_interval=None, catchup=False ) as dag: t1 = DummyOperator( task_id='extract_data', dag=dag ) t2 = BashOperator( task_id = "first_task", bash_command = bash_command ) #####ORCHESTRATION##### ## It is saying that in order for t2 to run, t1 must be done. t2.set_upstream(t1)
type: Answer
has comment: http://stackoverflow.com/comment/90031024
score: 28
has comment: http://stackoverflow.com/comment/116141740
downvote count: 0
has comment: http://stackoverflow.com/comment/95185518
has comment: http://stackoverflow.com/comment/137305628
upvote count: 28
has comment: http://stackoverflow.com/comment/90030981
answers question: http://stackoverflow.com/q/51520767
has comment: http://stackoverflow.com/comment/90031086

http://stackoverflow.com/q/51505744
has answer: http://stackoverflow.com/a/51506009
has body: I have a list with sublist's in it and want to group them based on a common value. For example: my_list = [["John", 1], ["Mark", 3], ["Peter", 5], ["Mark", 6], ["Mark", 33], ["John", 2]] I would like to group these based on the first value (the name). The desired result would be: grouped_list = [[["John", 1], ["John", 2]], [["Mark", 3], ["Mark", 6], ["Mark", 33]], "Peter", 5]
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/89980612
has title: How to group sublist's with matching values
possible better answer: http://stackoverflow.com/a/51506009
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51505814
accepted answer: http://stackoverflow.com/a/51505814
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/89980608

http://stackoverflow.com/comment/90164248
type: AnswerComment
type: Comment
has text: You are handling a requests response object. Check out my answer to convert it directly into a dictionary, using requests own parser.
score: 0
comment on: http://stackoverflow.com/a/51599089

http://stackoverflow.com/q/51622710
has comment: http://stackoverflow.com/comment/90211071
type: Question
tagged with: indexing
has answer: http://stackoverflow.com/a/51623277
tagged with: dataframe
tagged with: pandas
has body: I have 2 dataframes: a and b. When I run print(a.shape, b.shape), I get the following result: (1, 28849) (44, 29025) meaning that b has more columns that a. When I run b.columns.difference(a.columns) the result is a null index: (Index([], dtype='object'). I get the same result when I run a.columns.difference(b.columns). Why do the dataframes have different columns counts in shape but not have any different columns between them?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90210749
favorite count: 0
accepted answer: http://stackoverflow.com/a/51623277
tagged with: python
has title: Pandas: 2 data frames have different shapes but no different columns
has comment: http://stackoverflow.com/comment/90210819
has comment: http://stackoverflow.com/comment/90210855
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/a/51626068
has comment: http://stackoverflow.com/comment/90216957
has comment: http://stackoverflow.com/comment/90217719
answers question: http://stackoverflow.com/q/51625669
upvote count: 2
has body: Explaining why you got whitespaces in your code snippet. Have a look at the loop part: for i in range(length): for j in range(length): if j + i &lt;= length: number_list.append(target_string[j:j + i]) Here, both i and j gets initiated with 0. So when we decode it, it comes like: i = 0: j=0: 0+0 &lt; length number_list.append(for i in range(length): for j in range(length): if j + i &lt;= length: number_list.append(target_string[0:0 + 0])) --&gt; [''] and so on.....
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/51604716
score: 0
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/51604943
has title: Doesn't perform what I'm asking unless I click close (pygame)
type: UnansweredQuestion
tagged with: loops
type: Question
has body: the button clicked function doesn't run unless I click the top left exit button which won't close my game but instead, perform the task I am actually asking it to do. help? def game_intro(): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: return elif event.type == pygame.MOUSEMOTION: for button in buttons: if button[1].collidepoint(event.pos): button[2] = HOVER_COLOR else: button[2] = BLACK screen.blit(bg, (0, 0)) for text, rect, color in buttons: pygame.draw.rect(screen, color, rect) screen.blit(text, rect) pygame.display.flip() def button_clicked(): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: return if event.type == pygame.MOUSEBUTTONDOWN: print('test') pygame.display.flip() clock.tick(60) game_intro() button_clicked pygame.quit()
answer count: 2
tagged with: program-entry-point
tagged with: button
has answer: http://stackoverflow.com/a/51604728

http://stackoverflow.com/comment/90159786
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51550585
score: 0
has text: Iteresting. I might have to try that out. For now I am using your furst suggestion.

http://stackoverflow.com/q/51557885
tagged with: python
answer count: 0
has title: Signal matching and noise extraction
has comment: http://stackoverflow.com/comment/90132171
tagged with: signal-processing
type: Question
tagged with: filtering
has comment: http://stackoverflow.com/comment/91040970
tagged with: signals
has comment: http://stackoverflow.com/comment/90110261
score: 0
tagged with: fft
has body: I wish to match two signals and then extract a matching signal from one of the signals. Note that one of the signals appears to be more noisy. How can I design a filter to extract the matching components and later on determine the excessive noise.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91010379

data-analysis
tags question: http://stackoverflow.com/q/51494887
tags question: http://stackoverflow.com/q/51579073
tags question: http://stackoverflow.com/q/51622452
tags question: http://stackoverflow.com/q/51576982
type: Tag
tags question: http://stackoverflow.com/q/51578749
tags question: http://stackoverflow.com/q/51618724
tags question: http://stackoverflow.com/q/51534605
tag name: data-analysis

http://stackoverflow.com/q/51605708
upvote count: 1
has title: Get and Insert MongoDB auto generated UUID into current record
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90177391
score: 1
has comment: http://stackoverflow.com/comment/90177493
type: Question
has comment: http://stackoverflow.com/comment/90177343
tagged with: mongodb
has comment: http://stackoverflow.com/comment/90177667
has body: I have need to insert a MongoDB auto generated UUID into my another column like below code, try: conn = MongoClient('localhost', 27017) print("Connected successfully!!!") except: print("Could not connect to MongoDB") # database db = conn.hash # Created or Switched to collection names: my_gfg_collection collection = db.ib unix = datetime.utcnow() unixtime = calendar.timegm(unix.utctimetuple()) emp_rec1 = { "tib" : "8f7074d8-a520-4f7d-b2d3-09dc36acb5fd", "tib_name" : "TPEMAIL", "mail_box_name" : "Test Gmail", "id_mail_box" : "use here when generate to UUID v4 - MONGO", } # Insert Data rec_id1 = collection.insert_one(emp_rec1) As show in above code I will need to insert auto generated UUID (_id:5b5a36d40abd950a88003fc3) into my id_mail_box column.
has comment: http://stackoverflow.com/comment/90177409
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90177437
type: UnansweredQuestion

http://stackoverflow.com/q/51593859
has answer: http://stackoverflow.com/a/51594126
has comment: http://stackoverflow.com/comment/90153785
has body: I want to make a range between 2 dates and my range field has the time damage_list = Damage.objects.filter(entry_date__range=(fdate, tdate)) fdate and tdate are dates ('YYYY-mm-dd') and entry_date has time. How can I range all the records of the tdate ? Thanks in advance Kostas
tagged with: django
tagged with: python
has title: Python : range between dates when range field has time
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90153369
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90153458
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/51594126
has answer: http://stackoverflow.com/a/51594147
accepted answer: http://stackoverflow.com/a/51594147

http://stackoverflow.com/a/51572523
has comment: http://stackoverflow.com/comment/90116180
score: 0
has comment: http://stackoverflow.com/comment/90123141
answers question: http://stackoverflow.com/q/51572481
has comment: http://stackoverflow.com/comment/90111164
type: Answer
has body: if keys[pygame.K_LEFT]: rotatedleft = True You're assigning True to rotatedleft, which you've previously defined as a function, try calling the function, like so: if keys[pygame.K_LEFT]: rotatedleft() Now it's kinda turning, I'm pretty sure it's still not quite what you're looking for but hey, baby steps. Best of luck with your game. import pygame import sys pygame.init() screen = pygame.display.set_mode((1150, 800)) pygame.display.set_caption("Car Football") degrees = 180 x = 70 y = 70 x1 = 1000 y1 = 400 width = 70 height = 70 vel = 15 vel1 = 15 run = True while run: pygame.time.delay(100) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False screen.fill((0, 0, 0)) bgImg = pygame.image.load("Football_pitch.png").convert() screen.blit(bgImg, [0,0]) redcar = pygame.image.load("redcar.png") screen.blit(redcar, (x, y)) keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: redcar = pygame.transform.rotate(redcar, 15) screen.blit(redcar, (x, y)) if run: x += vel if keys[pygame.K_RIGHT]: redcar = pygame.transform.rotate(redcar, -15) screen.blit(redcar, (x, y)) pygame.display.flip() pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if run: x1 -= vel1 if keys[pygame.K_d] and x1 &lt; 1150: x1 += vel1 if keys[pygame.K_w]: y1 -= vel1 if keys[pygame.K_s]: y1 += vel1 bluecar = pygame.image.load("Bluecarss.png") screen.blit(bluecar, (x1, y1)) circleball = pygame.draw.circle(screen, (255, 255, 255), (300, 140), 50, 0) pygame.display.update() pygame.display.flip() pygame.quit() sys.exit()
has comment: http://stackoverflow.com/comment/90111340

http://stackoverflow.com/q/51597979
has comment: http://stackoverflow.com/comment/90163632
has comment: http://stackoverflow.com/comment/90165548
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/90164521
has comment: http://stackoverflow.com/comment/90163531
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90163689
upvote count: 1
has answer: http://stackoverflow.com/a/51599939
answer count: 1
tagged with: format
has comment: http://stackoverflow.com/comment/90163746
tagged with: pandas
has comment: http://stackoverflow.com/comment/90164632
type: AnsweredQuestion
has title: Python Tkinter GUI messy printing format
accepted answer: http://stackoverflow.com/a/51599939
downvote count: 0
has body: import pandas as pd import csv from tkinter import * master = Tk() textBox = Text(master, height=1, width=10) textBox.grid(row=0, column=1) fileVar = StringVar() fileLabel = Label(master, textvariable=fileVar) fileLabel.grid(row=3, column=1) fileVar2 = StringVar() fileLabel2 = Label(master, textvariable=fileVar) fileLabel2.grid(row=3, column=2) def retrieve_input(): Customer = textBox.get("1.0","end-1c") fileread = pd.read_csv('50.csv', encoding='latin-1') filevalue = fileread.loc[fileread['Customer'].str.contains(Customer, na=False),"Jul-18\nQty"] productheader = fileread.loc[fileread['Customer'].str.contains(Customer, na=False), 'Product'] fileVar.set(productheader) fileVar2.set(filevalue) button1 = Button(master,text="Show Values", command=lambda: retrieve_input()) button1.grid(row=4, column=1) mainloop() I have this program that prints values in Tkinter Gui, for specific values in a specific row. However the format of the values being printed is quiet messy and I am unsure how to clean it up, In addition I would like for it to not display the numbers labeled next to it, Just the product name (blurred out in blue) and the value associated with it( which are the number values with decimals). Here is a snapshot of the GUI: In addition, at the very bottom of the list, this is also displayed: Ideally, I would like for it to only show the header(July-18) and not the datatype Also if it helps to know, these are forecast files, (reason for headers with dates) Here is a dummy image of what my csv files look like:
score: 1
has comment: http://stackoverflow.com/comment/90164473
favorite count: 0

http://stackoverflow.com/a/51625814
type: Answer
has comment: http://stackoverflow.com/comment/90216422
score: 2
downvote count: 0
has body: By declaring include as a class variable you are making all instances of this class share the same variable include. Instead, you should make include an instance variable by initializing it in the __init__() method: class PWA_Parse(): def __init__(self): self.include = []
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51625775
answers question: http://stackoverflow.com/q/51625775

http://stackoverflow.com/comment/89973300
score: 0
has text: if you run your code with option 1 first you will get an error as you are trying to read a file that doesn't exist.
type: Comment
comment on: http://stackoverflow.com/a/51501423
type: AnswerComment

http://stackoverflow.com/a/51529623
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51529545
type: Answer
has body: If you want dictionary with column name as key, you can try: result = df.to_dict(orient='list') # result will be: # {'Param_2': [0.0118587, 0.011752, 0.011296299999999999, 0.0103071], # 'Param_1': [-0.171321, 1.93377, 4.10144, 6.25064], # 'Param_3': [-0.148752, 1.9707, 4.06861, 5.83927]} You can also use as_matrix which will return numpy ndarray, as below: result = df.as_matrix().T # result will be: # [[-0.171321 1.93377 4.10144 6.25064 ] # [ 0.0118587 0.011752 0.0112963 0.0103071] # [-0.148752 1.9707 4.06861 5.83927 ]] To get list from ndarray: result = df.as_matrix().T.tolist()

http://stackoverflow.com/comment/90021646
score: 1
has text: Will fail if a character name contains a quote in it
type: AnswerComment
comment on: http://stackoverflow.com/a/51526171
type: Comment

http://stackoverflow.com/a/51532590
downvote count: 0
has comment: http://stackoverflow.com/comment/90070148
type: AcceptedAnswer
score: 8
has comment: http://stackoverflow.com/comment/90051461
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/101421218
answers question: http://stackoverflow.com/q/51525043
has body: All scikit estimators handle multi-class problems automatically. Internally they will be converted to appropriately, either simple encoding to 0,1,2 etc if the algorithm supports native multi-class problems or one-hot encodings if the algorithm handles multi-class problems by transforming to binary. Please refer to the documentation to see this: All scikit-learn classifiers are capable of multiclass classification,... You can see that "logistic regression, multilayer perceptron, Gaussian naive Bayes, and random forest" are under the heading "Inherently multiclass". Others like SGD, or LinearSVC use one-vs-rest approach to handle multi-class, but that as I said above will be handled internally by scikit, so you as a user don't need to do anything and can pass multi-class labels (even as strings) in a single array of y to all classification estimators. Only thing where the user needs to explicitly convert labels to one-hot encoding is the multi-label problem, where more than one label can be predicted for a sample. But I think your question is not about that.
accepted answer of: http://stackoverflow.com/q/51525043

http://stackoverflow.com/q/51575127
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/64628227
has title: Use Google API with a token [Django & AllAuth]
accepted answer: http://stackoverflow.com/a/64628227
has comment: http://stackoverflow.com/comment/90131240
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90131093
downvote count: 0
type: Question
score: 5
has body: I am using AllAuth on my Django app to manage user authentication. With that my users can connect their Google accounts and i get a google API token (with appropriate scopes). I would like to use that token to access google APIs (Calendar v3 in my case) with that token, as my user already used OAuth2 to sign-in on my website, and gave me access to the calendar API. Google only gives the full process on their website (from auth to api), is there a way to build my idea, or is it simply impossible? i have tries drive = build('calendar', 'v3', credentials=credentials) as said here but "credentials" needs to be part of an oauth2client and not just a simple string token. Thank you for your precious time.
answer count: 1
tagged with: google-api-python-client
favorite count: 0
upvote count: 5
has comment: http://stackoverflow.com/comment/111096158
tagged with: django-allauth
tagged with: google-api
has comment: http://stackoverflow.com/comment/110650844

http://stackoverflow.com/comment/90075989
score: 0
type: AnswerComment
type: Comment
has text: Thanks!; They are: DATE(GMT) object TIME(GMT) int64 DATASET float64
comment on: http://stackoverflow.com/a/51552053

http://stackoverflow.com/q/51631168
upvote count: 0
has comment: http://stackoverflow.com/comment/90227455
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/51633933
has comment: http://stackoverflow.com/comment/90227326
has comment: http://stackoverflow.com/comment/90226466
has comment: http://stackoverflow.com/comment/90227713
has body: I want to use this widget in my code https://djangosnippets.org/snippets/10522/ My question is where to paste this code? and how to use it in my forms? My code requires me to select only month and date from the user using a drop-down menu. The date is set to '1' by default. I found this widget very helpful but I am unable to figure out how to use it in my code
score: -1
tagged with: django-forms
tagged with: django-widget
has title: How to use widgets from django snippet?
type: Question
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90227344
tagged with: python

http://stackoverflow.com/a/51635247
upvote count: 19
accepted answer of: http://stackoverflow.com/q/51635177
type: Answer
has comment: http://stackoverflow.com/comment/120362542
answers question: http://stackoverflow.com/q/51635177
downvote count: 0
score: 19
has body: Isn't that basically a dictionary, where the key is the result of applying the function to the value? y = {math.floor(i): i for i in iterable}
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90234893

http://stackoverflow.com/comment/90003138
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51500483
has text: Thank you. Works fine aswel

http://stackoverflow.com/comment/90050430
comment on: http://stackoverflow.com/q/51540451
type: Comment
has text: more clarification: i don't have permission to install python 3 on it because i have normal user privileges
score: 0
type: QuestionComment

http://stackoverflow.com/q/51618435
has comment: http://stackoverflow.com/comment/90203388
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90202926
type: Question
accepted answer: http://stackoverflow.com/a/51619165
has title: Pygame window runs fine until clicked on, then shows "Not responding"
has comment: http://stackoverflow.com/comment/90202488
has comment: http://stackoverflow.com/comment/90202973
score: 0
has comment: http://stackoverflow.com/comment/90202851
tagged with: python-3.7
tagged with: user-interface
answer count: 1
has answer: http://stackoverflow.com/a/51619165
linked to: http://stackoverflow.com/q/20165492
tagged with: python
tagged with: pygame
has body: A few things first: I am using Windows 10 Home edition I am using Python 3.7 I am using pygame 1.9.4 My IDE is Visual Studio Code, with IDLE as the backup I am currently designing a GUI using pygame. NOTE: the code is NOT done yet. When I run a debug session in VS Code, it (mostly) works as expected, but when I try to click on the start button, pygame does not respond and shows not responding. I've also noticed this with other pygame scripts I've made, where the pygame window freezes when clicked or moved. Any help would be appreciated. Here's the code: # Import modules import sys, pygame, time, math from time import sleep from PIL import Image # Display background image image = 'asdf.png' change = 2 img = Image.open('asdf.png') width = img.width * change height = img.height * change print(width) print(height) screen = pygame.display.set_mode((width,height)) background = pygame.image.load(image).convert() newscreen = pygame.transform.scale(background, (width, height)) screen.blit(newscreen, (0,0)) pygame.display.update() # start button pygame.draw.rect(newscreen, (255,120,0), pygame.Rect(width/4,height-height/4, width/2, height/7)) screen.blit(newscreen, (0,0)) pygame.display.update() pygame.init() myFont = pygame.font.SysFont("Times New Roman", 100) text = myFont.render("START", False, (0, 0, 0)) screen.blit(text, (width/4+8,height-height/4-10)) pygame.display.update() pygame.image.save(newscreen, 'background.png') pygame.image.save(text, 'starttext.png') # i button pygame.draw.rect(newscreen, (255,0,120), pygame.Rect(width - 50, 10, 40,40)) screen.blit(newscreen,(0,0)) pygame.display.update() myFont = pygame.font.SysFont("Times New Roman", 25) ibutton = myFont.render("i", False, (0, 0, 0)) screen.blit(ibutton, (width-32,17)) pygame.display.update() # Mouse click while True: left,right,center = pygame.mouse.get_pressed() if left == True: if event.type == MOUSEBUTTONUP: x,y = pygame.mouse.get_pos() if ((width/4) &lt;= x &lt;= ((width/4) + (width/2))) and ((height-he…

http://stackoverflow.com/comment/90208500
has text: Thank you. I'll tick this in a few minutes as i cannot do that now, for some reason.
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51621480

http://stackoverflow.com/q/51600355
type: Question
possible better answer: http://stackoverflow.com/a/51600393
has answer: http://stackoverflow.com/a/51600488
answer count: 3
tagged with: pandas
upvote count: 7
has body: I would like to truncate the time from my datetime object. My min example looks like this: date s1 7/26/2018 9:31 s2 7/26/2018 9:32 s3 7/26/2018 9:33 s4 7/26/2018 9:34 s5 7/26/2018 9:35 s6 7/26/2018 9:36 data = [{'date': '7/26/2018 9:31'},{'date': '7/26/2018 9:32'}, {'date': '7/26/2018 9:33'},{'date': '7/26/2018 9:34'}, {'date': '7/26/2018 9:35'},{'date': '7/26/2018 9:36'}] df = pd.DataFrame(data, index=['s1', 's2','s3','s4','s5','s6']) I would like to truncate the time from my datetime object. My goal looks like this: date s1 7/26/2018 s2 7/26/2018 s3 7/26/2018 s4 7/26/2018 s5 7/26/2018 s6 7/26/2018
tagged with: datetime
favorite count: 0
has answer: http://stackoverflow.com/a/51600393
has answer: http://stackoverflow.com/a/51600469
tagged with: python
has title: Truncate datetime object pandas
type: AnsweredQuestion
downvote count: 0
score: 7
accepted answer: http://stackoverflow.com/a/51600488

http://stackoverflow.com/comment/90218294
score: 0
has text: @HowardGENG I have attached the full image, thank you for your advice.
comment on: http://stackoverflow.com/q/51624496
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89947223
type: AnswerComment
comment on: http://stackoverflow.com/a/51488793
type: Comment
has text: I commented all, not working. And the constructor is executing, nice trick. Thanks for your help.
score: 0

http://stackoverflow.com/q/51585663
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51594861
tagged with: discord.py
answer count: 2
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90136947
tagged with: python
has body: i made this command it will purge the amount of messages that you said ie >purge 10 it will delete 10 messages i don't know how to check if the input was a decimal can you help Code: @client.command(pass_context=True) async def purge(ctx, amount=300): if ctx.message.author.server_permissions.manage_messages: channel = ctx.message.channel messages = [] async for message in client.logs_from(channel, limit=int(amount) + 1): messages.append(message) await client.delete_messages(messages) await client.say('Purged {} message(s)!'.format(len(messages)-1)) else: embed = discord.Embed( title = ':x: Insufficient Permissions', description = 'You need to have the Manage Messages premission to execute this command.', colour = 0xff0000 ) await client.say(embed=embed)
has title: Discord.py how to check if input has a decimal
has answer: http://stackoverflow.com/a/51585882

http://stackoverflow.com/comment/90141810
type: Comment
has text: You have to iterate the response_data. then you will get the respective result.
comment on: http://stackoverflow.com/q/51588325
score: 0
type: QuestionComment

http://stackoverflow.com/q/51621593
has comment: http://stackoverflow.com/comment/90288818
has comment: http://stackoverflow.com/comment/90209053
has comment: http://stackoverflow.com/comment/90216191
has answer: http://stackoverflow.com/a/51622174
has comment: http://stackoverflow.com/comment/90210594
has comment: http://stackoverflow.com/comment/90265709
has body: I got a fresh installation of Python 3.6.6 and PyCharm 2018.2 Commmunity Edition. Unfortunately PyCharm (and also a installed with Python IDLE) does not see packages installed with pip. I’ve installed with pip some pakages: Pillow, Pyglet, Pygame, Arcade. I can see them using pip list command, but they are inviosible in PyCharm interpreter settings. PyCharm detects only setuptools and pip. I reinstalled Python and Pycharm several times, tried to reinstall packages with pip, but nothing helps.
answer count: 2
has comment: http://stackoverflow.com/comment/90211449
has comment: http://stackoverflow.com/comment/90211219
tagged with: pycharm
has comment: http://stackoverflow.com/comment/90211640
type: UnansweredQuestion
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/51621660
has title: Pycharm does not detect installed installed packages
has comment: http://stackoverflow.com/comment/90208742
has comment: http://stackoverflow.com/comment/90210356
has comment: http://stackoverflow.com/comment/90244484
type: Question

http://stackoverflow.com/comment/90090374
has text: I found the problem... the server's loop was blocking on `select()` because I was calling it with a 5-second timeout. Thank you for your useful input
comment on: http://stackoverflow.com/a/51549936
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89985161
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51507943
has text: Both ways doesn't make any sense here? You're saying every list is increased to match length of longest list so clearly there's only one way-- getting bigger in size
score: 0

http://stackoverflow.com/q/51608823
upvote count: 1
has title: beautiful for loop nested in the dict function : how does that work?
type: Question
tagged with: for-loop
has body: I am currently reviewing this post about a sudoku solver in Python. I am trying to deconstruct it line by line, and I went through the following digits = '123456789' rows = 'ABCDEFGHI' cols = digits #squares will give you all the squares of a Sudoku, from A1-A9 to I1-I9 squares = cross(rows, cols) unitlist = ([cross(rows, c) for c in cols] + [cross(r, cols) for r in rows] + [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]) #each square has 3 units : the row it is in, the column it is in, and the "block" of 3x3 squares it is in : units = dict((s, [u for u in unitlist if s in u]) for s in squares) That last part is what dumbfounds me. We have, if I am not mistaken, a list comprehension, inside a generator. But what is the "for s in squares" doing inside the dict function ? How comes I can't write the following and obtain the same result ? for s in squares : units3 = dict((s, [u for u in unitlist if s in u])) This seems pretty obsure to me, unfortunately all my attempts at finding a ressource for this end up with results that point to basic tutorials on dict creation, or looping over dict values... Could you please either tell me how a for loop inside a dict function works, or point me towards a good tuto on that topic ?
has comment: http://stackoverflow.com/comment/90184069
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51608890
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90182663
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51608890

http://stackoverflow.com/comment/90186397
comment on: http://stackoverflow.com/a/51609960
has text: Hi, I don't understand why this method `element_to_be_clickable` needs to be called, actually If we simply write `driver.findElement(By.xpath("//a[not(@class='disabled') and @id='ctl00_ContentView_LinkButtonNext1']")).click` it works fine(giving implicit wait). This is just waiting for this particular element to exist. Element to be clickable function goes out of scope in this place.
type: Comment
score: 0
type: AnswerComment

calibration
tag name: calibration
type: Tag
tags question: http://stackoverflow.com/q/51635126

http://stackoverflow.com/q/51610133
accepted answer: http://stackoverflow.com/a/51612107
answer count: 1
has comment: http://stackoverflow.com/comment/90188433
has comment: http://stackoverflow.com/comment/90188736
has title: TypeError: a float is required pyspark
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51612107
tagged with: python
has comment: http://stackoverflow.com/comment/90185148
type: AnsweredQuestion
type: Question
has body: I aim to calculate the haversine distance of the lat-long data ,I have used uci dataset for the same https://archive.ics.uci.edu/ml/datasets/GPS+Trajectories (go_track_trackspoints.csv) I have used below code to calculate the distance def dist(lon2, lat2,lon1, lat1): phi_1=toRadians(lat1) phi_2=toRadians(lat2) delta_phi=toRadians(lat2-lat1) delta_lambda=toRadians(lon2-lon1) a=sin(delta_phi/2.0)**2+cos(phi_1)*cos(phi_2)*sin(delta_lambda/2.0)**2 c=2*atan2(sqrt(abs(a)),sqrt(abs((1-a)))) return c * 6372.8 And Schema is root |-- id: string (nullable = true) |-- latitude: string (nullable = true) |-- longitude: string (nullable = true) |-- track_id: string (nullable = true) |-- time: string (nullable = true) I have loaded the data into a spark dataframe (gps_data) +---+-----------------+-----------------+--------+-------------------+ | id| latitude| longitude|track_id| time| +---+-----------------+-----------------+--------+-------------------+ | 1|-10.9393413858164|-37.0627421097422| 1|2014-09-13 07:24:32| | 2| -10.939341385769|-37.0627421097809| 1|2014-09-13 07:24:37| | 3|-10.9393239478718|-37.0627645137212| 1|2014-09-13 07:24:42| | 4|-10.9392105616561|-37.0628430455445| 1|2014-09-13 07:24:47| +---+-----------------+-----------------+--------+-------------------+ Using the below command I am trying to get a column of distance my_window = Window.partitionBy().orderBy("time") gps_d=gps_data.withColumn("dist", dist( "longitude", "latitude", lag("longitude", 1).over(my_window), lag("latitude", 1).over(my_window) ).alias("dist")) But I am not able to solve an error and not able to find a solution either .Please help me! Error is : --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-219-6352041ff223&gt; in &lt;module&gt;() 1 gps_d=gps_data.withColumn("dist", dist( 2 "longitude", "latitude", ----&gt; 3 lag("longitude", 1).over(my_window), lag("latitude", 1).over(my_window) 4 ).alias("dist")) …
tagged with: pyspark
has comment: http://stackoverflow.com/comment/90185391
score: 0
has comment: http://stackoverflow.com/comment/90188161
tagged with: apache-spark

http://stackoverflow.com/q/51496012
upvote count: 3
tagged with: pandas
tagged with: mean
answer count: 1
linked to: http://stackoverflow.com/q/39409180
favorite count: 0
has answer: http://stackoverflow.com/a/51496084
accepted answer: http://stackoverflow.com/a/51496084
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: aggregate
type: Question
has body: I want to group-by three columns, and then find the mean of a fourth numerical column for all rows which are duplicated across the first three columns. I can achieve this with the following function: df2 = df.groupby(['col1', 'col2', 'col3'], as_index=False)['col4'].mean() The problem is that I also want a fifth column which will aggregate for all rows grouped by the groupby function, which I don't know how to do on top of the previous function. For example: df index col1 col2 col3 col4 col5 0 Week_1 James John 1 when and why? 1 Week_1 James John 3 How? 2 Week_2 James John 2 Do you know when? 3 Week_2 Mark Jim 3 What time? 4 Week_2 Andrew Simon 1 How far is it? 5 Week_2 Andrew Simon 2 Are you going? CURRENT(with above function): index col1 col2 col3 col4 0 Week_1 James John 2 1 Week_2 James John 2 2 Week_2 Mark Jim 3 3 Week_2 Andrew Simon 1.5 DESIRED: index col1 col2 col3 col4 col5 0 Week_1 James John 2 when and why?, How? 2 Week_2 James John 2 Do you know when? 3 Week_2 Mark Jim 3 What time? 4 Week_2 Andrew Simon 1.5 How far is it?, Are you going? I've tried here and here, however the .mean() function I'm using complicates the process. Any help would be appreciated. (If possible, I would like to specify a custom delimiter separating the strings of col5 when aggregated).
linked to: http://stackoverflow.com/q/35901959
has title: Python - Group-by multiple columns with .mean() and .agg()

http://stackoverflow.com/q/51484491
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51484584
has body: I want to store into a variable the last output of a subprocess after the user performs a Keyboard Interrupt. My problem is mainly with a subprocess without end, i.e. tail in my exemple below. Here is my code: class Testclass: def Testdef(self): try: global out print "Tail running" tail_cmd='tail -f log.Reconnaissance' proc = subprocess.Popen([tail_cmd], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() except KeyboardInterrupt: print("KeyboardInterrupt received, stopping…") finally: print "program output:", out if __name__ == "__main__": app = Testclass() app.Testdef() Below is its output, which I don't understand at this moment. Tail running program output: Traceback (most recent call last): File "./2Test.py", line 19, in &lt;module&gt; app.Testdef() File "./2Test.py", line 15, in Testdef print "program output:", out NameError: global name 'out' is not defined
has title: Get output of subprocess after Keyboard Interrupt
type: Question
tagged with: python
tagged with: subprocess
score: 0

http://stackoverflow.com/q/51565081
tagged with: python-3.x
upvote count: 0
has answer: http://stackoverflow.com/a/51565106
has title: Python - How to merge multiple dictionaries that exist in a list
type: UnansweredQuestion
downvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/11011756
type: Question
has comment: http://stackoverflow.com/comment/90097107
score: -2
has body: I have in my code a list with multiple dictionaries in it (at the moment I have a specific number of dictionaries, but I need the program to work for any n numbers of dictionaries). For example, let say I have 3 dictionaries to simplify: What I have: my_list = [{'a': 1, 'b': 2, 'c': 3}, {'b':4, 'c': 5, 'd': 6}, {'c':7, 'd': 8, 'e': 9}] what I need: my_list = [{'a': 1, 'b': 6, 'c': 15, 'd': 14, 'e': 9}] or my_list = {'a': 1, 'b': 6, 'c': 15, 'd': 14, 'e': 9} (It's essentially the same thing, isn't it?) Thank you for your help!!!
linked to: http://stackoverflow.com/q/9415785
has comment: http://stackoverflow.com/comment/90105810
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/90064393
comment on: http://stackoverflow.com/q/51547926
has text: An overlooked question: *why* are you storing your images in your database, instead of "as images on a filesystem", storing the metadata in the DB only?
score: 2
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51615849
upvote count: 7
has comment: http://stackoverflow.com/comment/90197165
has answer: http://stackoverflow.com/a/51616256
type: Question
possible better answer: http://stackoverflow.com/a/51616548
answer count: 2
has title: Pandas - Using `.rolling()` on multiple columns
has answer: http://stackoverflow.com/a/51616548
tagged with: dataframe
has body: Consider a pandas DataFrame which looks like the one below A B C 0 0.63 1.12 1.73 1 2.20 -2.16 -0.13 2 0.97 -0.68 1.09 3 -0.78 -1.22 0.96 4 -0.06 -0.02 2.18 I would like to use the function .rolling() to perform the following calculation for t = 0,1,2: Select the rows from t to t+2 Take the 9 values contained in those 3 rows, from all the columns. Call this set S Compute the 75th percentile of S (or other summary statistics about S) For instance, for t = 1 we have S = { 2.2 , -2.16, -0.13, 0.97, -0.68, 1.09, -0.78, -1.22, 0.96 } and the 75th percentile is 0.97. I couldn't find a way to make it work with .rolling(), since it apparently takes each column separately. I'm now relying on a for loop, but it is really slow. Do you have any suggestion for a more efficient approach?
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/51616256
score: 7
has comment: http://stackoverflow.com/comment/90197128
favorite count: 0
has comment: http://stackoverflow.com/comment/108461405
tagged with: rolling-computation
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/90197648
has comment: http://stackoverflow.com/comment/90197365

http://stackoverflow.com/a/51497791
accepted answer of: http://stackoverflow.com/q/51495982
upvote count: 23
has comment: http://stackoverflow.com/comment/90053618
has comment: http://stackoverflow.com/comment/90053706
has comment: http://stackoverflow.com/comment/90053519
has comment: http://stackoverflow.com/comment/90002942
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90053379
has body: You can use plt.text to place the information at the positions according to your data. However, if you have very small bars, it might need some tweaking to look perfect. df_total = df['Total Cost'] df = df.iloc[:, 0:4] df.plot(x = 'Airport', kind='barh',stacked = True, title = 'Breakdown of Costs', mark_right = True) df_rel = df[df.columns[1:]].div(df_total, 0)*100 for n in df_rel: for i, (cs, ab, pc, tot) in enumerate(zip(df.iloc[:, 1:].cumsum(1)[n], df[n], df_rel[n], df_total)): plt.text(tot, i, str(tot), va='center') plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center') EDIT: Some arbitrary ideas for better readability: shift the total values to the right, use 45° rotated text: plt.text(tot+10000, i, str(tot), va='center') plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center', rotation=45) switch between top- and bottom-aligned text: va = ['top', 'bottom'] va_idx = 0 for n in df_rel: va_idx = 1 - va_idx for i, (cs, ab, pc, tot) in enumerate(zip(df.iloc[:, 1:].cumsum(1)[n], df[n], df_rel[n], df_total)): plt.text(tot+10000, i, str(tot), va='center') plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va=va[va_idx], ha='center') label only bars with 10% or more: if pc &gt;= 10: plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center') ...or still print them, but vertical: if pc &gt;= 10: plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center') else: plt.text(cs - ab/2, i, str(np.round(pc, 1)) + '%', va='center', ha='center', rotation=90)
has comment: http://stackoverflow.com/comment/90053433
score: 23
has comment: http://stackoverflow.com/comment/90053053
type: Answer
answers question: http://stackoverflow.com/q/51495982
has comment: http://stackoverflow.com/comment/90053215
has comment: http://stackoverflow.com/comment/90011360
has comment: http://stackoverflow.com/comment/90054019

http://stackoverflow.com/comment/90098479
type: AnswerComment
has text: Looks like the "more conventional" way also works. Thank you both for helping me !
type: Comment
comment on: http://stackoverflow.com/a/51565725
score: 0

http://stackoverflow.com/comment/90012788
has text: Should be `pip install -r requirements.txt`
comment on: http://stackoverflow.com/q/51507842
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90204319
type: Comment
comment on: http://stackoverflow.com/a/51619368
has text: _Using `GET.get()` is a bad pratice_. That's not true. Especially considering how it used in OP question. It's a clean way of specifying a default value.
type: AnswerComment
score: 0

pca
tag name: pca
tags question: http://stackoverflow.com/q/51540847
type: Tag
tags question: http://stackoverflow.com/q/51576272
tags question: http://stackoverflow.com/q/51580996
tags question: http://stackoverflow.com/q/51546736
tags question: http://stackoverflow.com/q/51610821
tags question: http://stackoverflow.com/q/51526515

http://stackoverflow.com/a/51587462
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51587347
has body: myData.txt: a b c 1 2 3 4 5 6 Then You can use Pandas: import pandas as pd df=pd.read_csv('myData.txt',sep='\s+') df.to_csv('someFileName.csv')
has comment: http://stackoverflow.com/comment/90166366
type: Answer
has comment: http://stackoverflow.com/comment/90173621
has comment: http://stackoverflow.com/comment/90166109
has comment: http://stackoverflow.com/comment/90173614
answers question: http://stackoverflow.com/q/51587347
score: 0

http://stackoverflow.com/comment/89978556
score: 0
type: Comment
has text: @ankiiiiiii you shouldn't use the tarfile module. I edited the answer.
comment on: http://stackoverflow.com/a/51504727
type: AnswerComment

http://stackoverflow.com/comment/90132905
score: 0
comment on: http://stackoverflow.com/q/51583699
type: Comment
type: QuestionComment
has text: @PatrickArtner Yeah, I don't get why so many teachers do this. There are simple problems that call out for recursion. Instead of giving one of those problems, they come up with a problem that calls out for a loop and demand that you do it with recursion. As a later exercise, to show you how recursion and loops are dual after you understand both of them, this would make sense, but as a first-week assignment teaching recursion for the first time? It's like they just want to mislead their students…

http://stackoverflow.com/a/51582317
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51582175
answers question: http://stackoverflow.com/q/51582175
downvote count: 0
type: AcceptedAnswer
has body: The problem is in the way you accumulate you data. It should be done in the for loop. You don't need an extra video_count. Just sum them up in industry_data like so: industry_data = {} for key in video_ads: company = key["company"] if company in industry_data: industry_data[company] += 1 else: industry_data[company] = 1 print(industry_data) # {'Uber': 3, 'Grab': 1}
upvote count: 2

http://stackoverflow.com/q/51503819
downvote count: 1
has answer: http://stackoverflow.com/a/51514423
score: -1
has comment: http://stackoverflow.com/comment/89976317
has answer: http://stackoverflow.com/a/67269711
type: Question
answer count: 2
upvote count: 0
favorite count: 0
tagged with: centos
has comment: http://stackoverflow.com/comment/89980242
has body: I have installed tkinter package but the default Python (which is version 2.7) on CentOS 7 still complains that this package doesn't exist. sudo rpm --query centos-release centos-release-7-5.1804.el7.centos.2.x86_64 sudo yum install tkinter ... Package tkinter-2.7.5-69.el7_5.x86_64 already installed and latest version python -m tkinter /usr/bin/python: No module named tkinter python Python 2.7.5 (default, Jul 13 2018, 13:06:57) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tkinter Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named tkinter
tagged with: python
has title: How do I install tkinter for the default Python 2.7 on CentOS 7
tagged with: tkinter
type: UnansweredQuestion

http://stackoverflow.com/a/51584109
has comment: http://stackoverflow.com/comment/90152830
answers question: http://stackoverflow.com/q/51559330
type: Answer
accepted answer of: http://stackoverflow.com/q/51559330
score: 1
upvote count: 1
has body: Firstly you need to fix your average calc (operator precedence): avg_sum1 / (len(dd) / 2) # or avg_sum1 / len(dd) * 2 Out[]: 0.31740819000001924 2.8 s ± 28.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) You can do this in numpy, e.g.: In []: np.where(dd[1::2] &lt;= 10, dd[1::2]*0.1, dd[0::2]*0.01).mean() Out[]: 0.31740818999999987 10.8 ms ± 61.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90024268
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51527805
score: 0
has text: `global <name>` goes inside a function that tries to alter the global.

http://stackoverflow.com/a/51608314
answers question: http://stackoverflow.com/q/51591510
score: 0
type: Answer
has body: I have realized what I have done wrong. When I write a code line as the one bellow, I am comparing the words 'job.txt' with 'LucasQuadros.txt' and not the documents per se. similar('job.txt','LucasQuadros.txt') To change that I simply included the .read function on my code as: jd = open('job.txt') jd = jd.read() cv1= ('LucasQuadros.txt') cv1= cv1.read() from difflib import SequenceMatcher def similar(a, b): return SequenceMatcher(None, a, b).ratio() similar(jd, cv1) 0.0 similar(jd,cv2) 0.007104795737122558 Now the similarity is correct. As I said it above, it was a pretty beginners mistake.

http://stackoverflow.com/q/51490254
tagged with: keras
tagged with: deep-learning
accepted answer: http://stackoverflow.com/a/51507217
type: AnsweredQuestion
tagged with: python
favorite count: 0
has title: Fine tuned keras .h5 model to .pb model used in c++ gives running model failed error
tagged with: c++
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/89950190
answer count: 1
tagged with: tensorflow
has body: I've fine tuned VGG16 model and saved the model with best accuracy. My keras code is - #Input size rows = 125 column = 125 channels = 3 #RGB #Resizing def read_images(src): #read every image and resize every image to same size img = Image.open(src) #print(img.size) #method = Image.NEAREST if img.size == (rows,column) else Image.ANTIALIAS im_rz = img.resize((rows,column), Image.ANTIALIAS) #im_rz = resize_image_to_square(img, new_size = (rows,column)) #im_rz = ImageOps.fit(img, (rows,column), method = method) return im_rz #Conversion of image to np l = LabelEncoder() y_all = l.fit_transform(y_all) y_all = np_utils.to_categorical(y_all) #print(l.classes_) #x_train, x_valid, y_train, y_valid = test_train_split(x_all, y_all, test_size = 0.2, random_state = 42, stratify = y_all) x_train, x_test, y_train, y_test = train_test_split(x_all, y_all, test_size = 0.2, random_state = 42, stratify = y_all) batch_size = 32 nb_classes = 3 epochs = 300 x_train = np.array(x_train).astype('float32') x_test = np.array(x_test).astype('float32') y_train = np.array(y_train).astype('float32') y_test = np.array(y_test).astype('float32') x_train /= 255. x_test /= 255. #model vgg = VGG16(weights='imagenet', include_top=False, input_shape=(125, 125, 3)) # Freeze the layers except the last 4 layers for layer in vgg.layers[:-4]: layer.trainable = False # Check the trainable status of the individual layers for layer in vgg.layers: print(layer, layer.trainable) model = Sequential() # Add the vgg convolutional base model model.add(vgg_conv) # Add new layers model.add(layers.Flatten()) model.add(layers.Dense(1024, activation='relu')) model.add(layers.Dropout(0.5)) model.add(layers.Dense(3, activation='softmax')) print(model.summary()) opt = keras.optimizers.RMSProp(lr=1e-4) # #Training the model using optimizer model.compile(loss='categorical_crossentropy',optimizer=opt,metrics=['accuracy']) #Save the best model obtained during training #from keras.callbacks import ReduceLROnPlateau #lr_reduce = Reduc…
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51507217

forms
tags question: http://stackoverflow.com/q/51517599
tags question: http://stackoverflow.com/q/51630239
type: Tag
tags question: http://stackoverflow.com/q/51583731
tags question: http://stackoverflow.com/q/51596433
tags question: http://stackoverflow.com/q/51543266
tag name: forms
tags question: http://stackoverflow.com/q/51626461
tags question: http://stackoverflow.com/q/51525462

http://stackoverflow.com/q/51576125
has answer: http://stackoverflow.com/a/51576366
score: 3
has comment: http://stackoverflow.com/comment/90118043
possible better answer: http://stackoverflow.com/a/51576357
has answer: http://stackoverflow.com/a/51576352
answer count: 3
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/51576366
has title: Python Pandas- Find the first instance of a value exceeding a threshold
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/51576357
has body: I am trying to find the first instance of a value exceeding a threshold based on another Python Pandas data frame column. In the code below, the "Trace" column has the same number for multiple rows. I want to find the first instance where the "Value" column exceeds 3. Then, I want to take the rest of the information from that row and export it to a new Pandas data frame (like in the second example). Any ideas? d = {"Trace": [1,1,1,1,2,2,2,2], "Date": [1,2,3,4,1,2,3,4], "Value": [1.5,1.9,3.1,5.5,1.1,3.6,1.9,6.2]} df = pd.DataFrame(data=d)
type: Question

http://stackoverflow.com/comment/90098913
type: AnswerComment
comment on: http://stackoverflow.com/a/51565167
score: 0
type: Comment
has text: I updated the question. I was trying to use function but i think do the same with your suggestion

http://stackoverflow.com/comment/90085039
comment on: http://stackoverflow.com/q/51558901
has text: I don't understand your question. To connect an event to the canvas, you need to have a reference to the figure. How are you creating your figure? Please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51584535
upvote count: 2
has answer: http://stackoverflow.com/a/51584600
has comment: http://stackoverflow.com/comment/90134618
type: Question
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/51584600
answer count: 1
has comment: http://stackoverflow.com/comment/90134561
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90134546
has title: Getting the indexes of an element in a subset
tagged with: python
has comment: http://stackoverflow.com/comment/90134651
has body: I have an list and a subset of it, and want to find the index of each element in the subset. I have currently tried this code: def convert_toindex(listof_elements, listof_indices): for i in range(len(listof_elements)): listof_elements[:] = [listof_indices.index(x) for x in listof_elements] return listof_elements list1 = ['lol', 'please', 'help'] list2 = ['help', 'lol', 'please', 'extra'] What I want to happen when I do convert_toindex(list1, list2) is the output to be [2, 0, 1] However, when I do this I get a ValueError: '0' is not in list. 0, however, appears nowhere in either list so I am not sure why this is happening. Secondly, if I have a list of lists, and I want to do this process all the nested lists inside the big list, would I do something like this? for smalllist in biglist: smalllist[:] = [dict_of_indices[x] for x in smalllist] Where dict_of_indices is the dictionary of indices created following the top answer.
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/90071271
comment on: http://stackoverflow.com/q/51552017
score: 0
type: QuestionComment
type: Comment
has text: It is biowikia.kv

http://stackoverflow.com/q/51529641
has comment: http://stackoverflow.com/comment/90027534
has answer: http://stackoverflow.com/a/51529724
has comment: http://stackoverflow.com/comment/90027575
has title: 1064: SQL syntax error executing PyMySQL query
score: 3
answer count: 1
downvote count: 0
tagged with: pymysql
accepted answer: http://stackoverflow.com/a/51529724
favorite count: 0
has body: I am using PyMySQL to execute SQL query commands from python. My pystyle is pyformat which was found using: &gt;&gt;&gt; pymysql.paramstyle pyformat My db and cursor details are as follows: &gt;&gt;&gt; MYDB = pymysql.connect(_params_) &gt;&gt;&gt; cursor = MYDB.cursor() I then execute a SQL query using, &gt;&gt;&gt; cursor.execute("SELECT * FROM %(tablename)s", {"tablename": "activity"}) I get an error stating, ProgrammingError: (1064, u"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 '''activity''' at line 1") On the other hand, the query by itself works, &gt;&gt;&gt; unsafe_sql = ("Select * from activity") &gt;&gt;&gt; cursor.execute(unsafe_sql) &gt;&gt;&gt; 4 I am not sure what is going on with my first query. Any help appreciated.
has comment: http://stackoverflow.com/comment/90027617
linked to: http://stackoverflow.com/q/16649447
tagged with: python
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/16649447
upvote count: 3
linked to: http://stackoverflow.com/q/11321491
tagged with: mysql
has comment: http://stackoverflow.com/comment/90027597
type: Question

http://stackoverflow.com/q/51570585
accepted answer: http://stackoverflow.com/a/51571539
tagged with: dataframe
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90108251
type: AnsweredQuestion
has title: Construct a data frame which group items based on another data frame
has answer: http://stackoverflow.com/a/51571539
has body: I have a data frame that looks like that df = ID CODE 0 id1 A 1 id1 B 2 id1 C 3 id2 D 4 id2 E 5 id3 A 6 id3 E 7 id3 F I want to create pandas data frame from df that's look like that df2 = ID CODE1 CODE2 0 id1 A B 1 id1 A C 2 id1 B C 3 id2 D E 4 id3 A E 5 id3 A F 6 id3 E F I want to make pairs for code in two columns with respect to the ID I'm new in pandas data frame and I don't have any idea how to achieve that Note: df data frame contains thousands of records this is just example thanks for any help
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/q/51567310
answer count: 1
has title: pandas: resample.apply discards index names
score: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/90102359
has body: For some reason doing df.resample("M").apply(foo) drops the index name in df. Is this expected behavior? import pandas as pd df = pd.DataFrame({"a": np.arange(60)}, index=pd.date_range(start="2018-01-01", periods=60)) df.index.name = "dte" df.head() # a #dte #2018-01-01 0 #2018-01-02 1 #2018-01-03 2 #2018-01-04 3 #2018-01-05 4 def f(x): print(x.head()) df.resample("M").apply(f) #2018-01-01 0 #2018-01-02 1 #2018-01-03 2 #2018-01-04 3 #2018-01-05 4 #Name: a, dtype: int64 update/clarification: When I said drops the name I meant that series received by the function doesn't have a name component associated with its index
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51568199
type: Question
has comment: http://stackoverflow.com/comment/90102337

http://stackoverflow.com/comment/90186841
type: Comment
has text: try `len(row)`?
score: 0
comment on: http://stackoverflow.com/q/51611126
type: QuestionComment

http://stackoverflow.com/q/51630874
upvote count: 1
downvote count: 0
has body: Previously, I used a Morningstar API to get stock data; however, now that I am away from USA for a week, I am not being able to access the data. This is the code snippet: import datetime as dt from dateutil.relativedelta import relativedelta import matplotlib.pyplot as plt from matplotlib import style import pandas as pd pd.core.common.is_list_like = pd.api.types.is_list_like import pandas_datareader.data as web import csv from mpl_finance import candlestick_ohlc import matplotlib.dates as mdates from matplotlib.dates import DateFormatter, MonthLocator, YearLocator, DayLocator, WeekdayLocator style.use( 'ggplot' ) end = dt.date.today() start_48 = end - relativedelta( years=4 ) start_120 = end - relativedelta( years=10 ) ticker = input( 'Ticker: ' ) #should be in Uppercase ticker = ticker.upper() df_w = web.DataReader( ticker, 'morningstar', start_48, end ) df_m = web.DataReader( ticker, 'morningstar', start_120, end ) print() file_name_w = ticker + 'weekly.csv' file_name_m = ticker + 'monthly.csv' df_w.to_csv( file_name_w ) df_m.to_csv( file_name_m ) df_w = pd.read_csv( file_name_w, parse_dates=True, index_col=0 ) df_m = pd.read_csv( file_name_m, parse_dates=True, index_col=0 ) This is the error message: Ticker: spy Traceback (most recent call last): File "/Users/zubairjohal/Documents/OHLC.py", line 24, in &lt;module&gt; df_w = web.DataReader( ticker, 'morningstar', start_48, end ) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas_datareader/data.py", line 391, in DataReader session=session, interval="d").read() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas_datareader/mstar/daily.py", line 219, in read df = self._dl_mult_symbols(symbols=symbols) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas_datareader/mstar/daily.py", line 130, in _dl_mult_symbols resp.status_code, resp.reason)) Exception: Request Error!: 404 : Not Found Is it an IP issu…
accepted answer: http://stackoverflow.com/a/51636860
favorite count: 0
has answer: http://stackoverflow.com/a/51631219
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51636860
tagged with: pandas-datareader
has title: Getting a Request Error 404 in Python while accessing an API
type: AnsweredQuestion
tagged with: quantitative-finance
possible better answer: http://stackoverflow.com/a/51631219
score: 1
type: Question
answer count: 2

http://stackoverflow.com/q/51592247
has comment: http://stackoverflow.com/comment/90151778
tagged with: https
has comment: http://stackoverflow.com/comment/90150132
has comment: http://stackoverflow.com/comment/90150139
has comment: http://stackoverflow.com/comment/90259093
tagged with: httprequest
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51592571
has comment: http://stackoverflow.com/comment/90150086
has body: The title pretty much says it. I need to make sure that while I am working with python modules there isn't any sort of malicious code in the module, specifacily the type that scrapes data from the machine runnign the code and sends it elsewhere? do i have a method of doing that with python? can i be certain this is done even when i am using modules like requests for sending and receiving HTTP GET\POST requests? I mean is there a way to check this without reading every line of code in module?
has comment: http://stackoverflow.com/comment/90258882
has title: How to check if a python module is sending my data when i use it?
tagged with: security
score: 0
has answer: http://stackoverflow.com/a/51592377
tagged with: python
linked to: http://stackoverflow.com/q/51560850
has comment: http://stackoverflow.com/comment/90151951
type: UnansweredQuestion

http://stackoverflow.com/comment/89977521
has text: This may be related to [this](https://stackoverflow.com/questions/38356584/python-multiprocessing-threading-code-exits-early) problem.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51485284
score: 1

http://stackoverflow.com/q/51532316
has answer: http://stackoverflow.com/a/51535305
answer count: 1
score: 4
favorite count: 0
upvote count: 4
tagged with: image-morphology
tagged with: python
has title: matlab function strel("line") to python
tagged with: matlab
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/51535305
tagged with: image-processing
type: Question
has body: I want to use the matlab function strel("line") in python I found python library like scikit-learn / opencv / mahotas but I can't find it. finally, I found similar function in pymorph 'seline' but it is different to matlab strel function. specifically, I want to use(or implement) strel("line") and rotate it. like strel("line", length, degree) Matlab example a = strel("line",5,0) b = strel("line",5,30) c = strel("line",5,45) output is like this. Anyone who knows the algorithm of matlab's strel("line",length,degree) function or python library equal to strel("line",length,degree), please let me know. thank you.

selenium
tags question: http://stackoverflow.com/q/51604230
tags question: http://stackoverflow.com/q/51572802
tags question: http://stackoverflow.com/q/51561450
tags question: http://stackoverflow.com/q/51508532
tags question: http://stackoverflow.com/q/51538665
tags question: http://stackoverflow.com/q/51560030
tags question: http://stackoverflow.com/q/51515137
tags question: http://stackoverflow.com/q/51532831
tags question: http://stackoverflow.com/q/51502216
tags question: http://stackoverflow.com/q/51524463
tags question: http://stackoverflow.com/q/51545040
tags question: http://stackoverflow.com/q/51539818
tags question: http://stackoverflow.com/q/51573844
tags question: http://stackoverflow.com/q/51504428
tags question: http://stackoverflow.com/q/51542203
tags question: http://stackoverflow.com/q/51534651
tags question: http://stackoverflow.com/q/51611963
tags question: http://stackoverflow.com/q/51590374
tags question: http://stackoverflow.com/q/51554027
tags question: http://stackoverflow.com/q/51548638
tags question: http://stackoverflow.com/q/51532832
tags question: http://stackoverflow.com/q/51611689
tags question: http://stackoverflow.com/q/51637641
tags question: http://stackoverflow.com/q/51528556
tags question: http://stackoverflow.com/q/51629107
tags question: http://stackoverflow.com/q/51632860
tags question: http://stackoverflow.com/q/51605387
tags question: http://stackoverflow.com/q/51489746
tags question: http://stackoverflow.com/q/51634171
tags question: http://stackoverflow.com/q/51542001
tags question: http://stackoverflow.com/q/51482697
tags question: http://stackoverflow.com/q/51564332
tags question: http://stackoverflow.com/q/51510049
tags question: http://stackoverflow.com/q/51639372
tags question: http://stackoverflow.com/q/51578683
tag name: selenium
tags question: http://stackoverflow.com/q/51499962
tags question: http://stackoverflow.com/q/51493599
tags question: http://stackoverflow.com/q/51515221
tags question: http://stackoverflow.com/q/51528985
tags question: http://stackoverflow.com/q/51598471
tags question: http://stackoverflow.com/q/51514715
tags question: http://stackoverflow.com/q/51571530
tags question: http://stackoverflow.com/q/51578424
tags question: http://stackoverflow.com/q/51617433
tags question: http://stackoverflow.com/q/51491211
tags question: http://stackoverflow.com/q/51518620
tags question: http://stackoverflow.com/q/51585965
tags question: http://stackoverflow.com/q/51612549
tags question: http://stackoverflow.com/q/51511142
tags question: http://stackoverflow.com/q/51495609
tags question: http://stackoverflow.com/q/51584821
tags question: http://stackoverflow.com/q/51637504
tags question: http://stackoverflow.com/q/51507005
tags question: http://stackoverflow.com/q/51519601
tags question: http://stackoverflow.com/q/51637326
tags question: http://stackoverflow.com/q/51489331
tags question: http://stackoverflow.com/q/51637794
tags question: http://stackoverflow.com/q/51634550
tags question: http://stackoverflow.com/q/51609710
tags question: http://stackoverflow.com/q/51595563
tags question: http://stackoverflow.com/q/51491656
tags question: http://stackoverflow.com/q/51577185
tags question: http://stackoverflow.com/q/51530240
tags question: http://stackoverflow.com/q/51553348
tags question: http://stackoverflow.com/q/51573449
tags question: http://stackoverflow.com/q/51507299
tags question: http://stackoverflow.com/q/51541444
tags question: http://stackoverflow.com/q/51572132
tags question: http://stackoverflow.com/q/51638754
tags question: http://stackoverflow.com/q/51509600
tags question: http://stackoverflow.com/q/51553874
tags question: http://stackoverflow.com/q/51589224
tags question: http://stackoverflow.com/q/51599659
tags question: http://stackoverflow.com/q/51507047
tags question: http://stackoverflow.com/q/51483471
type: Tag
tags question: http://stackoverflow.com/q/51546819
tags question: http://stackoverflow.com/q/51627852
tags question: http://stackoverflow.com/q/51608018

http://stackoverflow.com/a/51614104
has comment: http://stackoverflow.com/comment/90224504
has body: Thanks a lot for your well detailled answer ! I tried your example and it works fine. After passing through some troubles trying to reproduce/adapt your idea to my code, now it compiles but doesn't work ... I made some changes in the interface file, my complete interface file is : pixy.i %module pixy %{ #define SWIG_FILE_WITH_INIT #include "pixy.h" %} %include "stdint.i" %include "carrays.i" %include "numpy.i" %init%{ import_array(); %} %apply (unsigned char** ARGOUTVIEW_ARRAY1, uint16_t* DIM1) {(unsigned char** current_frame, uint16_t* nbPixels)} //%include "pixy.h" //&lt;--- Error : Unable to find 'pixy.h' %array_class(struct Block, BlockArray); int pixy_init(); void pixy_close(); void pixy_error(int error_code); int pixy_blocks_are_new(); int pixy_get_blocks(uint16_t max_blocks, BlockArray *blocks); int pixy_rcs_set_position(uint8_t channel, uint16_t position); struct Block { uint16_t type; uint16_t signature; uint16_t x; uint16_t y; uint16_t width; uint16_t height; int16_t angle; }; // Inspired from the block struct above struct PixyFrame // if not written { // &gt;&gt;&gt; interpreter = pixy.PixyFrame() // &gt;&gt;&gt; Error : PixyFrame not defined int get_frame (unsigned char** current_frame, uint16_t* nbPixels); // if not added // &gt;&gt;&gt; interpreter = PixyFrame() // &gt;&gt;&gt; frame = interpreter.get_frame() // AttributeError: type object 'object' has no attribute '__getattr__' }; I've seen many example like : foo.i %module foo %{ #include "foo.h" %} %include "foo.h" but the last include returns an error in my file: Error : Unable to find 'pixy.h' I can almost reproduce your example with my interface file, but, when I call get_frame() : &gt;&gt;&gt; interpreter = PixyFrame() &gt;&gt;&gt; frame = interpreter.get_frame() TypeError: get_frame() takes exactly 3 arguments (1 given) The 3 arguments needed are (self, unsigned char **, uint16_t ) and while building I get this warning : pixy.i:17: Warning 453: Can't apply (unsigned char **ARGOUTVIEW_ARRAY1,uin…
has comment: http://stackoverflow.com/comment/90225763
has comment: http://stackoverflow.com/comment/90231981
has comment: http://stackoverflow.com/comment/90234059
has comment: http://stackoverflow.com/comment/90224205
has comment: http://stackoverflow.com/comment/90224409
has comment: http://stackoverflow.com/comment/90250450
score: 0
has comment: http://stackoverflow.com/comment/90221111
type: Answer
answers question: http://stackoverflow.com/q/51598137
has comment: http://stackoverflow.com/comment/90221131
has comment: http://stackoverflow.com/comment/90224159

http://stackoverflow.com/a/51617132
type: Answer
has comment: http://stackoverflow.com/comment/90209327
score: 1
has comment: http://stackoverflow.com/comment/90209273
has comment: http://stackoverflow.com/comment/90209578
upvote count: 1
has comment: http://stackoverflow.com/comment/90208699
has comment: http://stackoverflow.com/comment/90248361
has body: from sqlalchemy import and_ allocation_obj_to_delete _list=session.query(Allocation_Film_Genre).join(Film).join(Genre).filter(and_(Film.name=='Saw',Genre.name=="Comedy")).all() for obj in allocation_obj_to_delete: session.delete(obj) session.commit() Joined query and delete the objects
has comment: http://stackoverflow.com/comment/90209694
accepted answer of: http://stackoverflow.com/q/51614196
has comment: http://stackoverflow.com/comment/90209284
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51614196
has comment: http://stackoverflow.com/comment/90209070
has comment: http://stackoverflow.com/comment/90209517
has comment: http://stackoverflow.com/comment/90209312
has comment: http://stackoverflow.com/comment/90209416
has comment: http://stackoverflow.com/comment/90248504

http://stackoverflow.com/q/51545893
tagged with: error-handling
type: Question
score: 3
tagged with: contextmanager
linked to: http://stackoverflow.com/q/28157929
accepted answer: http://stackoverflow.com/a/51545957
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has body: I have the following code from contextlib import contextmanager @contextmanager def simple_context_manager(): print("starting context manager") yield print("finished context manager") try: with simple_context_manager(): raise RuntimeError except RuntimeError: print("Caught the error") print("Moving on") Right now it prints out starting context manager Caught the error Moving on which tells me that the context manager isn't closing. How can I get it to close and print the "finished context manager" line? Since I'm using the decorator, I don't have a dedicated __exit__ function that I think should be called according to this. So I'm not sure how to get my context manager to exit in the case of an error occurring inside of its context.
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51545957
upvote count: 3
has title: Getting a context manager created with @contextmanager to work properly with exceptions

nltk
tags question: http://stackoverflow.com/q/51485167
tags question: http://stackoverflow.com/q/51631439
tags question: http://stackoverflow.com/q/51547932
tags question: http://stackoverflow.com/q/51486403
tags question: http://stackoverflow.com/q/51609143
tags question: http://stackoverflow.com/q/51496215
tags question: http://stackoverflow.com/q/51514208
tags question: http://stackoverflow.com/q/51634328
tags question: http://stackoverflow.com/q/51490620
tags question: http://stackoverflow.com/q/51526478
tags question: http://stackoverflow.com/q/51605036
tags question: http://stackoverflow.com/q/51534586
tags question: http://stackoverflow.com/q/51560662
tags question: http://stackoverflow.com/q/51608482
tag name: nltk
tags question: http://stackoverflow.com/q/51522743
tags question: http://stackoverflow.com/q/51543714
tags question: http://stackoverflow.com/q/51518059
type: Tag
tags question: http://stackoverflow.com/q/51591216
tags question: http://stackoverflow.com/q/51569637

http://stackoverflow.com/comment/90092347
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51562730
has text: Are you returning any values in your init_x() method? Or do you want to affect the class-scope `x` variable?
score: 0

http://stackoverflow.com/a/51512011
has comment: http://stackoverflow.com/comment/89992995
has comment: http://stackoverflow.com/comment/89993591
accepted answer of: http://stackoverflow.com/q/51511972
has comment: http://stackoverflow.com/comment/89992654
type: Answer
has comment: http://stackoverflow.com/comment/89992706
upvote count: 1
has body: You can use this: df = df.sort_values(by=['id_student'])
has comment: http://stackoverflow.com/comment/89993023
has comment: http://stackoverflow.com/comment/89992536
has comment: http://stackoverflow.com/comment/89993043
score: 1
has comment: http://stackoverflow.com/comment/89992470
has comment: http://stackoverflow.com/comment/89992912
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51511972

http://stackoverflow.com/q/51599798
linked to: http://stackoverflow.com/q/18408307
has answer: http://stackoverflow.com/a/51599859
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90165644
tagged with: python
has body: I have a nice URL structure to loop through: https://marco.ccr.buffalo.edu/images?page=0&amp;score=Clear https://marco.ccr.buffalo.edu/images?page=1&amp;score=Clear https://marco.ccr.buffalo.edu/images?page=2&amp;score=Clear ... I want to loop through each of these pages and download the 21 images (JPEG or PNG). I've seen several Beautiful Soap examples, but Im still struggling to get something that will download multiple images and loop through the URLs. I think I can use urllib to loop through each URL like this, but Im not sure where the image saving comes in. Any help would be appreciated and thanks in advance! for i in range(0,10): urllib.urlretrieve('https://marco.ccr.buffalo.edu/images?page=' + str(i) + '&amp;score=Clear') I was trying to follow this post but I was unsuccessful: How to extract and download all images from a website using beautifulSoup?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51599859
linked to: http://stackoverflow.com/q/13137817
tagged with: web-scraping
type: Question
has title: Loop through webpages and download all images
tagged with: image
score: 0
answer count: 1

http://stackoverflow.com/q/51595319
score: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: netcdf
type: Question
tagged with: netcdf4
has title: NetCDF4 Python not recognizing attributes
has comment: http://stackoverflow.com/comment/90180997
has comment: http://stackoverflow.com/comment/90204519
has body: I am running the following code: file = Dataset('file.nc') print(file.ncattrs()) for name in file.ncattrs(): print(name) The second line returns [], and the for loops returns nothing, suggesting there are no attributes in the file. However, I opened the file and found 41 global attributes. Why is this not detecting the attributes? EDIT: Here is the file I'm using.
has comment: http://stackoverflow.com/comment/90238407

http://stackoverflow.com/comment/90043282
has text: @intentionallyleftblank it is valid
comment on: http://stackoverflow.com/q/51537879
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/64082553
answers question: http://stackoverflow.com/q/51564710
score: 1
has body: Here's the formal dialect for Netezza has been released. It can be used as documented here - https://github.com/IBM/nzalchemy#prerequisites Example from sqlalchemy import create_engine from urllib import parse_quote_plus # assumes NZ_HOST, NZ_USER, NZ_PASSWORD are set import os params = parse_quote_plus(f"DRIVER=NetezzaSQL;SERVER={os['NZ_HOST']};" f"DATABASE={os['NZ_DATABASE']};USER={os['NZ_USER'};" f"PASSWORD={os['NZ_PASSWORD']}") engine = create_engine(f"netezza+pyodbc:///?odbc_connect={params}", echo=True)
upvote count: 1
downvote count: 0
type: Answer

arima
tags question: http://stackoverflow.com/q/51567645
tag name: arima
type: Tag
tags question: http://stackoverflow.com/q/51622483

http://stackoverflow.com/comment/90097899
type: QuestionComment
has text: @cricket_007 In C or in Fortran. Both can be called from Fortran easily.
score: 1
comment on: http://stackoverflow.com/q/51565122
type: Comment

http://stackoverflow.com/comment/90148250
type: Comment
type: QuestionComment
has text: Yes I can. CTE are not available in MySQL 5.5. Also, its easier to do it with a programming language
comment on: http://stackoverflow.com/q/51590677
score: 0

http://stackoverflow.com/q/51616315
type: AnsweredQuestion
has title: pandas set index using split of column as new index
score: 1
has answer: http://stackoverflow.com/a/51616598
type: Question
has body: I have a dataframe that I get from a third party: r = get_finance_rate([eq_opt_px.index[0],vol_opt_px.index[0]], expiry) r: ticker field value 0 SPX US 08/17/2018 C2830.0 Index OPT_FINANCE_RT 2.004648 1 VXX US 08/17/2018 C27.0 Index OPT_FINANCE_RT 2.03248 Since the output is returned in a format that does not fits my needs I would like to reset the index. The obvious solution for what I'm trying to do is r['aux id'] = [x.split()[0] for x in r['ticker']] r = r.set_index('aux id') Result: ticker field value SPX SPX US 08/17/2018 C2830.0 Index OPT_FINANCE_RT 2.004648 VXX VXX US 08/17/2018 C27.0 Index OPT_FINANCE_RT 2.03248 However I would like to do something like r = get_finance_rate([eq_opt_px.index[0],vol_opt_px.index[0]], expiry).set_index('ticker'.split(' ')[0]) The previous instruction does not perform the split ticker field value SPX US 08/17/2018 C2830.0 Index OPT_FINANCE_RT 2.004648 VXX US 08/17/2018 C27.0 Index OPT_FINANCE_RT 2.03248 Is there such a way to accomplish what I want without having to create the temporary column?
answer count: 3
tagged with: pandas
upvote count: 1
downvote count: 0
possible better answer: http://stackoverflow.com/a/51616598
has comment: http://stackoverflow.com/comment/90198532
has answer: http://stackoverflow.com/a/51616596
favorite count: 0
accepted answer: http://stackoverflow.com/a/51616596
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51616664
tagged with: python
has comment: http://stackoverflow.com/comment/90198623

http://stackoverflow.com/comment/90254682
type: AnswerComment
has text: I found the answer. Thank you all.
type: Comment
comment on: http://stackoverflow.com/a/51512562
score: 0

http://stackoverflow.com/q/51604689
has comment: http://stackoverflow.com/comment/90175651
has answer: http://stackoverflow.com/a/51604927
tagged with: python
accepted answer: http://stackoverflow.com/a/51605244
favorite count: 0
has comment: http://stackoverflow.com/comment/90176277
has answer: http://stackoverflow.com/a/51605244
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90176139
has comment: http://stackoverflow.com/comment/90175725
downvote count: 0
tagged with: amazon-s3
score: 1
has title: Read zip files from amazon s3 using boto3 and python
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90176591
possible better answer: http://stackoverflow.com/a/51604927
tagged with: boto3
tagged with: amazon-web-services
linked to: http://stackoverflow.com/q/51351000
has body: I have an s3 bucket which has a large no of zip files having size in GBs. I need to calculate all zip files data length. I go through boto3 but didn't get it. I am not sure if it can directly read zip file or not but I have a process- Connect with the bucket. Read zip files from the bucket folder (Let's say folder is Mydata). Extract zip files to another folder named Extracteddata. Read Extracteddata folder and do action on files. Note: Nothing shouldn't download on local storage. All process goes on S3 to S3. Any suggestions are appreciated.
upvote count: 1
has comment: http://stackoverflow.com/comment/91852627

http://stackoverflow.com/a/51637779
has body: I tried to use requests module to get a response, and it worked. If this isn't working for you, the website might have some GeoIP blocking or other mechanism in order: import requests from bs4 import BeautifulSoup r = requests.get('http://www.pulsant.com') soup = BeautifulSoup(r.text, 'lxml') print(soup.title.text) print(soup.h1.text) Prints: Hybrid IT &amp; Managed Cloud Hosting Solutions | Pulsant Experts in compliant business cloud platforms
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51631812
type: Answer
answers question: http://stackoverflow.com/q/51631812
score: 1
upvote count: 1

http://stackoverflow.com/comment/89940216
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51485453
type: Comment
has text: but the downside of it is that every time the program starts the screen is bombarded with frames

http://stackoverflow.com/q/51483008
answer count: 1
downvote count: 0
tagged with: scrapy-splash
has answer: http://stackoverflow.com/a/51483397
favorite count: 0
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: screen-scraping
has body: I am curious to see if any splash can get the dynamic job content from this page - https://nreca.csod.com/ux/ats/careersite/4/home?c=nreca#/requisition/182 in order for splash to receive the URL fragment you have to use a SplashRequest. In order for it to handle the JS cookies I have had to use a lua script. below is my environment, script, and scrapy code. the site seems to render in 3 'steps': basically empty html with a script tag above script runs and generates the site header/footer and another script is retrieved script from #2 runs and in conjunction with a JS set cookie retrieves dynamic content (the job I want to scrape) if you do a simple GET on the URL (i.e. in postman) you will see only step 1 content. with splash I am only getting the result of step 2 (header/footer). I do see the JS cookies in response.cookiejar I cannot get the dynamic job content (step 3) to render. Environment: scrapy 1.3.3 scrapy-splash 0.72 settings script = """ function main(splash) splash:init_cookies(splash.args.cookies) assert(splash:go{ splash.args.url, headers=splash.args.headers, http_method=splash.args.http_method, body=splash.args.body, }) assert(splash:wait(15)) local entries = splash:history() local last_response = entries[#entries].response return { url = splash:url(), headers = last_response.headers, http_status = last_response.status, cookies = splash:get_cookies(), html = splash:html(), } end """ return SplashRequest('https://nreca.csod.com/ux/ats/careersite/4/home?c=nreca#/requisition/182', self.parse_detail, endpoint='execute', cache_args=['lua_source'], args={ 'lua_source': script, 'wait': 10, 'headers': {'User-Agent': 'Mozilla/5.0'} }, )
tagged with: scrapy
type: Question
tagged with: reactjs
has title: Scrapy-splash not rendering dynamic content from a certain react-driven site
accepted answer: http://stackoverflow.com/a/51483397

http://stackoverflow.com/comment/89976721
comment on: http://stackoverflow.com/q/51503997
has text: Your code is a bit difficult to parse without seeing the accompanying XML, but `if child.get('portid') not in temp` -- don't you want to check `temp[ip][name]`?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/90244365
has text: The answers to the duplicate questions make it very clear: `eval` is evil. They recommend **not** to use it, and give many better, safer alternatives.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51630921
type: AnswerComment

http://stackoverflow.com/a/51538620
type: Answer
accepted answer of: http://stackoverflow.com/q/51538588
upvote count: 3
has body: use the forloop.counter template var: {% for resp in results %} {{ resp }} {{ resp.Question_id.Statement }} {% endfor %}
score: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51538588

http://stackoverflow.com/comment/89975238
comment on: http://stackoverflow.com/a/51483874
type: AnswerComment
score: 0
type: Comment
has text: Line 2 is sorting the table by the `device_type` lexicographically in descending order, thus `Switch` will come before `Router`. That's rather crude, you could define a custom ordering if you had other values to consider.

http://stackoverflow.com/comment/89976113
type: QuestionComment
score: 2
has text: You can't have a function time itself like this because the way you're timing it runs the function, which times the function, which runs the function...
comment on: http://stackoverflow.com/q/51503672
type: Comment

http://stackoverflow.com/a/51529512
answers question: http://stackoverflow.com/q/51529502
has body: readlines strips the newline character from the lines you are reading, but print prints its own newline. If you don't want the newline, you should use print(line, end=''). In addition: line.replace("\n", "") is not effective, first because readlines won't produce strings with newlines in them, and second because replace returns a new string which you're not storing anywhere. print(fileLines) will print the "repr" (representation) of fileLines; this will include the array syntax, string delimiters, and so on and look like ['line 1', 'line 2', ...].
score: 0
type: Answer

http://stackoverflow.com/q/51633822
tagged with: python
has comment: http://stackoverflow.com/comment/111062594
score: 3
upvote count: 3
has body: I'm having trouble with the count() method of pyspark, which is way too slow for my program. I found out about the countApprox(timeout,confidence) one but it doesn't speed up the process. What i found doing a bit of research is that I should maybe use rdd.countApprox.initialValue but it doesn't seem to work, as in pyspark the result of countApprox is an int and not a PartialResult object (I guess it is different in scala or java) Does anyone know how to make countApprox work in pyspark ? My test code to compare : a = sc.parallelize(range(1000000),10) import time t = time.time() print("there are ",a.count()," rows") print(time.time()-t) gives : there are 1000000 rows 3.4864296913146973 but b = sc.parallelize(range(1000000),10) import time t = time.time() print("there are ",b.countApprox(10,0.1)," rows") print(time.time()-t) gives out : there are 1000000 rows 3.338970422744751 Which is pretty much the same time of execution...
has title: pyspark countApprox() does not seem to be different from count()
type: Question
has answer: http://stackoverflow.com/a/51634129
tagged with: pyspark
answer count: 1
downvote count: 0
tagged with: apache-spark
linked to: http://stackoverflow.com/q/51238557
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51564228
type: Question
tagged with: numpy
has title: How to fit a 2d curve to a matrix
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/45537055
has answer: http://stackoverflow.com/a/51565548
has body: I have squares matrices of real values and I would like to fit low degree polynomials or other simple functions to them. Here is a toy example matrix: M = [[ 0.63, 2.58, 8.7 , 18.17, 32.97], [ 3.97, 4.42, 11.9 , 19.88, 34.74], [ 7.75, 10.68, 14.11, 24.11, 34.99], [15.75, 10.86, 10.72, 24.99, 42.02], [16.57, 7.48, 16.91, 42.33, 48.43]] I would like to fit a function so that when I give it (i,j) it computes a values that is approximately M[i,j]. Is there some way in scipy or numpy (or any other python library) to do this?
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: curve-fitting
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90096302
tagged with: scipy

http://stackoverflow.com/q/51562341
has answer: http://stackoverflow.com/a/51566246
has title: ValueError: convolve2d inputs must be both 2D arrays
has comment: http://stackoverflow.com/comment/90096728
has comment: http://stackoverflow.com/comment/90095159
has comment: http://stackoverflow.com/comment/90098208
has comment: http://stackoverflow.com/comment/90095389
has comment: http://stackoverflow.com/comment/90091742
has comment: http://stackoverflow.com/comment/90096344
has comment: http://stackoverflow.com/comment/90099054
has body: I'm working on a program that takes in a video, splits the video into a sequence of images, applies a cleaning filter to the images (denoise/deblur/etc.), then puts it back together into a video. I wanted to use Scikit Image's "Unsupervised_wiener" restoration on the images to de-blur them, but I haven't been able to get it and I don't understand the documentation. This is what I have, copied from the documentation: frame = color.rgb2gray frame = convolve2d(frame, psf, 'same') frame += 0.1 * frame.std() * np.random.standard_normal(frame.shape) fixed = skimage.restoration.unsupervised_wiener(frame, psf) Where "frame" is a frame from the input, which I captured with OpenCV2: ret, frame = vid.read() But I get the following error: Traceback (most recent call last): line 1025, in convolve2d ValueError: convolve2d inputs must both be 2D arrays How do I convert the input frames into a 2D array so that Scikit Image can process them? Any help would be great, or if there's a better method I can use, I'm open to that as well. Thanks! Edit: pst shape is: (5,5), frame shape is: (1080, 1920, 3)
favorite count: 0
has comment: http://stackoverflow.com/comment/90096813
accepted answer: http://stackoverflow.com/a/51566246
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90094608
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90097092
score: 1
tagged with: scikit-image
has comment: http://stackoverflow.com/comment/90096934
has comment: http://stackoverflow.com/comment/90097426
type: Question
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/89983581
comment on: http://stackoverflow.com/q/51507219
has text: I think @jsbueno is right about your error; in the future, you should include all of your code (or enough to fully reproduce the problem), including the code that calls this function, where the parameters to this function come from, and where you print the result.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/89951740
has text: i have made all the changes you said. but just url changes and the filter isn't working still
score: 0
comment on: http://stackoverflow.com/a/51491255
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51570581
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51570498
answers question: http://stackoverflow.com/q/51570498
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90108456
has body: Code points U+D800 through U+DFFF are contained in the various "Surrogates" Unicode blocks. They result when UTF-16 text containing text in the Supplementary Multilingual Planes is (mis)decoded as UCS-2; they should never result in normal operation, and should not be treated as characters.
has comment: http://stackoverflow.com/comment/90108276
type: AcceptedAnswer

http://stackoverflow.com/q/51487174
type: Question
tagged with: python
has title: Maintaining accuracy of ratios in numpy
tagged with: numbers
upvote count: 1
answer count: 1
tagged with: numpy
has answer: http://stackoverflow.com/a/51487294
tagged with: math
has comment: http://stackoverflow.com/comment/89943581
type: AnsweredQuestion
has body: I am using numpy to analyze graphs. One type of analysis I am doing is traversing, while enumerating: "how often is node K in a path with node J, up to this point". In this analysis, many of my values are ratios, or percentages, or however you want to think of it. Since graphs often branch, they are often exponential when it comes to combinations or permutations. And so, some of the time, my ratios become very small. And, numpy loses accuracy. And, eventually, numpy says that the ratio is zero even though it should still be greater than zero. To elaborate a bit more, I use rows of the matrix to represent depth of my search, and I use columns to represent nodes. The value of the [row,column] is the ratio of said node, at said depth, to whatever other node I am comparing it to. And so it's the case, that depending upon the graph, that ratio may be cut in half at every next level. From 1, to .5, to .25, to ..... 1.369^(-554) and suddenly it's zero next iteration. Not to mention, when it gets small enough I lose accuracy in all my other calculations as well. If I want extreme accuracy even on large graphs, what options do I have? I suppose I could enumerate in the opposite direction, getting total counts and doing division to recalculate ratios when necessary (it is necessary at time in my program). But if I do this, I still expect I would lose a ton of accuracy when I divide one huge number by another huge number, yes?
tagged with: types
downvote count: 0
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51487294

ml-agent
tags question: http://stackoverflow.com/q/51528295
tag name: ml-agent
type: Tag

http://stackoverflow.com/q/51620322
score: 0
tagged with: nas
has body: Ultimately, I want to play movies from my Synology NAS on a Linux box connected to my TV. The Linux box is an Intel NUC running Ubuntu 16.04 LTS. It has a 128 GB SSD and a 32 GB USB 3.0 drive (permanently attached), also there is 8 GB of memory. For reference the average movie file size is 5 GB. I wrote a GUI in Python to handle the the movie title selection, NAS file retrieval and launching the movie in VLC player. My question is in regards to temporary file storage location. The way I see it I have (2) obvious options: 1) I can use the tempfile module to store the movie until it is finished playing, or 2) I can write the movie to the USB drive. My concern is I fear if i use the tempfile module I will slowly degrade my SSD until it fails. Assuming two movies will be watched on this machine per day means that 10 GB of data will be written to then erased from the SSD daily. If I use the USB drive I get the same wear and tear - the difference being the USB drive is way cheaper and easier to replace. Is this a credible concern or am I being overly cautious? If it is possible I would prefer to save the movie to memory and play it from there, but I don't know how or if that is even possible. The issue being some of the movies are > 5 GB and the movie wouldn't fit in memory without some kind of circular buffer. Any suggestions on which route is preferred?
answer count: 0
has title: Python write to TempFile or to USB drive
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90206402
tagged with: linux
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90206815

http://stackoverflow.com/q/51484712
tagged with: python
possible better answer: http://stackoverflow.com/a/51484818
score: 0
has body: I have a seemingly simple recursive function here that loops through a dictionary of dictionaries. I would like to print my value v as I am already doing and I would like to return the first key that is associated with this key:value pair. In this case, the code outputs v = 'hi' and None. I'm not sure why it keeps returning None. I set the k variable to an empty string outside of the function. K in this case should be 'six'. Also, I would like the code to somehow return 'five' since it is the first key but I am not sure if that is possible. Can anyone assist? I apologize in advance for any confusion with the keys either. Here, the code should be returning k = 'six'. I'm not sure how I would go about getting the key of {'six': 'hi'} returned. my_dict = {'one': {'two': 'hello'}, 'three': {'four': 'hey'}, 'five': {'six': 'hi'}} k = '' numero = 'six' def find_location(d): for k, v in d.iteritems(): if isinstance(v, dict): find_location(v) else: if numero == k: print 'this is k: {}'.format(k) print v return k def print_return(func): print func x = find_location(my_dict) print_return(x)
answer count: 2
has title: return value from function is None and can't return first key
accepted answer: http://stackoverflow.com/a/51485053
tagged with: recursion
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51485053
type: Question
has answer: http://stackoverflow.com/a/51484818

http://stackoverflow.com/comment/90226476
type: Comment
comment on: http://stackoverflow.com/a/51627228
has text: yep, your understanding is correct. and when you get response, transform it into human readable format and dump it into `fulfillmentText`. let me know if you have further questions.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90396122
has text: @WiktorStribiżew, it works!!! Thanks a lot. With your solution, I found out that the parenthesizes in the pattern were recognized as grouping. I understand now. Thanks again.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51518172
type: Comment

http://stackoverflow.com/a/53214092
answers question: http://stackoverflow.com/q/51565320
type: Answer
score: 6
upvote count: 6
has body: The issue is documented here https://github.com/ipython/ipython/issues/10794 You/Something has probably set your interactive shell to from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" One solution is the change all to last_expr The consequence of this is that a cell will display the output of the last expression rather than every expression. You could still of course print something and that would work normally. Another solution is to add ; to the last expression for example, you could add pass;at the end of the cells, which would suppress output A third option is as @sacul suggested, to assign outputs to variables by using some dummy variable. Make sure you're not using that variable elsewhere
downvote count: 0

http://stackoverflow.com/comment/90123616
type: Comment
type: QuestionComment
has text: Apologies ignore my last comment, I was thinking about `input_shape`. I do still have the feeling that `batch_input_shape` is the cause of the error; having read some more I think the first value should be equal to the batch size specified in `model.fit`.
score: 1
comment on: http://stackoverflow.com/q/51578810

http://stackoverflow.com/comment/89991405
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51509321
has text: I tried to use original picture: image to minus the DoG, the result might a little better than the previous one, but still could not identify the full tails.
type: Comment

http://stackoverflow.com/q/51487645
downvote count: 0
has answer: http://stackoverflow.com/a/51488346
has comment: http://stackoverflow.com/comment/89944618
favorite count: 0
has answer: http://stackoverflow.com/a/51489130
has title: Get path of script containing the calling function
has comment: http://stackoverflow.com/comment/89944453
score: 6
tagged with: python
type: AnsweredQuestion
has body: Say I have two files, foo.py and bar.py. It does not matter where they are located, only that foo.py somehow manages to import bar.py and call a function func() defined in the latter. How would I get the absolute path of foo.py from bar.func()?
possible better answer: http://stackoverflow.com/a/51487827
type: Question
upvote count: 6
accepted answer: http://stackoverflow.com/a/51488346
has answer: http://stackoverflow.com/a/51487827
answer count: 3
has comment: http://stackoverflow.com/comment/89944455

http://stackoverflow.com/comment/90164555
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51599289
has text: Sure thing. @Rakesh

http://stackoverflow.com/comment/90909216
has text: Thank you @Chungzuwalla ^^ I really didn't see that part in the openCV documentation. They just mentioned in one place. Now I can get the good results but I have other problems like changing perspective etc. Thank you, great day!
comment on: http://stackoverflow.com/a/51872097
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51629691
answer count: 3
favorite count: 0
has title: Comparing nested dictionaries
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51630031
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51630119
type: Question
has answer: http://stackoverflow.com/a/51629928
accepted answer: http://stackoverflow.com/a/51629928
has body: I would like to compare nested dictionaries as following: d = {'siteA': {'00000000': 3, '11111111': 4, '22222222': 5}, 'siteB': {'00000000': 1, '11111111': 2, '22222222': 5}} e = {'siteA': {'00000000': 5}} f = {'siteB': {'33333333': 10}} g = {'siteC': {'00000000': 8}} d is the total full dictionaries that will be use to compare with e, f and g. If e happens to found in siteA-00000000, then I would like both value (in this case 3 and 5) add up to become 8. If f is not found (in this case, it's true), I would like to append the dictionary into the d['siteB']. If g is not found, would like to append into d. Thanks!
tagged with: counter
possible better answer: http://stackoverflow.com/a/51630031
upvote count: 2

heatmap
tags question: http://stackoverflow.com/q/51568083
tags question: http://stackoverflow.com/q/51627286
type: Tag
tags question: http://stackoverflow.com/q/51543359
tag name: heatmap
tags question: http://stackoverflow.com/q/51601272

http://stackoverflow.com/comment/89955829
score: 0
type: QuestionComment
type: Comment
has text: @ScottBoston thanks for the tip, but that didn't work unfortunately. The error message is: pandas.errors.UnsortedIndexError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (3), lexsort depth (1)' My df is actually one I just read from a csv, so not sure if I can post an example?
comment on: http://stackoverflow.com/q/51483096

http://stackoverflow.com/comment/89973072
score: 0
type: QuestionComment
type: Comment
has text: @jpp pandas.core.frame.DataFrame
comment on: http://stackoverflow.com/q/51502263

http://stackoverflow.com/q/51530835
accepted answer: http://stackoverflow.com/a/51530848
tagged with: django
has title: django/python 3.5 imports/separating views.py into separate files
type: Question
has body: I've looked at just about everything I can here. I'm using python 3.5 and i've seen stuff about how they've changed the way imports work. My django project structure is like this: project --app --views/ --__init__.py --myFile.py --__init__.py --models.py --admin.py --urls.py --etc.... My urls.py is such: from django.contrib import admin from django.urls import path from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^api$', views.function_from_myFile_that_is_not_being_found), otherurls()... ] The error I'm getting is AttributeError: module 'app.views' has no attribute 'function_from_myFile_that_is_not_being_found' I'm really lost as to why this is happening. I've tried putting imports in my __init__.py files and that hasn't worked either. Not sure what else I'm missing. Thanks in advance.
tagged with: python-3.5
answer count: 1
has answer: http://stackoverflow.com/a/51530848
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/90091773
has text: There are answers in that question that don't require any imports.
score: 0
comment on: http://stackoverflow.com/q/51562280
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51488962
has comment: http://stackoverflow.com/comment/89976427
answers question: http://stackoverflow.com/q/51488737
score: 0
has comment: http://stackoverflow.com/comment/91014916
has comment: http://stackoverflow.com/comment/89946901
has body: deepcopy of an object should return an object of the same type. so an ordereddict returned as a copy should remain ordered? EDIT - This is not completely correct answer. Please look at Greg's comment below.
type: Answer
has comment: http://stackoverflow.com/comment/91575727
has comment: http://stackoverflow.com/comment/91581594
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/51566194
answer count: 1
has title: Precision and recall eval_metrics for labels and predictions of different number of elements in tensorflow
tagged with: python
has body: I am having a problem with registering precision and recall as eval_metrics in Tensorflow. My labels and predictions don't have the same number of elements, so I can't use the already built-in functions. I have the function to calculate the precision and recall, but I can't seem to get precision_update_op and recall_update_op. Any ideas how I can get that from having labels, predictions and the previously mentioned functions for calculation precision and recall? Thanks
has answer: http://stackoverflow.com/a/51583860
score: 0
type: UnansweredQuestion
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/90075871
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51542315
type: AnswerComment
has text: when I'm doing this: df['Active_Time_Spent'] = df['Active_Time_Spent'].astype(float) its stored as number in excel however when doing this df['Active_Time_Spent'] = df['Active_Time_Spent'].astype(str) stored as text, which is showing error mark on excel with warning number stored as text.

http://stackoverflow.com/comment/94942739
has text: This repo does similar to what you are trying to do. Have a look. https://github.com/lohithpro/intruder_detector_capture_alarm
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51615663
type: Comment

http://stackoverflow.com/comment/90181012
score: 3
type: Comment
type: QuestionComment
has text: @AnkitJaiswal That is _not_, and never was, an appropriate reason for closure. At best, it's a reason to downvote, which you could have done instead.
comment on: http://stackoverflow.com/q/51607607

http://stackoverflow.com/q/51574952
has body: For the below dataframe df Filename Language Repo/Repo_3/.travis.yml YAML 20 Repo/Repo_3/backup_automater_services.py Python 18 Repo/Repo_3/batch_file_rename.py Python 33 Repo/Repo_3/cbd_pennies. C 26 Repo/Repo_3/cbd_rand. C 19 Repo/Repo_3/cbd_rand_dist. C 20 Repo/Repo_3/chaos.py Python 8 Repo/Repo_3/chapter02/item01/Provider.jav Java 4 Repo/Repo_3/chapter02/item01/Service.jav Java 3 Repo/Repo_3/chapter02/item01/Services.jav Java 25 Trying to find out a way to find sum for duplicate in column of language. Sum of All C language or Python Filename Language Sum of All Repo/Repo_3 YAML 20 Repo/Repo_3 Python 118 Repo/Repo_3 C 120 Repo/Repo_3 Java 125 Trying to use groupby but no luck df.groupby(['Filename', 'Language'])['Code Lines'].sum()
possible better answer: http://stackoverflow.com/a/51575067
has answer: http://stackoverflow.com/a/51575067
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51575068
accepted answer: http://stackoverflow.com/a/51575068
tagged with: pandas
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has title: Pandas add sum based on dupliacte column name
type: Question

http://stackoverflow.com/a/51530265
score: 1
has body: try this. import pandas as pd import numpy as np df1 = pd.DataFrame({'CID':[1,25,100], 'Notional': [1000, 2500, 5500]}) df2 = pd.DataFrame({'CID':[25], 'Notional2': [0]}) df=pd.merge(df1,df2,how='left') df['Notional'] = np.where(df['Notional2'].isna(),df['Notional'],df['Notional2']) df.drop('Notional2',axis=1)
upvote count: 1
answers question: http://stackoverflow.com/q/51530054
type: Answer
downvote count: 0

http://stackoverflow.com/comment/90102611
type: QuestionComment
has text: Why does it *have* to use a list comp?
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51568156

http://stackoverflow.com/a/51563770
type: Answer
has comment: http://stackoverflow.com/comment/90106776
answers question: http://stackoverflow.com/q/51563548
score: 1
has body: ... but I couldn't find a solution This is because there isn't a simple one. A simple nested list cannot represent a complete XML document that uses more than one "axis" (for a loose definition of "axis"). In the first example you use only the parent/child axis, but in the second you use the "attribute" axis as well, meaning your data structure has three dimensions. This cannot be represented directly as nested lists without some flattening, and including some metadata in the output structure: <prod:insert> my_key my_signature my_code my_title <spec name="X" value="15" /> <spec name="Y" value="10.0T" /> </prod:insert> Becomes [my_key, my_signature, [my_code, my_title, [ ["X", "15"], ["Y", "10.0T"] ] ] I assume that can contain some unknown number of <spec> elements. This of course presumes that the XML strictly follows a schema ensuring that elements always appear in the same position. The best solution is to use a combination of nested dicts and lists { key:my_key, signature:my_signature, [ // variable { code: my_code, title:my_title, [ // specs { name:X, value:15} { name:Y, value:10.0T} ] } ] } There's more than one way to structure this. I elided the names variable and specs as they didn't add any semantics, but you could make them named objects if you wanted to.
upvote count: 1
has comment: http://stackoverflow.com/comment/90097669
has comment: http://stackoverflow.com/comment/90098031
downvote count: 0
has comment: http://stackoverflow.com/comment/90101714

http://stackoverflow.com/q/51555686
has answer: http://stackoverflow.com/a/51555956
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90078353
score: 2
type: Question
has title: python list variables in works by pattern (Python equivalent of R ls(pattern="namepattern")
upvote count: 2
has answer: http://stackoverflow.com/a/51556191
answer count: 2
has comment: http://stackoverflow.com/comment/90078426
downvote count: 0
favorite count: 0
has body: What is the python command to list all variables existing in the current worskpace that match a certain pattern? For example, list all existing variables/objects in the workspace that start with "ABC"

instantiation
type: Tag
tags question: http://stackoverflow.com/q/51506632
tags question: http://stackoverflow.com/q/51637374
tag name: instantiation

http://stackoverflow.com/a/51601905
type: Answer
has comment: http://stackoverflow.com/comment/95630560
upvote count: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/51601670
has comment: http://stackoverflow.com/comment/90170291
has body: No need for external libraries, use the built-in str function str.decode() print temp.decode('unicode-escape') or tell python that your string contains unicode characters by making it a string literal prepending it with u'' temp = u'That looks great \ud83d\udc4c Good Job!' A prefix of "u" or "U" makes the string a Unicode string http://docs.python.org/2.5/ref/strings.html
score: 0
has comment: http://stackoverflow.com/comment/90170431
answers question: http://stackoverflow.com/q/51601670
type: AcceptedAnswer

http://stackoverflow.com/comment/89983713
comment on: http://stackoverflow.com/q/51506354
type: Comment
score: 1
type: QuestionComment
has text: What I mean is that when not in Debugging mode, you can easily plot whatever you like at any point in the script, just as you'd do with print statements.

http://stackoverflow.com/comment/90002498
score: 0
has text: Yes, it is TKInter. I have tried passing the value 'pn' to .set() but now I get a different error: Traceback (most recent call last): File "G:\ERIC North East\IT\ArcMap Python stuff\", line 1582, in <module> app = Application(master=root) File "G:\ERIC North East\IT\ArcMap Python stuff\ 8.pyw", line 784, in __init__ self.createWidgets() File "G:\ERIC North East\IT\ArcMap Python stuff\Standalone mapping script\run_map_script v8.pyw", line 383, in createWidgets self.btnPickFile.gid(row=62, column=4, sticky=E, padx=5) AttributeError: Button instance has no attribute 'gid'
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51516562

http://stackoverflow.com/comment/89959005
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51495274
score: 1
has text: @Marcus.Aurelianus what does the diagonal part have to do with the fact that OP has probably created the list in the same fashion than in the linked question and is therefore observing the same behaviour: `a[0][0]` will set all first elements in every row, `a[1][1]` will set all second elements in every row and so on up until you have modified every element in the array. When defining the matrix like `a = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]`, then OP's code works just fine

http://stackoverflow.com/a/51595776
type: Answer
answers question: http://stackoverflow.com/q/51594182
score: 0
has body: I put command in the new environment that I made: pip install --upgrade pip==10.0.1 and I installed the older version of pip that way I successfully installed PyInstaller pack!! for everyone know :)

http://stackoverflow.com/a/51527229
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51527203
has body: Simple list comprehension here - a = [("roll", i) for i in a] OP [('roll', 1), ('roll', 2), ('roll', 3), ('roll', 4)] More about list comprehension here
score: 3
accepted answer of: http://stackoverflow.com/q/51527203
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/q/51559529
tagged with: python
has title: Dynamically replace NaN values with the average of previous and next non-missing values
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/78624074
score: 6
has body: I have a dataframe df with NaN values and I want to dynamically replace them with the average values of previous and next non-missing values. In [27]: df Out[27]: A B C 0 -0.166919 0.979728 -0.632955 1 -0.297953 -0.912674 -1.365463 2 -0.120211 -0.540679 -0.680481 3 NaN -2.027325 1.533582 4 NaN NaN 0.461821 5 -0.788073 NaN NaN 6 -0.916080 -0.612343 NaN 7 -0.887858 1.033826 NaN 8 1.948430 1.025011 -2.982224 9 0.019698 -0.795876 -0.046431 For example, A[3] is NaN so its value should be (-0.120211-0.788073)/2 = -0.454142. A[4] then should be (-0.454142-0.788073)/2 = -0.621108. Therefore, the result dataframe should look like: In [27]: df Out[27]: A B C 0 -0.166919 0.979728 -0.632955 1 -0.297953 -0.912674 -1.365463 2 -0.120211 -0.540679 -0.680481 3 -0.454142 -2.027325 1.533582 4 -0.621108 -1.319834 0.461821 5 -0.788073 -0.966089 -1.260202 6 -0.916080 -0.612343 -2.121213 7 -0.887858 1.033826 -2.551718 8 1.948430 1.025011 -2.982224 9 0.019698 -0.795876 -0.046431 Is this a good way to deal with the missing values? I can't simply replace them by the average values of each column because my data is time-series and tends to increase over time. (The initial value may be $0 and final value might be $100000, so the average is $50000 which can be much bigger/smaller than the NaN values).
type: Question
upvote count: 6
possible better answer: http://stackoverflow.com/a/58646182
has answer: http://stackoverflow.com/a/51559892
accepted answer: http://stackoverflow.com/a/51559892
has answer: http://stackoverflow.com/a/58646182
has answer: http://stackoverflow.com/a/78624185
tagged with: pandas
has answer: http://stackoverflow.com/a/73010012
has comment: http://stackoverflow.com/comment/90086145
favorite count: 0
linked to: http://stackoverflow.com/q/18689823
answer count: 5

http://stackoverflow.com/comment/90120199
comment on: http://stackoverflow.com/q/51577415
score: 3
type: Comment
has text: what is your question?
type: QuestionComment

http://stackoverflow.com/comment/90149729
has text: Just a heads-up: If the files are very large, this may fail; it reads the whole file into memory first.
type: AnswerComment
comment on: http://stackoverflow.com/a/51571720
type: Comment
score: 1

http://stackoverflow.com/comment/90043331
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51537879
has text: Nope. If this is Numpy, the question should mention it.

http://stackoverflow.com/q/51632848
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51634270
possible better answer: http://stackoverflow.com/a/51634975
accepted answer: http://stackoverflow.com/a/51634270
has answer: http://stackoverflow.com/a/51634975
has title: Date manipulation periods
has comment: http://stackoverflow.com/comment/90232723
tagged with: python
tagged with: excel
type: AnsweredQuestion
score: 0
tagged with: etl
has comment: http://stackoverflow.com/comment/90232185
type: Question
tagged with: analytics
has body: I have this problem for work. So I have this dataset as follows: Client Date Transaction Num A 7/20/2017 1 A 7/26/2017 1 A 7/31/2017 1 A 8/23/2017 2 A 8/31/2017 2 A 9/11/2017 2 A 9/19/2017 3 A 9/27/2017 3 A 10/4/2017 3 B 6/1/2017 1 B 6/29/2017 1 B 7/6/2017 2 B 8/27/2017 3 B 9/28/2017 4 B 10/16/2017 4 B 11/30/2017 5 What I need to do is generate the transaction num based on the date for each client as follows: For the starting date (for client A, it is 7/20/17), I need to assign a starting transaction Number = 1. Then for every 30 days from this starting date, I need to increment the transaction number by one. So 30 days from 7/20/17 is 8/19/17, so all dates falling within this range get transaction num =1, then if they exceed, the transaction number increments by one for every 30 days from starting date. This pattern goes on, so 30 days from 8/19/17 is 9/18/17, so dates within this range gets transaction num =2, and after 9/18/17, gets transaction num = 3 and so on. I need to do this for a large excel. Any help would be appreciated. If it easier in python, please let me know as well. Thanks, Sammy
answer count: 2

http://stackoverflow.com/comment/90144093
type: QuestionComment
comment on: http://stackoverflow.com/q/51588293
score: 0
has text: @coldspeed, thank you for the comment. It was to provide more sample for the testing. I will pay attention to it next time.
type: Comment

http://stackoverflow.com/comment/90094272
comment on: http://stackoverflow.com/q/51559363
score: 0
has text: Deleting an element is easy with an XML-aware command line tool such as xmlstarlet. Commenting out is harder. See https://stackoverflow.com/questions/48671491/how-to-comment-out-a-string-in-xml-file-in-shell.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51486724
has comment: http://stackoverflow.com/comment/89942651
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/20625582
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89954897
has body: Maybe I'm slowly losing my mind but I've gotten iterrows() to work in the past but now I'm trying to it to edit row values using it and some rows do get changed while other don't.When iterrows works When iterrows doesn't work The following worked (produced new columns called '1MM','3MM', and '5MM' and labeled correctly): for index, row in merged.iterrows(): merged.at[index, '1MM'] = 'Yes' if row['Opportunity'] &gt;=1 else 'No' merged.at[index, '3MM'] = 'Yes' if row['Opportunity'] &gt;=3 else 'No' merged.at[index, '5MM'] = 'Yes' if row['Opportunity'] &gt;=5 else 'No' But this didn't work (some Client Firm names didn't get changed): for i, row in ff.iterrows(): ff.at[i,'new'] = 'Raymond James' if re.search('Raymond James',row["Client Firm"]) else row['Client Firm'] ff.at[i,'new'] = 'Cetera' if re.search('Cetera',row['Client Firm']) else row['Client Firm'] ff.at[i,'new'] = 'LPL' if re.search('LPL',row['Client Firm']) else row['Client Firm'] ff.at[i,'new'] = 'Wells Fargo' if re.search('Wells Fargo',row['Client Firm']) else row['Client Firm'] The second dataframe looks something like this: pd.DataFrame({'Client Firm':['Cetera Financial Services','LPL Financial Advisors','Raymond James Advisors'],'AUM':['50','30','40']})
has comment: http://stackoverflow.com/comment/89942724
tagged with: python
has comment: http://stackoverflow.com/comment/89942523
answer count: 0
score: 0
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/89942838
linked to: http://stackoverflow.com/q/51353928
has comment: http://stackoverflow.com/comment/89944017
has comment: http://stackoverflow.com/comment/89942638
has comment: http://stackoverflow.com/comment/89942784
tagged with: pandas
has title: iterrows() sometimes works and sometimes doesn't

http://stackoverflow.com/comment/90242116
score: 0
has text: @hpaulj Great, thanks a lot!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51635713

http://stackoverflow.com/comment/90183594
has text: I am saying you don't have to scroll because it's clearly in view, open that site you can see.
score: 0
comment on: http://stackoverflow.com/a/51587095
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90050549
has text: It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask].
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51541392

http://stackoverflow.com/a/51545158
answers question: http://stackoverflow.com/q/51540384
accepted answer of: http://stackoverflow.com/q/51540384
type: AcceptedAnswer
score: 0
has body: In case someone need it! I just found a solution, probably not the best but it works. I asociate all the values from that column to a color in a map and just use it for "c": col = df['Causa DDW'].map({'EXC': 'g', 'MOD': 'b', 'DUR': 'r'})
type: Answer

http://stackoverflow.com/comment/90133826
type: QuestionComment
comment on: http://stackoverflow.com/q/51584172
score: 0
has text: What have your tried / researched? Do you just need the raw text or do you need further processing? The lack of this information is likely why you query has been down voted.
type: Comment

http://stackoverflow.com/comment/90153052
has text: Thanks, this was exactly what I needed
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51593420
score: 0

http://stackoverflow.com/comment/90207047
type: Comment
type: QuestionComment
has text: You do not need the line `theta2, phi2 = np.meshgrid(phiInit, thetaInit)`. Just use `thetaInit` and `phiInit` in the last three statements.
score: 0
comment on: http://stackoverflow.com/q/51620634

http://stackoverflow.com/comment/94678974
score: 0
has text: TCP is a byte stream, although you may often/sometimes happen to receive the same chunks you send this isn’t in any way guaranteed. You need to add a way of distinguising the start/end of each message. For classic TCP protocols like http and ftp (among others) this is done by make the messages printable characters and using carriage-return/linefeed the end of message. At the receiving end you have to buffer received characters until you see the \n then process the message conserving any extra characters.
comment on: http://stackoverflow.com/q/51590277
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51488941
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89946839
has body: Context I am relatively new to python / computer programming and trying to wrap my head around some basic concepts by playing around with them. In my understanding, python is an interpreted language i.e. it evaluates the line of code as it is being executed. Question In a function, why does interpreter check for a variable assignment by going down the code and not execute the line it is on, especially, since all relevant information is available? Example: def spam(): eggs = 'spam local' print(eggs) global eggs print(eggs) eggs = 'global' print(eggs) Error: The code above results in the following error: "SyntaxError: name 'eggs' is used prior to global declaration" Confusion: In my mind, 2nd line explicitly assigns "spam local" to the variable 'eggs'. Hence, when the interpreter reaches line 3 i.e print(eggs), it should print "spam local" and not go down the code to see there is a global declaration of the variable and return the SyntaxError. Why is the interpreter not executing the line it is one, given that all relevant information is available?
tagged with: global
tagged with: variables
accepted answer: http://stackoverflow.com/a/51488988
has title: Python: Why does interpreter search for variable assignment in a function below the line being executed?
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89946791
has comment: http://stackoverflow.com/comment/89946745
tagged with: interpreter
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51488988
has comment: http://stackoverflow.com/comment/89946803
tagged with: local

http://stackoverflow.com/q/51550585
has comment: http://stackoverflow.com/comment/90081116
tagged with: pyserial
linked to: http://stackoverflow.com/q/17172878
has comment: http://stackoverflow.com/comment/90148216
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90087593
tagged with: python
has comment: http://stackoverflow.com/comment/90159702
has comment: http://stackoverflow.com/comment/90158846
has title: Python: Allowing seperate process created as a class to read/write a variable
has comment: http://stackoverflow.com/comment/90172639
tagged with: tkinter
answer count: 0
linked to: http://stackoverflow.com/q/47877508
has body: I am working on a project that will have a tkinter GUI running in one process, and a second process that is reading data from an Arduino over pyserial. These processes are defined using the class based method, as seen in this stackoverflow post. I would like to be able to have the tkinter class send messages that will be sent over the serial line, and for the tkinter class to be able to read the data from the Arduino. I understand that a queue would be best if I was reading all of the data as it came in (such as sending information to the arduino), but for getting data to display on the tkinter GUI, I want to only periodically poll the most recent line that was received from the arduino. From what I can tell, the best way to share a variable between processes would be to use a manager, but all of the examples using a manager do not use class-based processes. The only example that I can find is this stackexchange post. However, the sample that he has written is not complete, and I cannot seem to figure out what else needs to be added to the code in order for the method to work. I suppose that my question is twofold: Is a manager class the best way to do this, if not what is How exactly do I get the data to be shared, as all of my attempts do not seem to share data between the processes. Here is the code that I have written (without a manager class) import tkinter as tk import multiprocessing import serial import time from multiprocessing.managers import BaseManager # pylint: disable=C0111 accData = [1, 2, 3] gyroData = [4, 5, 6] magData = [7, 8, 9] altitude = 10 temp = 11 pres = 12 class SerCotrol(multiprocessing.Process): def run(self): ser = serial.Serial('COM4', 9600) while not self.exit.is_set(): s = ser.write(b'h') s = ser.read(10) s = s.decode("utf-8") x = s.split('\t') for i, num in enumerate(x): try: x[i] = int(float(num)) except ValueError: pass ser.close() def __init__(self, shared): self.exit = multiprocessing.Event() multiprocessing.Process.__init__(self)…
tagged with: python-multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/90159786
linked to: http://stackoverflow.com/q/49660594
score: 0

http://stackoverflow.com/comment/90132649
comment on: http://stackoverflow.com/a/51583650
score: 0
type: AnswerComment
type: Comment
has text: Thanks, but I'm getting a "dict_values" object does not support indexing error where you use [0]

http://stackoverflow.com/comment/90045874
score: 0
has text: Hm, why learn the model when you already know it from physics? Also, you could be right :D
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51522011

http://stackoverflow.com/comment/90093215
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51563088
has text: I tried making the variable more global before I asked the question, but it didn't seem to work. Whenever I tested it, it would say that local variable mood referenced before assignment. I think it thinks that I'm trying to declare the variable inside the function, but that's not the case.
type: AnswerComment

http://stackoverflow.com/comment/90306316
comment on: http://stackoverflow.com/a/51654302
score: 0
type: Comment
has text: you could change that to Error instead of COMError
type: AnswerComment

http://stackoverflow.com/comment/90200125
score: 0
has text: I 'd recommend keeping the two dags separate. Maybe create two dags based on config. Does it make any sense to you?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51617236

http://stackoverflow.com/q/51545986
accepted answer: http://stackoverflow.com/a/51546071
favorite count: 0
has comment: http://stackoverflow.com/comment/90059679
tagged with: eval
has comment: http://stackoverflow.com/comment/90059653
score: 5
has comment: http://stackoverflow.com/comment/90059760
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90059897
has body: I'm trying to evaluate a function at x0 f = lambda x:mu*div2d(grad2d(x))+x-b I tried this: def feval(f, *args): return eval(f)(*args) feval(f,x0) but it throws up a traceback: Traceback (most recent call last): File "&lt;ipython-input-128-6be96feb06d6&gt;", line 1, in &lt;module&gt; feval(f,x0) File "&lt;ipython-input-126-67b053764219&gt;", line 2, in feval return eval(f)(*args) TypeError: eval() arg 1 must be a string, bytes or code object I also read that using eval() is bad practice. What'd be a good way to do this then? Thanks.
has answer: http://stackoverflow.com/a/51546071
type: Question
has title: TypeError: eval() arg 1 must be a string, bytes or code object
upvote count: 5
has comment: http://stackoverflow.com/comment/90059743
has comment: http://stackoverflow.com/comment/90059847
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51582764
type: AnsweredQuestion
has body: Again, a python newbie -- but constantly learning. I have a DataFrame below as follows: Printing one line above and one line below tags=QQQ timestamp close high low open tags vol new_column 719 2002-11-13 54.2400 55.9300 54.1100 55.3600 None 536 0.002 720 2002-11-14 55.9900 57.0000 55.8700 56.9900 QQQ 391 0.032 721 2002-11-15 56.6000 56.9200 55.6700 56.6900 None 387 0.010 3204 2012-09-26 30.2800 30.6000 30.0400 30.1650 None 546 -0.021 3205 2012-09-27 30.1700 30.4000 29.8900 30.1600 QQQ 471 -0.003 3206 2012-09-28 30.1800 30.2600 29.7400 29.7600 None 542 0.0003 3534 2014-01-22 36.2600 36.3200 35.7500 35.9300 None 219 -0.015 3535 2014-01-23 36.0900 36.1300 35.5200 36.0550 QQQ 430 -0.004 3536 2014-01-24 37.4500 37.5500 36.5300 36.8050 None 763 0.037 How can I create 'n' (in this case 3) dataframes, with unique names, consisting of data which is one above and one below the tags=QQQ ? I am thinking of using a for loop but have not achieved any success so far.
tagged with: dataframe
type: Question
score: 0
tagged with: for-loop
answer count: 1
has answer: http://stackoverflow.com/a/51582950
tagged with: pandas
has title: Pandas - Slicing a bigger dataframe into smaller dataframes using a for loop
tagged with: python
accepted answer: http://stackoverflow.com/a/51582950

http://stackoverflow.com/comment/90217090
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51626170
type: QuestionComment
has text: @ShanavasM see edit

http://stackoverflow.com/q/51530628
has answer: http://stackoverflow.com/a/51530683
accepted answer: http://stackoverflow.com/a/51530683
has title: Socket keep returning double string value
answer count: 2
favorite count: 0
downvote count: 3
tagged with: sockets
score: -3
tagged with: python
upvote count: 0
possible better answer: http://stackoverflow.com/a/51530789
has body: So i made a simple server-client with socket in python and i have this problem is that the server keep returning double of the string from client can anyone help me? thanks. Server: def new_user(client,addr): while True: data = client.recv(10030) client.settimeout(5.0) if not data: break if data == ("-quit-"): break data = data.upper() print("Client -&gt;",data) data = raw_input("Admin -&gt;") client.send(data) client.close() def main(): start_user() def start_user(): s = socket.socket() s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) print("Socket Telah Dibuat") try: s.bind(('',4303)) print("Bind telah dibuat") except: print("Bind failed"+str(sys.exc_info())) sys.exit(1) s.listen(1) while True: client , addr = s.accept() print("Client telah connect:"+str(addr)) Thread(target=new_user,args=(client,addr)).start() s.close() Client: def main(): s = socket.socket() print("Socket Telah Dibuat") try: s.connect(('',4303)) print("telah connect") except: print("connection failed"+str(sys.exc_info())) sys.exit(1) print("Untuk Quit Masukkan--quit--:") message = raw_input("-&gt;") while message != ("--quit--"): s.send(message) data = s.recv(10030) if not data: break data = data.upper() print("Admin -&gt;",data) message = raw_input("-&gt;") s.send(message) s.close() server run ('Client -&gt;', 'HELLO')-- from here Admin -&gt;yes ('Client -&gt;', 'WHAT UP') Admin -&gt;yo too ('Client -&gt;', 'WHAT UP') Admin -&gt;what -- to here is still working ('Client -&gt;', 'LETS MEET UPLETS MEET UP') &lt;--this where its start to get error client run Socket Telah Dibuat telah connect Untuk Quit Masukkan--quit--: -&gt;hello ('Admin -&gt;', 'YES') -&gt;what up ('Admin -&gt;', 'YO TOO') -&gt;lets meet up ('Admin -&gt;', 'WHAT ')
has answer: http://stackoverflow.com/a/51530789
type: Question
type: AnsweredQuestion
tagged with: network-programming

http://stackoverflow.com/q/51580548
has answer: http://stackoverflow.com/a/51583062
has comment: http://stackoverflow.com/comment/90126890
has answer: http://stackoverflow.com/a/51581232
favorite count: 0
has body: How can I set manually DateTimeField value given date and time ? Here is my model and I am trying to assign date &amp; time value to "created_at" field: class Attendance(models.Model): employee = models.ForeignKey(Employee) company = models.ForeignKey(Company) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ​ def __str__(self): return self.employee.username ​ Here is something I tried in the console:​ ​ &gt; o = Attendance.objects.last() &gt; o.updated_at datetime.datetime(2018, 6, 26, 0, 45, 31, 829827, tzinfo=&lt;UTC&gt;) &gt; x = datetime.strptime('17/07/2018 12:20', '%d/%m/%Y %H:%M') &gt; x datetime.datetime(2018, 7, 17, 12, 20) &gt;o.updated_at = x o.save() &gt;z = Attendance.objects.last() &gt;z.updated_at datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, tzinfo=&lt;UTC&gt;) notice that I set "2018, 7, 17" but it appears "2018, 7, 29". is the assignment correct ? probably it needs the timezone as well.
has comment: http://stackoverflow.com/comment/90127231
has comment: http://stackoverflow.com/comment/90127510
tagged with: datetime
has comment: http://stackoverflow.com/comment/90126687
linked to: http://stackoverflow.com/q/33280135
tagged with: python
has comment: http://stackoverflow.com/comment/90127054
has comment: http://stackoverflow.com/comment/90126702
downvote count: 0
type: UnansweredQuestion
tagged with: django
linked to: http://stackoverflow.com/q/13866926
type: Question
has comment: http://stackoverflow.com/comment/90126634
linked to: http://stackoverflow.com/q/3305413
score: 1
has title: Django - How can I set manually DateTimeField value given date and time?
has comment: http://stackoverflow.com/comment/90126615
answer count: 2
tagged with: django-queryset
upvote count: 1
has comment: http://stackoverflow.com/comment/90127098

http://stackoverflow.com/q/51602194
has title: How to concatenate two tensors having different shape with TensorFlow?
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51847393
has answer: http://stackoverflow.com/a/51602416
accepted answer: http://stackoverflow.com/a/51602416
tagged with: tensorflow
type: Question
upvote count: 4
tagged with: numpy
answer count: 2
downvote count: 0
tagged with: neural-network
score: 4
has body: Hello I'm new with TensorFlow and I'd like to concatenate a 2D tensor to a 3D one. I don't know how to do it by exploiting TensorFlow functions. tensor_3d = [[[1,2], [3,4]], [[5,6], [7,8]]] # shape (2, 2, 2) tensor_2d = [[10,11], [12,13]] # shape (2, 2) out: [[[1,2,10,11], [3,4,10,11]], [[5,6,12,13], [7,8,12,13]]] # shape (2, 2, 4) I would make it work by using loops and new numpy arrays, but in that way I wouldn't use TensorFlow transformations. Any suggestions on how to make this possible? I don't see how transformations like: tf.expand_dims or tf.reshape may help here... Thanks for sharing your knowledge.
possible better answer: http://stackoverflow.com/a/51847393

http://stackoverflow.com/a/51627178
accepted answer of: http://stackoverflow.com/q/51626790
has comment: http://stackoverflow.com/comment/90219211
answers question: http://stackoverflow.com/q/51626790
has comment: http://stackoverflow.com/comment/90219503
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90219266
upvote count: 2
has body: You should print the line to standard output: def passwd_safe(): file = "/etc/passwd" for line in fileinput.input(file,inplace=1): if not line.startswith('+'): print(line, end='') Excerpt from fileinput's documentation: Optional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently).
has comment: http://stackoverflow.com/comment/90219614
type: AcceptedAnswer

http://stackoverflow.com/a/51485352
has comment: http://stackoverflow.com/comment/89940442
has comment: http://stackoverflow.com/comment/89939799
accepted answer of: http://stackoverflow.com/q/51485042
type: Answer
answers question: http://stackoverflow.com/q/51485042
has body: Try numpy.array2string which takes ndarray as input and you can set precision. Scroll down in below documentation link for examples. https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.array2string.html
has comment: http://stackoverflow.com/comment/89940282
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90046507
has text: It is not printing the values over 1 when the lists in values contain repetitive elements
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51539404
score: 1

http://stackoverflow.com/comment/90202260
score: 0
type: Comment
type: QuestionComment
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.
comment on: http://stackoverflow.com/q/51618323

http://stackoverflow.com/comment/90128983
comment on: http://stackoverflow.com/a/51581762
has text: Same -- this is the right way to do it (and 12 minutes earlier than mine!)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90029190
score: 1
comment on: http://stackoverflow.com/q/51530578
has text: Did you set AUTH_USER_MODEL to None?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90114318
type: Comment
comment on: http://stackoverflow.com/a/51573593
type: AnswerComment
has text: This gives me an href link indeed, but i am looking for the html content of href, not the href itslelf. Plus when i try to open the resulted href manually it does give me :'Page not found' error, This is the href i am trying to open:https://www.quora.com/api/mobile_expanded_voter_list?key=2EacbahnSx&type=answer
score: 0

http://stackoverflow.com/comment/90248351
score: 0
type: AnswerComment
has text: Thank you for catching that! I updated the answer for completeness.
type: Comment
comment on: http://stackoverflow.com/a/51563899

http://stackoverflow.com/a/51517637
has comment: http://stackoverflow.com/comment/90007742
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51517517
answers question: http://stackoverflow.com/q/51517517
has body: Single criterion If you are looking only to update rows with "Miscellaneous": d = {'Helipad': 'Transport Services', 'Restaurant': 'Fooding &amp; Lodging Services'} mask = data['CATEGORY'] == 'Miscellaneous' df.loc[mask, 'CATEGORY'] = df.loc[mask, 'SUB_CAT'].map(d) Multiple criteria Construct a dictionary with a structure mapping criteria to value: d = {('Miscellaneous', 'Helipad'): 'Transport Services', ('Miscellaneous', 'Restaurant'): 'Fooding &amp; Lodging Services'} Then use pd.Series.map: # extract series of tuples tups = data.set_index(['CATEGORY', 'SUB_CAT']).index.to_series() # alternatively: # tups = pd.Series(list(zip(data['CATEGORY'], data['SUB_CAT']))) # map series to values data['CATEGORY'] = tups.map(d).fillna(data['CATEGORY'])
has comment: http://stackoverflow.com/comment/90004479
has comment: http://stackoverflow.com/comment/90006087
score: 0
type: Answer

wifi
tag name: wifi
type: Tag
tags question: http://stackoverflow.com/q/51569251

http://stackoverflow.com/comment/90005032
comment on: http://stackoverflow.com/q/51517685
type: Comment
type: QuestionComment
has text: No problem, thanks a lot. But apart from imageio, is there another way to do this task ?
score: 0

http://stackoverflow.com/comment/90040261
has text: Correct, I'm using version 0.22.0.
type: Comment
comment on: http://stackoverflow.com/a/51536279
score: 0
type: AnswerComment

http://stackoverflow.com/q/51597888
has title: Upload big file to S3
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90171303
tagged with: boto
has body: I have python 2.7, pip and boto on my machine. I need to upload a zip file of about 400 MB to an S3 bucket. The upload works on small files, but fails with this error when uploading the required 400 MB file. BotoServerError: 400 Bad Request I am using code below. Any ideas? def UploadFileToS3(self, zippedfile, aws_access_key_id, aws_secret_access_key, bucket, awsfolder, callback=None, md5=None, reduced_redundancy=False, content_type=None): #def UploadFileToS3(self, zippedfile, callback=None, md5=None, reduced_redundancy=False, content_type=None): try: file = open(zippedfile, 'r+') key = file.name try: size = os.fstat(file.fileno()).st_size except Exception as ex: # Not all file objects implement fileno(), # so we fall back on this file.seek(0, os.SEEK_END) size = file.tell() conn = boto.connect_s3(aws_access_key_id, aws_secret_access_key) bucket = conn.get_bucket(bucket, validate=True) k = Key(bucket) #k.key = key filename = os.path.basename(zippedfile) k.key = awsfolder + "/" + filename if content_type: k.set_metadata('Content-Type', content_type) sent = k.set_contents_from_file(file, cb=callback, md5=md5, reduced_redundancy=reduced_redundancy, rewind=True) # Rewind for later use file.seek(0) except Exception as ex: print "Error encountered while uploading to S3. " + unicode(ex) if sent != None: if sent == size: return True return False #enddef Stacktrace: Traceback (most recent call last): File "C:\AJ\scripts\GISSTdbS3ExtractFunctions.py", line 286, in UploadFileToS3 sent = k.set_contents_from_file(file, cb=callback, md5=md5, reduced_redundancy=reduced_redundancy, rewind=True) File "C:\Python27\python2714\Lib\site-packages\boto\s3\key.py", line 1309, in set_contents_from_file chunked_transfer=chunked_transfer, size=size) File "C:\Python27\python2714\Lib\site-packages\boto\s3\key.py", line 762, in send_file chunked_transfer=chunked_transfer, size=size) File "C:\Python27\python2714\Lib\site-packages\boto\s3\key.py", line 963, in _ send_file_internal query_args=query…
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/90162308
type: Question
has comment: http://stackoverflow.com/comment/90205275
has comment: http://stackoverflow.com/comment/90171985
has comment: http://stackoverflow.com/comment/90168499

http://stackoverflow.com/q/51502052
accepted answer: http://stackoverflow.com/a/51502175
answer count: 2
has comment: http://stackoverflow.com/comment/89972909
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89972577
tagged with: string-formatting
has comment: http://stackoverflow.com/comment/89972567
tagged with: python
type: AnsweredQuestion
has title: f-string behaves differently then the format method for nested formatting
upvote count: 3
tagged with: f-string
has answer: http://stackoverflow.com/a/51502175
possible better answer: http://stackoverflow.com/a/51502245
has answer: http://stackoverflow.com/a/51502245
type: Question
linked to: http://stackoverflow.com/q/48559775
score: 3
has comment: http://stackoverflow.com/comment/89972766
tagged with: python-3.6
has body: I am doing nested formatting using format and it doesn't work as expected. however if i try to do it with f-strings it works perfectly. example: doing this: values = 'first', 'second', 'third' a = f"""cardinality and values: {'|'.join(f'val:{val}, card:{i}'for i, val in enumerate(values))} """ gives me this (the needed result): 'cardinality and values: val:first, card:0|val:scond, card:1|val:third, card:2' however if i try to do it using format: a = """cardinality and values: {'|'.join('val:{val}, card:{i}'.format(val=val, i=i) for i, val in enumerate(values))} """.format(values=values) I get the following exception: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: "'|'" how do i do this with format ? I need to use format instead of f-strings because another file imports this string and then formats it.

http://stackoverflow.com/a/51581680
answers question: http://stackoverflow.com/q/51539424
has comment: http://stackoverflow.com/comment/90192572
has body: You have to use from_json or equivalent method. If structure of the document looks like in the question from pyspark.sql.functions import from_json, col from pyspark.sql.types import * schema = StructType([ StructField("id", LongType()), StructField("timestamp", LongType()), StructField("distances", ArrayType(LongType())) ]) ds = spark.readStream.load(...) ds.withColumn("value", from_json(col("value").cast("string"), schema))
score: 0
type: Answer
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/51489309
has answer: http://stackoverflow.com/a/51489369
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/89947630
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/51529774
has comment: http://stackoverflow.com/comment/90026552
has answer: http://stackoverflow.com/a/51491208
tagged with: string
has comment: http://stackoverflow.com/comment/89971994
favorite count: 0
accepted answer: http://stackoverflow.com/a/51529774
has title: How do I remove all possible extraneous spaces, tabs, next line, and others from an input to clean up a stdin python input?
tagged with: python
has answer: http://stackoverflow.com/a/51489365
answer count: 4
type: AnsweredQuestion
has body: I have tried the following code in different variations with no avail. The user may input unstructured data like so "4231, 312 1231212,12 1 23 123,12,3,123 123 1,2, 3123" , and i am trying to clean it up to [4231, 312, 1231212, 12, 1, 23, 123, 12 , 3, 123, 123, 1, 2, 3123] Code: print("Please enter the numbers (separated by space, comma or line) then press CMD/CTRL D :") num_input = sys.stdin.read() def convert_number_input(integer_inputs): """Takes integer inputs separated by comma or space or line as a string and converts to list of operable integers. First checks for comma typos in input, then removes spaces and irrelevant data, then finally converts to integer. If just one number is the input it simply converts it to integer list""" first_input = re.sub(r"[\n\t\s]", " ", integer_inputs) all_comma_input = first_input.strip() stripping_input = all_comma_input.replace(' ', ',') fresh_input = stripping_input.strip(',') clean_integer_inputs = fresh_input.replace(',,,', ',') very_clean_integer_inputs = clean_integer_inputs.replace(',,', ',') split_input = very_clean_integer_inputs.split(',') final_input = list(map(int, split_input)) return final_input final_num_input = convert_num_input(num_input) print(final_num_input)
possible better answer: http://stackoverflow.com/a/51489369
tagged with: list
has comment: http://stackoverflow.com/comment/90027775

http://stackoverflow.com/comment/90223182
has text: On which python version do you want TensorFlow? You are using the commands for both 3.* and 2.* versions..
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51629358

http://stackoverflow.com/comment/89958739
type: AnswerComment
has text: @Encode.to.code I have updated the answer with an example of how to instantiate a class. There are many different ways to learn a new language, depending on which learning method works best for you. Doing exercises like this is one way, another that I found particularly useful was reading through the O'Reilly Introduction to Python book. But the internet is full of useful resources if you don't want to invest in a book.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51483639

http://stackoverflow.com/comment/90034645
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51520884
has text: books is passed into the html here: {% for book in books %} in the first code snippet. This part of the code renders correctly
type: Comment

http://stackoverflow.com/a/51543370
has comment: http://stackoverflow.com/comment/90064028
has comment: http://stackoverflow.com/comment/90062653
accepted answer of: http://stackoverflow.com/q/51503889
has body: There is nothing special in using multiple inputs for GP regression, apart maybe that, for the anisotropic case, you must provide explicitly the relevant arguments in the kernel definition. Here is a simple example for dummy 5D data, as yours, and an isotropic RBF kernel: from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF from sklearn.datasets import make_regression import numpy as np # dummy data: X, y = make_regression(n_samples=20, n_features=5, n_targets=1) X.shape # (20, 5) kernel = RBF(length_scale=1.0, length_scale_bounds=(1e-1, 10.0)) gp = GaussianProcessRegressor(kernel=kernel) gp.fit(X, y) # GaussianProcessRegressor(alpha=1e-10, copy_X_train=True, # kernel=RBF((length_scale=1), n_restarts_optimizer=0, # normalize_y=False, optimizer='fmin_l_bfgs_b', # random_state=None) UPDATE: In the anisotropic case, you should define the different parameters explicitly in the kernel; here is an example definition for the RBF kernel and a 2D variable: kernel = RBF(length_scale=[1.0, 2.0], length_scale_bounds=[(1e-1, 10.0), (1e-2, 1.0)]) Extend analogously for the 5D case.
upvote count: 1
has comment: http://stackoverflow.com/comment/90063683
score: 1
has comment: http://stackoverflow.com/comment/90063437
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90062866
downvote count: 0
has comment: http://stackoverflow.com/comment/90063129
answers question: http://stackoverflow.com/q/51503889
has comment: http://stackoverflow.com/comment/90063149
has comment: http://stackoverflow.com/comment/90063210
has comment: http://stackoverflow.com/comment/90062711
type: Answer

http://stackoverflow.com/q/51606105
tagged with: python-tesseract
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
has title: Restrict cores for multiprocessing in Tesseract
has comment: http://stackoverflow.com/comment/90178736
type: Question
has comment: http://stackoverflow.com/comment/90256846
downvote count: 0
favorite count: 0
tagged with: redis
has body: image of running process status I am trying to implement multiprocessing with redis queue. The job inserted in the queue is tesseract ocr process on a file having 11 pages, taking approx. 70 sec. I started 2 workers and inserted 2 jobs inside redis queue, which were fetched by workers respectively. Expected output: Both workers should execute tesseract simultaneously on respective files. Current Output: Switching is happening between the jobs. At one time, 1 image is getting processed inside first worker and then image of another file is processed on another worker. So, both workers are giving output at same time after 140 seconds. How do i restrict the Tesseract process to use only half of the cpu cores so that both process can run simultaneously. Technology used: Python, Pytesseract, Redis queue.
tagged with: python
tagged with: tesseract

http://stackoverflow.com/q/51622756
has comment: http://stackoverflow.com/comment/90241470
has answer: http://stackoverflow.com/a/51683490
score: 0
answer count: 2
tagged with: arcmap
has comment: http://stackoverflow.com/comment/90242673
has comment: http://stackoverflow.com/comment/90242219
has body: I am just too new to Python to figure it out myself. Here goes: I have a table of Traffic Count data with: Street Location | Direction | Dir__NB_or | Dir_SB_or and I was attempting to write a reclassification into the new field of Count. What I am looking for is a script to say: "if direction is N or E, insert Dir__NB_or into field Count" Is what I have, (probably horrific) but I would appreciate any help you can provide! Reclass (Dir__NB_or , Dir_SB_or, Direction): if (Direction == "N"): return Dir__NB_or elif (Direction == "S"): return Dir_SB_or elif (Direction == "E"): return Dir__NB_or elif (Direction == "W"): return Dir_SB_or else: return "0000" Count = Reclass ( !Dir__NB_or! , !Dir_SB_or!, !Direction! ) Edit: I should mention I am using ESRI's ArcMap and Field Calculator for this task.
tagged with: python
has title: Reclassifying an "Add Field" with If/Else statement based on multiple fields
accepted answer: http://stackoverflow.com/a/51683490
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90211213
has comment: http://stackoverflow.com/comment/90241431
type: Question
possible better answer: http://stackoverflow.com/a/51622927
has answer: http://stackoverflow.com/a/51622927
tagged with: if-statement
has comment: http://stackoverflow.com/comment/90241898

http://stackoverflow.com/comment/90154031
type: Comment
comment on: http://stackoverflow.com/a/51593640
score: 1
has text: No need for the anchor and flag unless you use the negated colon `[^:]` group instead of the dot. `.` does not match newlines without the dotall (s) flag.
type: AnswerComment

http://stackoverflow.com/comment/90102529
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51568034
has text: Ah, gotcha, that makes sense. Thanks for the clarification, I think I have enough information to work with now.
score: 0

http://stackoverflow.com/a/51615979
has comment: http://stackoverflow.com/comment/90265300
answers question: http://stackoverflow.com/q/51611102
has comment: http://stackoverflow.com/comment/90265420
has comment: http://stackoverflow.com/comment/90210488
has comment: http://stackoverflow.com/comment/90235239
has comment: http://stackoverflow.com/comment/90274744
score: 0
has body: Add the following line of code at the end of function def number: return Level
type: Answer
has comment: http://stackoverflow.com/comment/90265321

jupyter-notebook
tags question: http://stackoverflow.com/q/51566497
tags question: http://stackoverflow.com/q/51601061
tags question: http://stackoverflow.com/q/51518231
tags question: http://stackoverflow.com/q/51563702
tags question: http://stackoverflow.com/q/51496267
tags question: http://stackoverflow.com/q/51584430
tags question: http://stackoverflow.com/q/51590030
tags question: http://stackoverflow.com/q/51498951
tags question: http://stackoverflow.com/q/51499289
tags question: http://stackoverflow.com/q/51551056
tags question: http://stackoverflow.com/q/51576005
tags question: http://stackoverflow.com/q/51523301
tags question: http://stackoverflow.com/q/51485828
tags question: http://stackoverflow.com/q/51529791
tags question: http://stackoverflow.com/q/51534912
tags question: http://stackoverflow.com/q/51550507
tags question: http://stackoverflow.com/q/51573241
tags question: http://stackoverflow.com/q/51628155
tags question: http://stackoverflow.com/q/51634886
tags question: http://stackoverflow.com/q/51515137
tags question: http://stackoverflow.com/q/51569300
tags question: http://stackoverflow.com/q/51599488
type: Tag
tags question: http://stackoverflow.com/q/51560750
tags question: http://stackoverflow.com/q/51596139
tags question: http://stackoverflow.com/q/51595172
tags question: http://stackoverflow.com/q/51604079
tags question: http://stackoverflow.com/q/51613670
tags question: http://stackoverflow.com/q/51532750
tags question: http://stackoverflow.com/q/51548928
tags question: http://stackoverflow.com/q/51622472
tags question: http://stackoverflow.com/q/51610195
tags question: http://stackoverflow.com/q/51549853
tags question: http://stackoverflow.com/q/51533001
tags question: http://stackoverflow.com/q/51613845
tags question: http://stackoverflow.com/q/51581139
tags question: http://stackoverflow.com/q/51572352
tags question: http://stackoverflow.com/q/51546983
tags question: http://stackoverflow.com/q/51512907
tags question: http://stackoverflow.com/q/51512303
tags question: http://stackoverflow.com/q/51612124
tags question: http://stackoverflow.com/q/51568030
tags question: http://stackoverflow.com/q/51617979
tags question: http://stackoverflow.com/q/51596896
tags question: http://stackoverflow.com/q/51615888
tags question: http://stackoverflow.com/q/51568083
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/51599227
tags question: http://stackoverflow.com/q/51513603
tags question: http://stackoverflow.com/q/51614853
tags question: http://stackoverflow.com/q/51551891
tags question: http://stackoverflow.com/q/51588840
tags question: http://stackoverflow.com/q/51548753
tags question: http://stackoverflow.com/q/51579073
tags question: http://stackoverflow.com/q/51576756
tags question: http://stackoverflow.com/q/51609864

http://stackoverflow.com/q/51635290
has body: I have 2 columns, which we'll call x and y. I want to create a new column called xy: x y xy 1 1 2 2 4 4 8 8 There shouldn't be any conflicting values, but if there are, y takes precedence. If it makes the solution easier, you can assume that x will always be NaN where y has a value.
favorite count: 0
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51635395
has answer: http://stackoverflow.com/a/51635395
has answer: http://stackoverflow.com/a/51635663
accepted answer: http://stackoverflow.com/a/51635317
upvote count: 3
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: dataframe
has title: Pandas - combine two columns
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51635317

http://stackoverflow.com/a/51582473
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51525364
has body: How about this approach? import pandas as pd df = pd.DataFrame({'ColA': ['A','B','C'], 'ColB': ['D','E','F' ],'ColC':['G','H','I'],'Name':['Rajish','Rohit','Rahim']}) print(df) Result: ColA ColB ColC Name 0 A D G Rajish 1 B E H Rohit 2 C F I Rahim Then do the transform: import pandas as pd df = pd.DataFrame({'ColA': ['A','B','C'], 'ColB': ['D','E','F' ],'ColC':['G','H','I'],'Name':['Rajish','Rohit','Rahim']}) print(df) Result: df2 = (df.set_index(['Name']) .stack(dropna=False)) print(df2)

http://stackoverflow.com/q/51489163
has title: python : How to include third party app by cx_freeze and bdist_msi?
type: Question
linked to: http://stackoverflow.com/q/17307934
has body: I extracted the python package as an msi file by cx_freeze and bdist_msi. The msi file consisting only of the python package confirmed its installation and execution. Next step, I want to include the third party windows application(ex:sqlite) in the installation file. Is there a way to include third-party applications as cx_freeze only or another application? python version : 3.6.5. OS : windows 10
tagged with: windows-installer
score: 0
type: UnansweredQuestion
tagged with: windows
has comment: http://stackoverflow.com/comment/89956466
has comment: http://stackoverflow.com/comment/89955073
tagged with: python
answer count: 0
tagged with: installation

http://stackoverflow.com/comment/89939902
type: Comment
has text: if I do: scaler = MinMaxScaler(feature_range=(0, 1)), scaler.fit_transform(valuesX) your command clf = joblib.load('filename.pkl') will restore my "scaler" ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51485224

http://stackoverflow.com/q/51529458
has comment: http://stackoverflow.com/comment/105970591
has answer: http://stackoverflow.com/a/51529459
has body: Assume I created a @dataclass class Foo, and added a __post_init__ to perform type checking and processing. When I attempt to yaml.load a !Foo object, __post_init__ is not called. from dataclasses import dataclass, fields from ruamel.yaml import yaml_object, YAML yaml = YAML() @yaml_object(yaml) @dataclass class Foo: foo: int bar: int def __post_init__(self): raise Exception for field in fields(self): value = getattr(self, field.name) typ = field.type if not isinstance(value, typ): raise Exception s = '''\ !Foo foo: "foo" bar: "bar" ''' yaml.load(s) How do I perform parameter checking when loading dataclasses via ruamel.yaml? This behavior occurs in Python 3.7 as well as 3.6 with pip install dataclasses.
linked to: http://stackoverflow.com/q/37259748
tagged with: yaml
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: ruamel.yaml
has title: When ruamel.yaml loads @dataclass from string, __post_init__ is not called
score: 7
upvote count: 7
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51534889

http://stackoverflow.com/q/51582899
tagged with: flask-sqlalchemy
tagged with: python
has answer: http://stackoverflow.com/a/73601227
has answer: http://stackoverflow.com/a/51597671
type: AnsweredQuestion
score: 0
has title: SQLAlchemy min/max of query with limit
tagged with: sqlalchemy
type: Question
has body: Hello everyone, I have a couple of sensors reading temperature and humidity. With SQLAlchemy I succeeded to query the last ten results of every sensor with: sensorlist = db.session.query(Sensor).order_by(Sensor.id.asc()).all() for sensor in sensorlist: readings = sensor.readings.order_by(Sensorreading.time.desc()).limit(10) Now I want of the ten results the min and the max, so I can present that of every sensor. Something like: &lt;sensor 1, min temp = 23, max temp = 26, min hum = 56, max hum =74&gt; &lt;sensor 2, min temp = 22, max temp = 30, min hum = 51, max hum =63&gt; &lt;sensor 3, min temp = 24, max temp = 25, min hum = 62, max hum =75&gt; But I don't know how to query that with SQLAlchemy/python. For every reading I did it with this code, but then I can't get it work to limit the data before calculate min/max. If I replace .all() for .limit(10), then it just query ten sensors, instead of ten readings: sensors = db.session.query(Sensor.name, db.func.min(Sensorreading.temp_value).label("temp_value_min"), db.func.max(Sensorreading.temp_value).label("temp_value_max")).outerjoin(Sensorreading, Sensor.id == Sensorreading.sensor_id).group_by(Sensor.name).all() Just for some background information the models of my table: class Sensor(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) sensor_type = db.Column(db.Integer) pin = db.Column(db.Integer) limit_temp_up = db.Column(db.Float) limit_temp_down = db.Column(db.Float) limit_hum_up = db.Column(db.Float) limit_hum_down = db.Column(db.Float) limit_aqua_temp_up = db.Column(db.Float) limit_aqua_temp_down = db.Column(db.Float) readings = db.relationship('Sensorreading', backref='sensor', lazy='dynamic') class Sensorreading(db.Model): id = db.Column(db.Integer, primary_key=True) time = db.Column(db.DateTime) name = db.Column(db.String(50)) temp_value = db.Column(db.Float) hum_value = db.Column(db.Float) aqua_temp_value = db.Column(db.Float) sensor_id = db.Column(db.Integer, db.ForeignKe…
possible better answer: http://stackoverflow.com/a/62015423
accepted answer: http://stackoverflow.com/a/51597671
has answer: http://stackoverflow.com/a/62015423
answer count: 3

http://stackoverflow.com/a/51625654
score: 0
has comment: http://stackoverflow.com/comment/90217183
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51625542
has comment: http://stackoverflow.com/comment/90216693
has comment: http://stackoverflow.com/comment/90216525
downvote count: 1
has body: You should define directory of template like following, in your settings.py file TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(BASE_DIR), 'templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
has comment: http://stackoverflow.com/comment/90216688
has comment: http://stackoverflow.com/comment/90216262
has comment: http://stackoverflow.com/comment/90216341
has comment: http://stackoverflow.com/comment/90216672

dictionary
tags question: http://stackoverflow.com/q/51561607
tags question: http://stackoverflow.com/q/51582436
tags question: http://stackoverflow.com/q/51500703
tags question: http://stackoverflow.com/q/51526531
tags question: http://stackoverflow.com/q/51616695
tags question: http://stackoverflow.com/q/51592945
tags question: http://stackoverflow.com/q/51500003
tags question: http://stackoverflow.com/q/51581663
tags question: http://stackoverflow.com/q/51563985
tags question: http://stackoverflow.com/q/51635798
tags question: http://stackoverflow.com/q/51575139
tags question: http://stackoverflow.com/q/51580013
tags question: http://stackoverflow.com/q/51587905
tags question: http://stackoverflow.com/q/51601446
tags question: http://stackoverflow.com/q/51602125
tags question: http://stackoverflow.com/q/51510255
tags question: http://stackoverflow.com/q/51560600
tags question: http://stackoverflow.com/q/51533173
tags question: http://stackoverflow.com/q/51576629
tags question: http://stackoverflow.com/q/51619188
tags question: http://stackoverflow.com/q/51484809
tags question: http://stackoverflow.com/q/51634656
tags question: http://stackoverflow.com/q/51527264
tags question: http://stackoverflow.com/q/51541392
tags question: http://stackoverflow.com/q/51614297
tags question: http://stackoverflow.com/q/51540806
tags question: http://stackoverflow.com/q/51531488
tags question: http://stackoverflow.com/q/51598223
tags question: http://stackoverflow.com/q/51550982
tags question: http://stackoverflow.com/q/51499643
tags question: http://stackoverflow.com/q/51600336
tags question: http://stackoverflow.com/q/51578454
tags question: http://stackoverflow.com/q/51598605
tags question: http://stackoverflow.com/q/51543705
tags question: http://stackoverflow.com/q/51519411
tags question: http://stackoverflow.com/q/51569702
tags question: http://stackoverflow.com/q/51629076
tags question: http://stackoverflow.com/q/51549943
tags question: http://stackoverflow.com/q/51579184
tags question: http://stackoverflow.com/q/51600544
tags question: http://stackoverflow.com/q/51597222
tags question: http://stackoverflow.com/q/51484898
tags question: http://stackoverflow.com/q/51549315
tags question: http://stackoverflow.com/q/51609688
tags question: http://stackoverflow.com/q/51608823
tags question: http://stackoverflow.com/q/51551891
tags question: http://stackoverflow.com/q/51547252
tag name: dictionary
tags question: http://stackoverflow.com/q/51543545
tags question: http://stackoverflow.com/q/51583109
tags question: http://stackoverflow.com/q/51517759
tags question: http://stackoverflow.com/q/51569080
tags question: http://stackoverflow.com/q/51584754
tags question: http://stackoverflow.com/q/51577938
tags question: http://stackoverflow.com/q/51509894
tags question: http://stackoverflow.com/q/51587175
tags question: http://stackoverflow.com/q/51584385
tags question: http://stackoverflow.com/q/51526076
tags question: http://stackoverflow.com/q/51503997
tags question: http://stackoverflow.com/q/51502943
tags question: http://stackoverflow.com/q/51542905
tags question: http://stackoverflow.com/q/51616047
tags question: http://stackoverflow.com/q/51495352
tags question: http://stackoverflow.com/q/51567847
tags question: http://stackoverflow.com/q/51543964
tags question: http://stackoverflow.com/q/51634530
tags question: http://stackoverflow.com/q/51489548
tags question: http://stackoverflow.com/q/51570985
tags question: http://stackoverflow.com/q/51514098
tags question: http://stackoverflow.com/q/51533808
tags question: http://stackoverflow.com/q/51527379
tags question: http://stackoverflow.com/q/51620440
tags question: http://stackoverflow.com/q/51484937
tags question: http://stackoverflow.com/q/51554469
tags question: http://stackoverflow.com/q/51560689
tags question: http://stackoverflow.com/q/51611031
tags question: http://stackoverflow.com/q/51570764
tags question: http://stackoverflow.com/q/51489071
tags question: http://stackoverflow.com/q/51628032
tags question: http://stackoverflow.com/q/51505468

http://stackoverflow.com/comment/90391591
score: 0
type: AnswerComment
type: Comment
has text: This looks promising. I will have to test and update. One issue though: `# As we want all Articles, we have to fetch them` - we actually only need the articles that appear in reports from last X hours, the reports we're filtering for.
comment on: http://stackoverflow.com/a/51714041

http://stackoverflow.com/comment/90034104
type: QuestionComment
has text: Ca you add some smple data for [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) ?
comment on: http://stackoverflow.com/q/51533162
score: 0
type: Comment

http://stackoverflow.com/a/51550500
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51550459
downvote count: 0
has body: You can read the file and use exec to execute the code with the current globals so that __name__ == '__main__' would be true. exec(open('file.py').read(), globals())

http://stackoverflow.com/comment/90075911
has text: @Vikas Damodar can you explain more?
type: Comment
comment on: http://stackoverflow.com/a/51554391
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89982088
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51506404
score: 1
has text: Due to the nature of the recurrent layers, predicting one step and looping seems the best approach.

http://stackoverflow.com/q/51605392
type: Question
has comment: http://stackoverflow.com/comment/90176425
tagged with: odoo
accepted answer: http://stackoverflow.com/a/51605509
tagged with: odoo-10
answer count: 1
has comment: http://stackoverflow.com/comment/90176211
has comment: http://stackoverflow.com/comment/90176374
favorite count: 0
upvote count: 2
has body: Python Float division by zero error. I can't find any error in this. Can anybody fix it ? I'm using this code in the Odoo version 10. I tried some other ways but it was not working. Hope it might be helpful to somebody also. class etq_results(models.Model): _name = "etq.result" _description = "Exam Result" exam_id = fields.Many2one('etq.exam', string="Exam", readonly=True) user_id = fields.Many2one('student.student',"Exam candidate / Student", translate=True) score = fields.Float(string="Score", compute="_compute_score", store=True) results = fields.One2many('etq.result.question', 'result_id', string="Results", readonly=True) token = fields.Char(string="Token") state = fields.Selection([('incomplete','Incomplete'), ('complete','Complete')], string="State") @api.one @api.depends('results') def _compute_score(self): num_questions = self.env['etq.result.question'].search_count([('result_id', '=', self.id)]) correct_questions = self.env['etq.result.question'].search_count([('result_id', '=', self.id), ('correct', '=', True)]) # raise UserError(_(float(num_questions))) if float(num_questions) and float(correct_questions) is None: self.score = 0.0 else: self.score = float(correct_questions) + "/" + float(num_questions) + " " + (float(correct_questions) / float(num_questions)) * 100.0 + "%"
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51605509
has comment: http://stackoverflow.com/comment/90176312
score: 1
has title: Python Float division ny zero Error
downvote count: 1

http://stackoverflow.com/a/51604717
has body: IIUC, rename flat_df.rename(columns=nested_columns) Out[224]: One Two a c b d 0 36 19 53 46 1 17 85 63 36 2 40 80 75 86 3 31 83 75 16 Updated flat_df.columns.map(nested_columns.get) Out[15]: MultiIndex(levels=[['One', 'Two'], ['a', 'b', 'c', 'd']], labels=[[0, 0, 1, 1], [0, 2, 1, 3]])
has comment: http://stackoverflow.com/comment/90175121
type: Answer
answers question: http://stackoverflow.com/q/51604679
has comment: http://stackoverflow.com/comment/90175139
has comment: http://stackoverflow.com/comment/90175235
has comment: http://stackoverflow.com/comment/90175256
upvote count: 1
has comment: http://stackoverflow.com/comment/90175305
has comment: http://stackoverflow.com/comment/90175157
has comment: http://stackoverflow.com/comment/90175222
has comment: http://stackoverflow.com/comment/90175209
has comment: http://stackoverflow.com/comment/90175131
downvote count: 0
score: 1

http://stackoverflow.com/q/51588887
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/51589054
upvote count: 2
type: UnansweredQuestion
has body: I have a file with Contents as below:- He is good at python. Python is not a language as well as animal. Look for python near you. Hello World it's great to be here. Now, script should search for pattern "python" or "pyt" or "pyth" or "Python" or any regex related to "p/Python". After search of particular word, it should insert new word like "Lion". So output should become like below:- He is good at python. Lion Python is not a language as well as animal. Lion Look for python near you. Lion Hello World it's great to be here. How can I do that ? NOTE:- Till now I wrote code like this:- def insertAfterText(args): file_name = args.insertAfterText[0] pattern = args.insertAfterText[1] val = args.insertAfterText[2] fh = fileinput.input(file_name,inplace=True) for line in fh: replacement=val+line line=re.sub(pattern,replacement,line) sys.stdout.write(line) fh.close()
type: Question
tagged with: python-2.7
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51591596
tagged with: python
has title: How insert a string in next line for searched pattern in a file using python?
tagged with: regex

http://stackoverflow.com/q/51598868
score: 1
tagged with: file
upvote count: 1
tagged with: django-forms
type: Question
tagged with: image
has title: How do I access images uploaded through a formset in Django?
has body: I cannot seem to find a way to iterate through the files uploaded by the formset, although the files are uploaded as the code indicates. When I load the page it shows 1-3 "img src=(unkown)" tags. It shows 3 when I upload 2 images and 1 when I upload 1 image. Template view-post: {% block body %} {{ post.title }} {{ post.body }} Posted by {{ post.user }} on {{ post.created_date }} {% if not post.created_date == post.updated_date %} and updated on {{ post.updated_date }} {% endif %} {% for img in images %} {{ img.url }} {% endfor %} {% if post.cover_image %} {% endif %} {% endblock %} Here I use filter, not get, so it should give me a list of the images connected via foreignkey to the right post. The post here is displayed as it should be, along with the internal cover image and text in the post. View view-post: class ViewPost(TemplateView): template_name = 'posts/view_post.html' context_object_name = 'view_post' def get(self, request, pk): post = Post.objects.get(pk=pk) images = Images.objects.filter(post=post) args = {'post': post, 'images': images} return render(request, self.template_name, args) Template make-post: {% block body %} {% csrf_token %} {{ form.as_p }} {{ form.errors }} {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form }} {% endfor %} Submit {% endblock %} View make-post: class MakePost(DetailView): template_name = 'posts/make_post.html' ImageFormSet = modelformset_factory(Images, form=ImageForm, extra=3) def get(self, request): form = PostForm() formset = self.ImageFormSet(queryset=Images.objects.none()) args = {'form': form, 'formset': formset} return render(request, self.template_name, args) def post(self, request): form = PostForm(request.POST, request.FILES) formset = self.ImageFormSet(request.POST, request.FILES, queryset=Images.objects.none()) if form.is_valid() and formset.is_valid(): post = form.save(commit=False) post.user = request.user post.cover_image = form.cleaned_data['cover_image'] post.title = form.cleane…
accepted answer: http://stackoverflow.com/a/51599363
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51599363
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90038303
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51535241
score: 1
has text: Possible duplicate of [Local variable referenced before assignment in Python?](https://stackoverflow.com/questions/18002794/local-variable-referenced-before-assignment-in-python)

http://stackoverflow.com/a/51635317
has comment: http://stackoverflow.com/comment/90235370
has comment: http://stackoverflow.com/comment/90235175
has body: it could be quite simple if your example is accurate df.fillna(0) #if the blanks are nan will need this line first df['xy']=df['x']+df['y']
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/90234994
accepted answer of: http://stackoverflow.com/q/51635290
has comment: http://stackoverflow.com/comment/90235268
has comment: http://stackoverflow.com/comment/90235025
upvote count: 4
answers question: http://stackoverflow.com/q/51635290

http://stackoverflow.com/q/51627233
answer count: 2
has comment: http://stackoverflow.com/comment/131578223
has body: I've seen this a couple of times: # http://geopandas.org/aggregation_with_dissolve.html continents.plot(column = 'pop_est', scheme='quantiles', cmap='YlOrRd'); # https://jakevdp.github.io/PythonDataScienceHandbook/04.14-visualization-with-seaborn.html plt.legend('ABCDEF', ncol=2, loc='upper left'); # https://matplotlib.org/api/pyplot_api.html x = np.arange(0, 5, 0.1); It confuses me that it is done very often with matplotlib and also inconsistently. Is this only an error? Was it in the matplotlib documentation for a while? Does / did ; have any function at the and of a line in Python? (This suggests the answer is "no", but it does not explain why it is so wide-spread with matplotlib.)
accepted answer: http://stackoverflow.com/a/51629429
favorite count: 0
linked to: http://stackoverflow.com/q/14506583
has comment: http://stackoverflow.com/comment/90219132
has comment: http://stackoverflow.com/comment/90219026
tagged with: python
has comment: http://stackoverflow.com/comment/90222437
upvote count: 11
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90219181
possible better answer: http://stackoverflow.com/a/63524041
has answer: http://stackoverflow.com/a/63524041
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90222482
linked to: http://stackoverflow.com/q/12335358
has answer: http://stackoverflow.com/a/51629429
has title: Why is there a semicolon ; after matplotlibs plot() function?
tagged with: matplotlib
score: 10
has comment: http://stackoverflow.com/comment/90220161

http://stackoverflow.com/a/51524670
upvote count: 3
type: Answer
has body: If you're setting the value of a variable in an if block and you try to use it later, make sure that it's declared before the block so that if the if doesn't happen, it still exists. Wrong: if False: x = 3 print(x) # UnboundLocalError Right: x = 0 if False: x = 3 print(x) # 0
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51524628

http://stackoverflow.com/a/51526419
has body: As noted in this question the list-comprehension uses list.append under the hood, so it will call the list-resize method, which overallocates. To demonstrate this to yourself, you can actually use the dis dissasembler: &gt;&gt;&gt; code = compile('[x for x in iterable]', '', 'eval') &gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(code) 1 0 LOAD_CONST 0 (&lt;code object &lt;listcomp&gt; at 0x10560b810, file "", line 1&gt;) 2 LOAD_CONST 1 ('&lt;listcomp&gt;') 4 MAKE_FUNCTION 0 6 LOAD_NAME 0 (iterable) 8 GET_ITER 10 CALL_FUNCTION 1 12 RETURN_VALUE Disassembly of &lt;code object &lt;listcomp&gt; at 0x10560b810, file "", line 1&gt;: 1 0 BUILD_LIST 0 2 LOAD_FAST 0 (.0) &gt;&gt; 4 FOR_ITER 8 (to 14) 6 STORE_FAST 1 (x) 8 LOAD_FAST 1 (x) 10 LIST_APPEND 2 12 JUMP_ABSOLUTE 4 &gt;&gt; 14 RETURN_VALUE &gt;&gt;&gt; Notice the LIST_APPEND opcode in the disassembly of the &lt;listcomp&gt; code object. From the docs: LIST_APPEND(i) Calls list.append(TOS[-i], TOS). Used to implement list comprehensions. Now, for the list-repetition operation, we have a hint about what is going on if we consider: &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.getsizeof([]) 64 &gt;&gt;&gt; 8*10 80 &gt;&gt;&gt; 64 + 80 144 &gt;&gt;&gt; sys.getsizeof([None]*10) 144 So, it seems to be able to exactly allocate the size. Looking at the source code, we see this is exactly what happens: static PyObject * list_repeat(PyListObject *a, Py_ssize_t n) { Py_ssize_t i, j; Py_ssize_t size; PyListObject *np; PyObject **p, **items; PyObject *elem; if (n &lt; 0) n = 0; if (n &gt; 0 &amp;&amp; Py_SIZE(a) &gt; PY_SSIZE_T_MAX / n) return PyErr_NoMemory(); size = Py_SIZE(a) * n; if (size == 0) return PyList_New(0); np = (PyListObject *) PyList_New(size); Namely, here: size = Py_SIZE(a) * n;. The rest of the functions simply fills the array.
has comment: http://stackoverflow.com/comment/90054015
answers question: http://stackoverflow.com/q/51526242
downvote count: 0
has comment: http://stackoverflow.com/comment/90053425
score: 57
upvote count: 57
type: Answer
has comment: http://stackoverflow.com/comment/90053769
has comment: http://stackoverflow.com/comment/90053149

http://stackoverflow.com/q/51503335
tagged with: python
has comment: http://stackoverflow.com/comment/89975459
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89976883
has comment: http://stackoverflow.com/comment/89977229
tagged with: attributeerror
has title: Attribute Error Crazyflie
type: Question
tagged with: crazyflie
has body: I get the error: AttributeError: 'list' object has no attribute 'is_connected' " When I run the code below: import logging # Only output errors from the logging framework logging.basicConfig(level=logging.ERROR) link_uri = 'radio://0/80/250K' class ParamExample: """ Simple logging example class that logs the Stabilizer from a supplied link uri and disconnects after 5s.` """ def __init__(self, link_uri): """ Initialize and run the example with the specified link_uri """ self._cf = Crazyflie(rw_cache='./cache') # Connect some callbacks from the Crazyflie API self._cf.connected.add_callback(self._connected) self._cf.disconnected.add_callback(self._disconnected) self._cf.connection_failed.add_callback(self._connection_failed) self._cf.connection_lost.add_callback(self._connection_lost) print('Connecting to %s' % link_uri) # Try to connect to the Crazyflie self._cf.open_link(link_uri) # Variable used to keep main loop occupied until disconnect self.is_connected = True self._param_check_list = [] self._param_groups = [] random.seed() def _connected(self, link_uri): """ This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.""" print('Connected to %s' % link_uri) # Print the param TOC p_toc = self._cf.param.toc.toc for group in sorted(p_toc.keys()): print('{}'.format(group)) for param in sorted(p_toc[group].keys()): print('\t{}'.format(param)) self._param_check_list.append('{0}.{1}'.format(group, param)) self._param_groups.append('{}'.format(group)) # For every group, register the callback self._cf.param.add_update_callback(group=group, name=None, cb=self._param_callback) # You can also register a callback for a specific group.name combo self._cf.param.add_update_callback(group='cpu', name='flash', cb=self._cpu_flash_callback) print('') def _cpu_flash_callback(self, name, value): """Specific callback for the cpu.flash parameter""" print('The connected Crazyflie has {}kb of flash'.format(value)) def _param_callba…
has comment: http://stackoverflow.com/comment/89980454
score: 0

http://stackoverflow.com/comment/90013943
score: 0
type: Comment
has text: Nothing happend :( FYI if I call `type(df)` just before the `.apply` line, I do get `<class 'pandas.core.frame.DataFrame'>` Edit: Still nothing, after the edit
type: AnswerComment
comment on: http://stackoverflow.com/a/51522497

http://stackoverflow.com/q/51524038
answer count: 3
tagged with: argparse
possible better answer: http://stackoverflow.com/a/51524223
has answer: http://stackoverflow.com/a/51524235
has answer: http://stackoverflow.com/a/51524223
tagged with: python
favorite count: 0
tagged with: python-3.x
has title: Display a subject using argparse
upvote count: 1
has comment: http://stackoverflow.com/comment/90020543
has body: My goal is to ask a question to the user by using argparse(CLI) and then store the input as a string in a similar way as the following: marker = input("Name of marker: ") Location = input("Name of location: ") I am not sure how to do this but here is what I currently have: parser = argparse.ArgumentParser(description = 'Collect Information') parser.add_argument('marker', help = 'Name of marker') parser.add_argument('location', help = 'Name of location') args = parser.parse_args()
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51524224
type: Question
has comment: http://stackoverflow.com/comment/90020481
downvote count: 0
accepted answer: http://stackoverflow.com/a/51524224

http://stackoverflow.com/comment/90235027
comment on: http://stackoverflow.com/q/51635303
type: Comment
type: QuestionComment
has text: The problem with what you are doing is that you are iterating over the elements of items. You should use a variation of for/while with len(items) / range(len(items)) as the one in the link I posted before
score: 1

http://stackoverflow.com/q/51522019
has title: Adding a list as row and column indices to pandas dataframe
tagged with: pandas
favorite count: 0
upvote count: 2
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/51522285
has answer: http://stackoverflow.com/a/51522043
has answer: http://stackoverflow.com/a/51522307
has body: I have a pandas dataframe: 0 1 2 3 4 0 4.8 2.1 0 6.2 0 1 8.5 4.9 0 2.2 0 2 0 5.3 6 9.3 0 and two lists: ind=[ind1,ind2,ind3] and col=[col1,col2,col3,col4,col5] I want to rename the dataframe index and columns such that: col1 col2 col3 col4 col5 ind1 4.8 2.1 0 6.2 0 ind2 8.5 4.9 0 2.2 0 ind3 0 5.3 6 9.3 0 I tried converting the list to a dataframe and append by df.append(col)and df.append(ind). But this did not work (probably because the indices of the df are different from that of the col and ind dataframes) How do I do this?
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51522175
has answer: http://stackoverflow.com/a/51522054
has answer: http://stackoverflow.com/a/51522175
type: Question
accepted answer: http://stackoverflow.com/a/51522307
downvote count: 0
tagged with: dataframe

http://stackoverflow.com/comment/89998312
has text: @HaR Thanks for pointing that out - just updated the example to reflect that
comment on: http://stackoverflow.com/q/51497731
score: 0
type: Comment
type: QuestionComment

python-requests
tags question: http://stackoverflow.com/q/51574243
tags question: http://stackoverflow.com/q/51631812
tags question: http://stackoverflow.com/q/51576163
tags question: http://stackoverflow.com/q/51544197
tags question: http://stackoverflow.com/q/51584343
type: Tag
tags question: http://stackoverflow.com/q/51572376
tags question: http://stackoverflow.com/q/51628229
tags question: http://stackoverflow.com/q/51630571
tags question: http://stackoverflow.com/q/51637310
tags question: http://stackoverflow.com/q/51517668
tags question: http://stackoverflow.com/q/51531372
tags question: http://stackoverflow.com/q/51611011
tags question: http://stackoverflow.com/q/51491246
tags question: http://stackoverflow.com/q/51560515
tags question: http://stackoverflow.com/q/51567716
tags question: http://stackoverflow.com/q/51529060
tags question: http://stackoverflow.com/q/51632003
tags question: http://stackoverflow.com/q/51523618
tags question: http://stackoverflow.com/q/51583779
tags question: http://stackoverflow.com/q/51544389
tags question: http://stackoverflow.com/q/51564391
tags question: http://stackoverflow.com/q/51600489
tags question: http://stackoverflow.com/q/51508554
tags question: http://stackoverflow.com/q/51586059
tags question: http://stackoverflow.com/q/51492267
tags question: http://stackoverflow.com/q/51574998
tags question: http://stackoverflow.com/q/51616803
tags question: http://stackoverflow.com/q/51639531
tags question: http://stackoverflow.com/q/51584393
tags question: http://stackoverflow.com/q/51521396
tags question: http://stackoverflow.com/q/51610256
tags question: http://stackoverflow.com/q/51508087
tags question: http://stackoverflow.com/q/51626170
tags question: http://stackoverflow.com/q/51563503
tags question: http://stackoverflow.com/q/51508549
tags question: http://stackoverflow.com/q/51563186
tags question: http://stackoverflow.com/q/51545528
tags question: http://stackoverflow.com/q/51534651
tags question: http://stackoverflow.com/q/51623481
tags question: http://stackoverflow.com/q/51546898
tags question: http://stackoverflow.com/q/51592560
tags question: http://stackoverflow.com/q/51568075
tag name: python-requests
tags question: http://stackoverflow.com/q/51610330
tags question: http://stackoverflow.com/q/51638850
tags question: http://stackoverflow.com/q/51581667
tags question: http://stackoverflow.com/q/51501579
tags question: http://stackoverflow.com/q/51574210
tags question: http://stackoverflow.com/q/51529991
tags question: http://stackoverflow.com/q/51626372
tags question: http://stackoverflow.com/q/51490285
tags question: http://stackoverflow.com/q/51525237
tags question: http://stackoverflow.com/q/51536421
tags question: http://stackoverflow.com/q/51638468
tags question: http://stackoverflow.com/q/51601129
tags question: http://stackoverflow.com/q/51508866
tags question: http://stackoverflow.com/q/51521658
tags question: http://stackoverflow.com/q/51529081

http://stackoverflow.com/q/51538264
has body: i have two csv files as 1.csv and 2.csv. 1.csv has 50 lines and 2. csv has 75 lines. Now i am trying to write to a new csv file that is 3.csv based on matching username, feature, ipaddress. i tried my code but it is giving the above error. Any help would be appreciated. below is the code that i have tried. df1.to_csv('1.csv') df2.to_csv('2.csv') with open('1.csv') as a: c=pd.read_csv(a) with open('2.csv') as b: d=pd.read_csv(b) if (c['User'] == d['User'] and c['Feature'] == d['Feature'] and c['ipaddress'] == d['ipaddress']): c['User']=c['user'] c['Feature']=c['Feature'] c['ipaddress']=c['ipaddress'] c.to_csv('3.csv')
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90047348
has comment: http://stackoverflow.com/comment/90045389
type: Question
has title: raise ValueError("Can only compare identically-labeled " ValueError: Can only compare identically-labeled Series objects
has comment: http://stackoverflow.com/comment/90045784
has comment: http://stackoverflow.com/comment/90049218
has comment: http://stackoverflow.com/comment/90045771
has comment: http://stackoverflow.com/comment/90047928
has comment: http://stackoverflow.com/comment/90052619
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/90047983

http://stackoverflow.com/q/51528213
tagged with: string
type: UnansweredQuestion
tagged with: python
tagged with: hex
has answer: http://stackoverflow.com/a/51528260
type: Question
has body: I am trying to decode the hex values inside my string so at the end I have one "readable" string. For example: encoded_string = 'videoplayback%253Fexpire%253D1532566750%2526mime%253Dvideo%25252Fmp4%2526key%253Dyt6%2526mt%253D1532544983%2526fvip%253D5%2526i' Each hex value is indicated by a %-symbol and the length of the value can differentiate. What I tried is to decode the string manually: encoded_string = encoded_string.replace('%253A', '\x25\x3A') encoded_string = encoded_string.replace('%252F', '\x25\x2F') encoded_string = encoded_string.replace('%253F', '\x25\x3F') encoded_string = encoded_string.replace('%253D1532566750', '\x25\x3D\x15\x32\x56\x67\x50') Now I need help with a function that is able to find the hex values and decode them. Thank you guys!
has answer: http://stackoverflow.com/a/51528331
has title: How to decode hex values from a string in python
tagged with: decode
score: 0
answer count: 2

http://stackoverflow.com/comment/89948007
has text: Array and list have very specific meanings in Python, and I'm not sure if you're using them correctly throughout.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51489236
type: Comment

http://stackoverflow.com/comment/90221969
type: QuestionComment
comment on: http://stackoverflow.com/q/51628776
has text: You should see the Python server's log for the traceback.
score: 0
type: Comment

http://stackoverflow.com/q/51482697
favorite count: 0
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
downvote count: 0
has title: How to get user agent information in Selenium WebDriver with Python
tagged with: selenium
tagged with: web-scraping
has answer: http://stackoverflow.com/a/51483414
has comment: http://stackoverflow.com/comment/89934286
accepted answer: http://stackoverflow.com/a/51483414
type: AnsweredQuestion
score: 26
type: Question
answer count: 1
has body: I am trying to get the actual user agent that I am using in Selenium, at the moment with the chromedriver. I found a Java version of this problem: How to get userAgent information in Selenium Web driver. Does someone know how to do that in Python?
linked to: http://stackoverflow.com/q/43229299
upvote count: 26
tagged with: python

http://stackoverflow.com/a/51583387
answers question: http://stackoverflow.com/q/51583365
type: Answer
accepted answer of: http://stackoverflow.com/q/51583365
score: 4
has body: Use rolling with min and then shift: df['Min'] = df['B'].rolling(n).min().shift(-n) print (df) A B Min 0 42 19 2.0 1 5 49 2.0 2 46 2 17.0 3 8 24 17.0 4 34 17 11.0 5 5 21 4.0 6 47 42 1.0 7 10 11 NaN 8 36 4 NaN 9 43 1 NaN If performance is important use this solution: def rolling_window(a, window): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) arr = rolling_window(df['B'].values, n).min(axis=1) df['Min'] = np.concatenate([arr[1:], [np.nan] * n]) print (df) A B Min 0 42 19 2.0 1 5 49 2.0 2 46 2 17.0 3 8 24 17.0 4 34 17 11.0 5 5 21 4.0 6 47 42 1.0 7 10 11 NaN 8 36 4 NaN 9 43 1 NaN
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51494633
type: Question
has title: Django is searching wrong statics directory
has comment: http://stackoverflow.com/comment/89958691
has comment: http://stackoverflow.com/comment/89958338
has body: When i run django on uwsgi with; uwsgi --http :8081 --module proj1.wsgi It gives below error when i open start page from browser: Not Found: /accounts/login/static/css/style.css But my settings.py is : STATIC_URL = 'static/' STATIC_ROOT = '/home/proj1/static/' STATICFILES_DIRS = ( '/home/proj1/staticorj/static/', ) When i make collectstatic, it copies files to static root without problem. I dont understand why does it look for /accounts/login. It should look in /home/proj1 directory for static dir. So the browser opens the page but without serving static files.
score: 0
answer count: 1
tagged with: django-staticfiles
has comment: http://stackoverflow.com/comment/89957921
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51520854
has comment: http://stackoverflow.com/comment/89957710
tagged with: uwsgi

http://stackoverflow.com/a/51496047
score: 1
answers question: http://stackoverflow.com/q/51495549
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89961872
downvote count: 0
has body: You can create your aa list as such: letters = ['a', 'j', 'd'] #The letters you want here aa = [] for l in letters: aa += [l]*number_of_times_letter_should_be_repeated Your for loop can be refactored like: for i, c in enumerate(lijst): ascii = ord(c) - 97 if ascii &lt; 0 or ascii &gt; 24: # your code only goes to replacing y? otherwise put in 25. continue lijst[i] = aa[(i+ascii)*25%650] the for loop without aa: for i, c in enumerate(lijst): ascii = ord(c) - 97 if ascii &lt; 0 or ascii &gt; 24: # your code only goes to replacing y? otherwise put in 25. continue letters_index = round((i+ascii+1)*25%650)/25 - 0.5) # Do check this because it isn't clear to me if this does what you are actually after. lijst[i] = aa[letters_index]
has comment: http://stackoverflow.com/comment/89960504

http://stackoverflow.com/comment/90093269
type: Comment
type: QuestionComment
has text: Also, we still need to know that the arrays are the same in Python and in Matlab. If they are not the same, we'll just waste time experimenting with the matrix that you have shown. Is the matrix generated with code? If so, show the Matlab and Python code that you use. (Simplify it as much as possible.)
comment on: http://stackoverflow.com/q/51562302
score: 1

http://stackoverflow.com/comment/90648413
type: Comment
has text: @Temu I'm a bit confused.. the second link you sent states that it will install the requirements.txt dependencies while running in the GAE Flex Environment, but that's exactly what this issue is all about, it's no longer doing just that. If I deploy to the flex environment, the requirements are not installed unless enumerated in the setup.py file.
comment on: http://stackoverflow.com/a/51795844
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90035944
comment on: http://stackoverflow.com/q/51534109
score: 0
type: Comment
type: QuestionComment
has text: Also note that using a Bootstrap template doesn't in any way prevent you from using a Django form.

http://stackoverflow.com/q/51578921
score: 2
type: AnsweredQuestion
has title: Retrieving list of secrets from azure keyvault in python
upvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/51598294
downvote count: 0
answer count: 1
has body: I'm trying to retrieve and print a list of secrets from an azure keyvault use the python sdk. The following returns an paged.SecretItemPaged object: from azure.keyvault import KeyVaultClient, KeyVaultAuthentication from azure.common.credentials import ServicePrincipalCredentials az_client_id = '*****' az_secret = '*****' az_tenant = '*****' credentials = None def auth_callback(server, resource, scope): credentials = ServicePrincipalCredentials( client_id=az_client_id, secret=az_secret, tenant=az_tenant, resource="https://vault.azure.net" ) token = credentials.token return token['token_type'], token['access_token'] client = KeyVaultClient(KeyVaultAuthentication(auth_callback)) secrets = client.get_secrets('https://thevault.vault.azure.net/') print('vault secrets:\n{}'.format(secrets)) e.g: vault secrets: &lt;azure.keyvault.models.secret_item_paged.SecretItemPaged object at 0x7fc494c78b38&gt; I'm not sure how to handle this object. The documentation isn't giving me any hints, unless I've just missed something.
favorite count: 0
tagged with: azure
tagged with: azure-sdk
tagged with: python
tagged with: azure-keyvault
has answer: http://stackoverflow.com/a/51598294

http://stackoverflow.com/a/51538007
accepted answer of: http://stackoverflow.com/q/51535925
answers question: http://stackoverflow.com/q/51535925
has body: Just compute the sum within a Lambda layer. For example: from keras.layers import Input, Lambda from keras.models import Model X = 3 y = 2 x = Input(shape=(X, y)) b = Input(shape=(y,)) out = Lambda(lambda a: a[0] + a[1])([x, b]) model = Model(inputs=[x, b], outputs=out)
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/90150718
type: AnswerComment
has text: Can you tell me how to do it with the updated code in the question?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51592462

http://stackoverflow.com/comment/90096476
has text: I have tried running it from my shell and it works. Unfortunately is has to be run inside the docker container
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51564723
score: 0

http://stackoverflow.com/a/51557918
type: Answer
answers question: http://stackoverflow.com/q/51557452
has body: You can use defaultdict for this: from collections import defaultdict class FileOwners: @staticmethod def group_by_owners(files): d = defaultdict(list) for k, v in files.items(): d[v].append(k) return dict(d) files = { 'Input.txt': 'Randy', 'Code.py': 'Stan', 'Output.txt': 'Randy' } print(FileOwners.group_by_owners(files)) # {'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}
score: 0

http://stackoverflow.com/comment/90080167
score: 0
type: AnswerComment
has text: @SwagatamSengupta add stderr=subprocess.PIPE to your Popen
type: Comment
comment on: http://stackoverflow.com/a/51556394

http://stackoverflow.com/comment/90068607
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51550586
has text: Please don't link to images of data and code, instead, construct a Minimal, Complete, and Verifiable example, see: https://stackoverflow.com/help/mcve
score: 0

statsmodels
tags question: http://stackoverflow.com/q/51631021
tags question: http://stackoverflow.com/q/51553355
tags question: http://stackoverflow.com/q/51548666
tags question: http://stackoverflow.com/q/51596661
tags question: http://stackoverflow.com/q/51563742
tags question: http://stackoverflow.com/q/51507423
tags question: http://stackoverflow.com/q/51567645
type: Tag
tags question: http://stackoverflow.com/q/51563711
tags question: http://stackoverflow.com/q/51617781
tag name: statsmodels
tags question: http://stackoverflow.com/q/51585038
tags question: http://stackoverflow.com/q/51565948
tags question: http://stackoverflow.com/q/51544927
tags question: http://stackoverflow.com/q/51619884

http://stackoverflow.com/comment/90126827
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51578561
has text: can you write the formula in a proper way and write it over here so that i can code it out.
score: 0

http://stackoverflow.com/a/51503086
has body: You are opening your file twice, the second time without specifying the encoding: file = open('EVG_text mining.txt', encoding="utf8") document_text = open('EVG_text mining.txt', 'r') You should open the file as follows: frequencies = {} with open('EVG_text mining.txt', encoding="utf8", mode='r') as f: text = f.read().lower() match_pattern = re.findall(r'\b[a-z]{3,15}\b', text) ... The second time you were opening your file, you were not defining what encoding to use which is probably why it errored. The with statement helps perform certain task linked with I/O for a file. You can read more about it here: https://www.pythonforbeginners.com/files/with-statement-in-python You should probably have a look at error handling as well as you were not enclosing the line that was actually causing the error: https://www.pythonforbeginners.com/error-handling/ The code ignoring all decoding issues: import re import string # Do you need this? with open('EVG_text mining.txt', mode='rb') as f: # The 'b' in mode changes the open() function to read out bytes. bytes = f.read() text = bytes.decode('utf-8', 'ignore') # Change 'ignore' to 'replace' to insert a '?' whenever it finds an unknown byte. match_pattern = re.findall(r'\b[a-z]{3,15}\b', text) frequencies = {} for word in match_pattern: # Your error handling wasn't doing anything here as the error didn't occur here but when reading the file. count = frequencies.setdefault(word, 0) frequencies[word] = count + 1 for word, freq in frequencies.items(): print (word, freq)
has comment: http://stackoverflow.com/comment/89981799
has comment: http://stackoverflow.com/comment/89979599
downvote count: 0
has comment: http://stackoverflow.com/comment/89983308
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/89979704
answers question: http://stackoverflow.com/q/51502634
score: 2
has comment: http://stackoverflow.com/comment/89975980

http://stackoverflow.com/comment/90020026
has text: I couldn't post the output (because I don't have 10 reps), the 'hue' bar on the right side of the graph only labels 0,1,3,4 and skips label 2. But all the points are graphed regardless of their labels.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51525284

http://stackoverflow.com/comment/90150343
type: Comment
comment on: http://stackoverflow.com/q/51592114
type: QuestionComment
score: 0
has text: @Andersson it works for me. Thanks

http://stackoverflow.com/q/51612321
tagged with: irfanview
has answer: http://stackoverflow.com/a/51632614
tagged with: python
tagged with: command-line
type: Question
has title: IrfanView: Command Line Batch Conversion
score: 0
answer count: 1
has body: A) I'd like to Batch convert from *.TIF Format Packbit Conversion to LZW Conversion, overwrite the original file BUT maintain the original folder structure automatically. This can easily be done in the Batch GUI of Irfanview (I did that already, ask me how If you'd like to do the same, sth similar) B) I want to do the same as A) but only pick Pictures with the same file ending (*xyz.tif) and also maintain the folder structure! I think this bit can be prepared with python os.walk maybe?!
type: UnansweredQuestion

http://stackoverflow.com/a/51494378
answers question: http://stackoverflow.com/q/51494257
type: Answer
has comment: http://stackoverflow.com/comment/90592717
has body: You have to cast 'today' to date, otherwise it is just a string literal. Ie use ... trunc((cast('today' as date) - pac.BIRTH_DATE)/365.25) as AGE ... You might also want to use CURRENT_DATE instead, see Context variables topic of the Firebird manual. It seems you want to calculate age in "full years" so you could use DATEDIFF function for that: DATEDIFF(YEAR from CURRENT_DATE to pac.BIRTH_DATE)
score: 0

http://stackoverflow.com/comment/90106500
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/51570135
type: Comment
has text: Glad you found an answer. But now imagine just having your question and your answer without further context. Would it mean anything to you? We don't have your data file, so we have no clue, what your input is, what your expected output is, what exactly you are doing with this one-liner. Please read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) for future reference.

http://stackoverflow.com/comment/90062657
type: QuestionComment
comment on: http://stackoverflow.com/q/51546356
has text: This might well be a bug, possibly related https://github.com/matplotlib/matplotlib/issues/11746.
score: 0
type: Comment

http://stackoverflow.com/a/56515233
score: 0
has body: Using map in base Python, you could do dat['values'] = pd.Series(map(lambda x, y : x[y:], dat['values'], dat['size'])) which returns dat Out[34]: values size 0 [3, 4, 5, 6, 7] 2 1 [4] 3 2 [4, 3] 5
type: Answer
answers question: http://stackoverflow.com/q/51496684

http://stackoverflow.com/comment/89985311
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51508104
has text: Don't create a bunch of variables, put your objects in a container like a list or dict

http://stackoverflow.com/comment/89986308
comment on: http://stackoverflow.com/q/51508589
score: 0
type: QuestionComment
type: Comment
has text: I add the models.py and you are right, the List wants an User instance but Mock() shouldn't fakes one? I tried MagicMock(spec=User) and things like that but at not avail (sorry I'm newby, so I'm not sure what I'm doing). I want to test even an authenticated user. How can I make my mock pass the isinstance() test?

http://stackoverflow.com/q/51488270
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51488394
type: Question
has body: I have a Dataframe like so, lets say x: enter image description here And there is another dataframe with descriptions for the labelNames like so, lets say y: enter image description here Now, How do I replace the LabelNames in the x with the description in the y? Know that LabelNames in x is not unique
tagged with: dataframe
tagged with: image
has comment: http://stackoverflow.com/comment/89945615
answer count: 1
score: 0
tagged with: pandas
tagged with: python
has title: Replacing pandas column value with values from another column

http://stackoverflow.com/a/51526157
answers question: http://stackoverflow.com/q/51526027
score: 0
type: Answer
has body: Marcus has your answer, but optionally, if we're using Python 3.6+, we can use a format template string. print(f'working_loop {i}') Or, you can use the more backward compatible format method as well print('Working_loop {}'.format(i)) # or... print('Working_loop {index}'.format(index=i))

http://stackoverflow.com/q/51615325
has answer: http://stackoverflow.com/a/51616207
score: 4
type: Question
has comment: http://stackoverflow.com/comment/90196792
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/90196709
favorite count: 0
has body: Can the python itertools combinations library by used on objects rather than lists? For instance, how may I use it on the following data? Rahul - 20,000 - Mumbai Shivani - 30,000 - Mumbai Akash - 40,000 - Bangalore I want all the possible combinations on the names and the combined salary value. How can I do this with combinations? Assuming the data is read using pd.read_csv and is stored. Code so far - import pandas as pd import itertools df = pd.read_csv('stack.csv') print (df) for L in range(0, len(df)+1): for subset in itertools.combinations(df['Name'], L): print (subset) Output Name Salary City 0 Rahul 20000 Mumbai 1 Shivani 30000 Mumbai 2 Akash 40000 Bangalore () ('Rahul',) ('Shivani',) ('Akash',) ('Rahul', 'Shivani') ('Rahul', 'Akash') ('Shivani', 'Akash') ('Rahul', 'Shivani', 'Akash') Process finished with exit code 0 How do I add salary to these combinations?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90196870
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/90196084
has answer: http://stackoverflow.com/a/51615931
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90196620
downvote count: 2
has comment: http://stackoverflow.com/comment/90196145
tagged with: combinations
tagged with: python-itertools
has answer: http://stackoverflow.com/a/51615909
has title: Python itertools combinations on objects

http://stackoverflow.com/comment/90101648
score: 1
type: AnswerComment
has text: My if.. sentences looks stupid, you can rewrite them
comment on: http://stackoverflow.com/a/51567599
type: Comment

http://stackoverflow.com/q/51629256
favorite count: 0
has comment: http://stackoverflow.com/comment/90223865
tagged with: visualization
has title: Anyone cannot plot using seaborn's relplot()?
tagged with: python
upvote count: 0
tagged with: seaborn
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90222781
has comment: http://stackoverflow.com/comment/90225518
type: Question
score: -1
downvote count: 1
has body: Hi all, I have updated the latest seaborn version, however, when I typed into the relplot() function to plot the scatterpoint, it was shown as no attribute. Any clue?
has answer: http://stackoverflow.com/a/51973208
answer count: 1

http://stackoverflow.com/a/52655550
answers question: http://stackoverflow.com/q/51578425
score: 30
has comment: http://stackoverflow.com/comment/102376378
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51578425
has comment: http://stackoverflow.com/comment/101835284
upvote count: 30
has body: It's a bug since November 2017. I had the same error and that's what helped: Make changes to mysql_config file in mysqlclient-python or mysql-connector-c or libmysqlclient (depending on what you are using) Change # on macOS, on or about line 112: # Create options libs="-L$pkglibdir" libs="$libs -l " to: # Create options libs="-L$pkglibdir" libs="$libs -lmysqlclient -lssl -lcrypto" Add following to the end of your .bash_profile how to do that: export PATH="/usr/local/opt/openssl/bin:$PATH" export LDFLAGS="-L/usr/local/opt/openssl/lib" export CPPFLAGS="-I/usr/local/opt/openssl/include" Run pip install mysqlclient, that should work now. For more info check this link, look at the "Note about bug of MySQL Connector/C on macOS" section.
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/97616503

http://stackoverflow.com/comment/90080890
score: 1
comment on: http://stackoverflow.com/a/51556918
type: AnswerComment
has text: This assumes the values in each list are unique. For lists with repeated values, this *ignores* the repetition counts!
type: Comment

http://stackoverflow.com/q/51570985
has comment: http://stackoverflow.com/comment/90107978
has comment: http://stackoverflow.com/comment/90108091
has body: I'm new in Python, and didn't find previous questions that describe the issue I'm asking for. Thank you. 1) My first question is, why the type that I get here is not a real List ? (the [ ] in the output, looks like a list but it's not, as you can see in the line below). 2) How can I convert the values in this 'dict_values' to integers inside a List (to make some calculations later) ? print(list(node_list[j].neighbors.values())) print(type(node_list[j].neighbors.values())) The output is: [10, 20, 20, 5, 10] &lt;class 'dict_values'&gt;
upvote count: 2
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/17431638
tagged with: python
tagged with: dictionary
tagged with: list
tagged with: oop
answer count: 0
duplicate of: http://stackoverflow.com/q/16228248
has comment: http://stackoverflow.com/comment/90107990
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/90108120
tagged with: class
linked to: http://stackoverflow.com/q/7296716
has title: How 'dict_values' can be convert to integers in a list?
has comment: http://stackoverflow.com/comment/90108323
score: 2
duplicate of: http://stackoverflow.com/q/7296716
favorite count: 0

http://stackoverflow.com/comment/90121713
score: 0
comment on: http://stackoverflow.com/q/51577963
type: Comment
type: QuestionComment
has text: Theyre on the DockerHub under confluentinc

http://stackoverflow.com/a/67898394
score: 0
answers question: http://stackoverflow.com/q/51613990
type: Answer
has body: Finally solved it. Because passlib does some transformations on the base64 encoded strings none of the mentioned solutions worked for me. I ended up writing my own node-module wich is tested with passlib 1.7.4 hashes. Thanks @kayluhb for pushing me in the right direction! Feel free to use it: node-passlib

http://stackoverflow.com/a/51623954
has body: Object usually create those problem , one way is to convert the dict or list to str df['Ratings1'] = df.Ratings.astype(str) df=df.drop_duplicates(df.columns.difference(['Ratings'])).drop('Ratings1')
downvote count: 0
has comment: http://stackoverflow.com/comment/126598785
score: 3
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/90216228
answers question: http://stackoverflow.com/q/51623901

http://stackoverflow.com/comment/90108059
has text: @roganjosh agreed, but thats how all those hackathon-challenges work :/
comment on: http://stackoverflow.com/a/51571025
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51557048
type: UnansweredQuestion
upvote count: 1
tagged with: odoo
has body: I want to add a field on odoo module. I'm using odoo v8. add.field.product.form # Name field (whatever) product.template # Parent object # Parent View # Name field and Position (after) # Your new Field My class: from openerp import models, fields class AddFieldProduct(models.Model): # Name class _inherit = "product.template" # Name parent object info = fields.Char('Info') I have this error: AssertionError: Did not expect text in element record content, line 3
score: 1
tagged with: odoo-8
type: Question
has title: add field on module odoo localhost
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51558330
favorite count: 0
tagged with: python

http://stackoverflow.com/a/51601850
has body: This matplotlib documentation page shows some different ways to make custom colormaps, including transparency: https://matplotlib.org/stable/users/explain/colors/index.html In your case, it looks like you want a modified version of the gist_rainbow colormap. You can achieve this by modifying the alpha channel as follows: import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap # get colormap ncolors = 256 color_array = plt.get_cmap('gist_rainbow')(range(ncolors)) # change alpha values color_array[:,-1] = np.linspace(1.0,0.0,ncolors) # create a colormap object map_object = LinearSegmentedColormap.from_list(name='rainbow_alpha',colors=color_array) # register this new colormap with matplotlib plt.colormaps.register(cmap=map_object) # show some example data f,ax = plt.subplots() h = ax.imshow(np.random.rand(100,100),cmap='rainbow_alpha') plt.colorbar(mappable=h) Above code will create a colormap rainbow_alpha that is fully opaque at start and linearly changes transparency to be fully transparent at end. If you want a reverse effect (transparent at start and opaque at end) you can change line 9 like so: color_array[:,-1] = np.linspace(0.0,1.0,ncolors) You can also change transparency of a single value: color_array[0,-1] = 0.0 Note: For matplotlib versions &lt;3.7 colormaps were registered using plt.register_cmap
score: 28
type: Answer
accepted answer of: http://stackoverflow.com/q/51601272
downvote count: 0
has comment: http://stackoverflow.com/comment/129138436
answers question: http://stackoverflow.com/q/51601272
upvote count: 28
has comment: http://stackoverflow.com/comment/90291102
type: AcceptedAnswer

http://stackoverflow.com/q/51498056
accepted answer: http://stackoverflow.com/a/51566036
tagged with: python
linked to: http://stackoverflow.com/q/18499497
type: AnsweredQuestion
tagged with: choregraphe
has body: I need to handle the event when the shutdown process is started(for example with long press the robot's chest button or when the battery is critically low). The problem is that I didn't find a way to handle the shutdown/poweroff event. Do you have any idea how this can be done in some convenient way?
type: Question
tagged with: pepper
has answer: http://stackoverflow.com/a/51566036
score: 0
has title: How can I handle Pepper robot shutdown event?
tagged with: nao-robot
answer count: 1

http://stackoverflow.com/a/51502359
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51502197
has comment: http://stackoverflow.com/comment/89975784
answers question: http://stackoverflow.com/q/51502197
type: Answer
has comment: http://stackoverflow.com/comment/89974731
has comment: http://stackoverflow.com/comment/89974220
has body: If intervals is sorted, you can use np.searchsorted: np.array(intervals)[np.searchsorted(intervals, sample)] # array([ 30., 18., 18., 15., 30., 10., inf, 18., 25., 21.]) searchsorted returns the index of the interval where the element belongs to: np.searchsorted(intervals, sample) # array([7, 4, 4, 3, 7, 1, 8, 4, 6, 5]) The default side='left' returns the smallest index of such interval and the result falls into the left open, right close scenario.
score: 9
upvote count: 9

http://stackoverflow.com/comment/90014292
type: QuestionComment
has text: I'd recommend to create stored procedure which accepts source parameters and returns whole outpuut you need.
score: 0
comment on: http://stackoverflow.com/q/51522716
type: Comment

http://stackoverflow.com/a/51543233
score: 1
answers question: http://stackoverflow.com/q/51508096
upvote count: 1
has body: End up using the Index api together with uuid() lib to generate the desired unique index name like code below. from sqlalchemy import Index add = Table('src_add_lookup', metadata, Column('id', Integer, Sequence('seq_add', schema='can'), primary_key=True) Index('idx_add_{}'.format(uuid.uuid4().hex), add.c.id, unique=True)
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51508096

http://stackoverflow.com/q/51600908
upvote count: 2
tagged with: set
accepted answer: http://stackoverflow.com/a/51601008
has comment: http://stackoverflow.com/comment/90167996
type: Question
has body: How can I delete the last element of a set, or create a new set without last element? Sets do not support indexing. I have a set of integers, and want to remove the largest.
has comment: http://stackoverflow.com/comment/90168060
has comment: http://stackoverflow.com/comment/90168160
has answer: http://stackoverflow.com/a/51601004
has comment: http://stackoverflow.com/comment/90167998
has title: Delete last element of set in python
possible better answer: http://stackoverflow.com/a/51601004
downvote count: 0
has answer: http://stackoverflow.com/a/51600966
favorite count: 0
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51601008
score: 2
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51600967

http://stackoverflow.com/comment/90337278
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51636746
has text: @UnbearableLightness Figured OP was interested in the substring after the date. I guess I was right.

http://stackoverflow.com/q/51605064
has comment: http://stackoverflow.com/comment/90176381
has comment: http://stackoverflow.com/comment/90175978
has comment: http://stackoverflow.com/comment/90178781
linked to: http://stackoverflow.com/q/30871033
tagged with: angular
has comment: http://stackoverflow.com/comment/90175728
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90176337
tagged with: angular2-services
has comment: http://stackoverflow.com/comment/90175664
type: UnansweredQuestion
has title: POST http://127.0.0.1:8000/api/checks 403 (Forbidden)
tagged with: django
tagged with: python
has body: I have an application that uses angular 6 as front framework & Django on backend. When I use get request everything is ok, but whenever I want to use post I face 403 forbidden error. Tried to use headers={'Access-Control-Allow-Origin': '*' on Django but it didn't work any good. Here's my code: Check.service.ts: editCheck(check: Check):Observable<any> { return this.http.post(this.checksUrl, check,httpOptions) } check-edit.component.ts: goBack():void{ this.location.back(); } editCheck(): void { this.checksService.editCheck(this.check) .subscribe(() =>this.goBack()) } editCheck is called at check-edit.component.html: Save View: class GetChecksView(APIView): renderer_classes = [renderers.JSONRenderer] def get(self, request): checks = PingCheck.objects.all() checks = PingCheckSerializer(checks, many=True).data return Response(checks) And here is what the error looks like: polyfills.js:1 POST http://127.0.0.1:8000/api/checks 403 (Forbidden) main.js:1 ERROR e {headers: t, status: 403, statusText: "Forbidden", url: "http://127.0.0.1:8000/api/checks", ok: false, …}
score: 3
answer count: 0
upvote count: 3
type: Question

http://stackoverflow.com/q/51538192
has answer: http://stackoverflow.com/a/51538300
type: Question
has comment: http://stackoverflow.com/comment/90044634
possible better answer: http://stackoverflow.com/a/51538409
has answer: http://stackoverflow.com/a/51538950
tagged with: string
has answer: http://stackoverflow.com/a/71554547
has comment: http://stackoverflow.com/comment/90044765
duplicate of: http://stackoverflow.com/q/12453580
has body: I've seen many questions on getting all the possible substrings (i.e., adjacent sets of characters), but none on generating all possible strings including the combinations of its substrings. For example, let: x = 'abc' I would like the output to be something like: ['abc', 'ab', 'ac', 'bc', 'a', 'b', 'c'] The main point is that we can remove multiple characters that are not adjacent in the original string (as well as the adjacent ones). Here is what I have tried so far: def return_substrings(input_string): length = len(input_string) return [input_string[i:j + 1] for i in range(length) for j in range(i, length)] print(return_substrings('abc')) However, this only removes sets of adjacent strings from the original string, and will not return the element 'ac' from the example above. Another example is if we use the string 'abcde', the output list should contain the elements 'ace', 'bd' etc.
accepted answer: http://stackoverflow.com/a/51538300
favorite count: 0
linked to: http://stackoverflow.com/q/464864
has comment: http://stackoverflow.com/comment/90044788
answer count: 5
has answer: http://stackoverflow.com/a/51538616
tagged with: python
downvote count: 1
duplicate of: http://stackoverflow.com/q/464864
upvote count: 24
has comment: http://stackoverflow.com/comment/90046491
type: AnsweredQuestion
has title: Getting all combinations of a string and its substrings
linked to: http://stackoverflow.com/q/1482308
duplicate of: http://stackoverflow.com/q/75666408
has comment: http://stackoverflow.com/comment/90043979
score: 23
has answer: http://stackoverflow.com/a/51538409

http://stackoverflow.com/comment/90053368
comment on: http://stackoverflow.com/a/51540140
score: 0
type: AnswerComment
has text: Please don't post code in comments, it's impossible to read. In my opinion, this is highly likely *not* to be a bottleneck. But, if it is, then sure the ternary operator may be the way to go, and less readable.
type: Comment

http://stackoverflow.com/q/51508179
tagged with: pyfilesystem
tagged with: python
accepted answer: http://stackoverflow.com/a/51508921
possible better answer: http://stackoverflow.com/a/51508918
type: AnsweredQuestion
has title: How to construct an in-memory virtual file system and then write this structure to disk
has answer: http://stackoverflow.com/a/51508918
tagged with: virtualfilesystem
type: Question
score: 20
has answer: http://stackoverflow.com/a/51508921
tagged with: filesystems
answer count: 2
has body: I'm looking for a way to create a virtual file system in Python for creating directories and files, before writing these directories and files to disk. Using PyFilesystem I can construct a memory filesystem using the following: &gt;&gt;&gt; import fs &gt;&gt;&gt; temp_dir = fs.open_fs('mem://') &gt;&gt;&gt; temp_dir.makedirs('fruit') SubFS(MemoryFS(), '/fruit') &gt;&gt;&gt; temp_dir.makedirs('vegetables') SubFS(MemoryFS(), '/vegetables') &gt;&gt;&gt; with temp_dir.open('fruit/apple.txt', 'w') as apple: apple.write('braeburn') ... 8 &gt;&gt;&gt; temp_dir.tree() ├── fruit │ └── apple.txt └── vegetables Ideally, I want to be able to do something like: temp_dir.write_to_disk('&lt;base path&gt;') To write this structure to disk, where &lt;base path&gt; is the parent directory in which this structure will be created. As far as I can tell, PyFilesystem has no way of achieving this. Is there anything else I could use instead or would I have to implement this myself?
favorite count: 0
tagged with: python-3.x
upvote count: 20
downvote count: 0

http://stackoverflow.com/q/51572176
tagged with: python
favorite count: 0
tagged with: trading
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: if-statement
possible better answer: http://stackoverflow.com/a/51572285
tagged with: dataframe
has answer: http://stackoverflow.com/a/51572509
has answer: http://stackoverflow.com/a/51572285
type: Question
has answer: http://stackoverflow.com/a/51572597
accepted answer: http://stackoverflow.com/a/51572597
has title: Creating an IF statement in Python that looks at previous IF statement output
upvote count: 3
has body: I am having difficulty creating an IF statement that does the following: If C1 = Buy, then Buy If C2 = Sell, then Sell If C1 &amp; C2 = nan, then the current cell = previous cell Please see an example below. I am hoping to create a column like 'C3'. Sample Dataset: index C1 C2 0 Buy nan 1 nan nan 2 nan Sell 3 nan nan 4 Buy nan 5 nan Sell 6 nan Sell 7 nan nan 8 nan nan 9 Buy nan 10 nan Sell Output: index C1 C2 C3 0 Buy nan Buy 1 nan nan Buy 2 nan Sell Sell 3 nan nan Sell 4 Buy nan Buy 5 nan Sell Sell 6 nan Sell Sell 7 nan nan Sell 8 nan nan Sell 9 Buy nan Buy 10 nan Sell Sell
answer count: 3
tagged with: pandas

binary-tree
tag name: binary-tree
type: Tag
tags question: http://stackoverflow.com/q/51530678

http://stackoverflow.com/q/51587175
has body: I wish to check the total "id" appeared( 12 "id" in this case) and then create an empty list to append the "item_task" according to "item_id" in sequence order. Example, 1:play, 2:give, 3:give, 4:check.......12:nice (Completed) Since "item_id" for number 6 is not listed, then I would like to assign an empty list to it. "item_id" ---> 6:[].... I would like it to automatically check which "item_id" does not include inside the json. In this example I give 6 but sometimes 5 or 12 is not inside. Is there a way to do so? Below is my json file. json = [ { "testing" : [ { "example" : { }, "get" : [ { "id" : "0", "item" : [ { "get_id" : "1", "item_task" : "play" } ] }, { "id" : "1", "item" : [ ], } ] }, { "example" : { }, "get" : [ { "id" : "2", "item" : [ ], } ] }, { "example" : { } ] }, "get" : [ { "id" : "3", "item" : [ { "item_id" : "2", "item_task" : "give" } ], } ] }, { "example" : { }, "get" : [ { "id" : "4", "item" : [ { "item_id" : "5", "item_task" : "play" } ], }, { "id" : "5" } ] }, { "example" : { }, "get" : [ { "id" : "6", "item" : [ { "item_id" : "0", "item_task" : "let" }, { "item_id" : "3", "item_task" : "give" }, { "item_id" : "4", "item_task" : "check" }, { "item_id" : "7", "item_task" : "nice" }, { "item_id" : "8", "item_task" : "nice" }, { "item_id" : "9", "item_task" : "do" } ] }, { "id" : "7", }, { "id" : "8", }, { "id" : "9" } ] }, { "example" : { }, "get" : [ { "id" : "10", "item" : [ { "item_id" : "11", "item_task" : "nice" }, { "item_id" : "12", "item_task" : "nice" } ] }, { "id" : "11", }, { "id" : "12" } ] } ] } ] My code to (1) calculate the number of 'id'. (2) Find the difference between 'id' and 'item_id' (3) Add an empty list to whichever 'item_id' not in the json file. count = 0 for test in u[0]['testing']: for value in test["get"]: if "id" in valu: count += 1 value = [] for test in u[0]["testing"]: for value in test["get"]: if 'item' in value: for u in value["item"]: for i in range(count): if str(i) not in u["item_id"]: print(str(i)) However…
has answer: http://stackoverflow.com/a/51607334
accepted answer: http://stackoverflow.com/a/51607334
type: AnsweredQuestion
has title: append a rearrange json.values() and if empty then put it as empty list
has comment: http://stackoverflow.com/comment/90173424
favorite count: 0
type: Question
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90147356
score: 0
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/90052937
score: 0
has text: That is an excellent suggestion that I will likely implement since it's more like what I'm doing when first rendering the form. However, that's not my problem. I start off with Node_1 selected that has ADOM_1 and ADOM_2 associated with it so they are the only two in the ADOM ChoiceField list. If I change the Node ChoiceField to Node_2, the ADOM ChoiceField will be changed via the javascript to have ADOM_3 and ADOM_4 in it. When I POST that back, I'm told 4 is not a valid choice because it only started with 1 and 2.
comment on: http://stackoverflow.com/a/51527831
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51558226
has answer: http://stackoverflow.com/a/51558347
has comment: http://stackoverflow.com/comment/90083325
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51558422
has answer: http://stackoverflow.com/a/51594620
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90083439
has comment: http://stackoverflow.com/comment/90083586
has title: Using Python Lists and arrays
type: Question
has body: After years of working with multidimensional arrays, the Python array concept of 'List' seems quite complex to me (although it is said to be superior). I have long (thousands of lines) 2-dimensional array files with hexadecimal values with the following format (can be with or without line separation): [0xF26,0x70,0x66],[0x1158,0x72,0xA6],[0x1388,0x72,0xB6], [0x15BA,0x4E,0x08],[0x17E9,0x70,0x92],[0x1A1D,0x72,0x94], [0x1C4F,0x72,0xB4],[0x4409,0x4A,0x14], etc. etc. I wish to use the file in Python, extracting and manipulating any random element. I realize that I will have to convert the file into a list, and use the list. The length of the file (number records) is dynamic, the width (elements in each record) is fixed. Which is the most efficient Pythonian way for this? I can change the file format if required (separation chars, etc). New edit: Based on some clues in the few replies I recieved, I managed to make progress, but the question is still there. Here is what I have done, but at the end, I can not make it function like a 2-dim array, as can be seen in the attached code: &gt;&gt;&gt; test1 = open("C:/testdata1.txt", 'r') #This opens automatically as a #list, but with line breaks and no start and end brackets. &gt;&gt;&gt; test2 = test1.read() # Convert to string &gt;&gt;&gt; test2 = test2.replace("\n","") # Remove line breaks &gt;&gt;&gt; test2 = "[" + test2 + "]" # Add brackets &gt;&gt;&gt; print(test2) # The result looks like pure 2-dim list, but does not behave like one: [[0x0,0x42,0x2A],[0x229,0x44,0x7C],[0x452,0x40,0x03],[0xCF9,0x4E,0x08], [0xF26,0x70,0x66],[0x1158,0x72,0xA6],[0x1388,0x72,0xB6],] #This gives an error &gt;&gt;&gt; print(test2[1][2]) Traceback (most recent call last): File "&lt;pyshell#79&gt;", line 1, in &lt;module&gt; print(test2[1][2]) IndexError: string index out of range #But it runs like one-dim array of chars &gt;&gt;&gt; print(test2[8]) 4 &gt;&gt;&gt; # If I copy and paste the above list as a new list, it works nicely! Can better use: …
tagged with: arrays

http://stackoverflow.com/comment/89969160
type: Comment
type: QuestionComment
has text: You can always write a proc and check if the tablenames car is in the system catalog before execution of the command as a way to check it's validity
comment on: http://stackoverflow.com/q/51500345
score: 0

http://stackoverflow.com/q/51593857
upvote count: 4
type: AnsweredQuestion
tagged with: dataframe
type: Question
has title: Create multicolumn Pandas DataFrame from nested dict
answer count: 1
has body: I have a dict that looks like this: {"key1":[0.], "key2":{"a":[0.],"b":[0.],"c":[0.]}, "key3":[0.]} Is there an elegant way to create a Pandas DataFrame with the nested keys a,b,c as subcolumns? All the lists contain float values. +------+-----------+------+ | key1 | key2 | key3 | +------+-----------+------+ | | a | b | c | | +------+---+---+---+------+ | 0 | 0 | 0 | 0 | 0 | +------+---+---+---+------+
score: 4
has answer: http://stackoverflow.com/a/51594176
accepted answer: http://stackoverflow.com/a/51594176
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/90153621
has comment: http://stackoverflow.com/comment/90153483
favorite count: 0
tagged with: python-3.x
downvote count: 0

http://stackoverflow.com/a/51579706
has comment: http://stackoverflow.com/comment/90125114
answers question: http://stackoverflow.com/q/51571609
has comment: http://stackoverflow.com/comment/90126454
accepted answer of: http://stackoverflow.com/q/51571609
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90127205
type: Answer
has body: Traversing the tree and collecting all the tags that are under increasing levels of <h> tags can be done with BeautifulSoup: html = ''' House rule Rule 1 A B Rule 2 Rule 2.1 C Rule 2.2 D ''' from bs4 import BeautifulSoup soup = BeautifulSoup(html,"lxml") counter = 1 all_leafs = [] while True: htag = 'h%d'%counter hgroups = soup.findAll(htag) print(htag,len(hgroups)) counter += 1 if len(hgroups) == 0: break for hgroup in hgroups: for c,descendant in enumerate(hgroup.find_all_next()): name = getattr(descendant, "name", None) if name == 'p': all_leafs.append((hgroup.getText(),descendant.getText())) print(all_leafs) ... h1 1 h2 2 h3 2 h4 0 [('House rule', 'A'), ('House rule', 'B'), ('House rule', 'C'), ('House rule', 'D'), ('Rule 1', 'A'), ('Rule 1', 'B'), ('Rule 1', 'C'), ('Rule 1', 'D'), ('Rule 2', 'C'), ('Rule 2', 'D'), ('Rule 2.1', 'C'), ('Rule 2.1', 'D'), ('Rule 2.2', 'D')]

http://stackoverflow.com/comment/93802596
has text: @johnMoutafis Thanks! We actually did something similar, with minor changes. First of all the passing loop into ClientSession is deprecated since version 2.0, so we don't do that. Also we don't define a global session using 'global' but we put it on the app. Also don't forget you need to close the ClientSession when the app is closed.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51638347
score: 2

http://stackoverflow.com/comment/90191532
has text: That is very weird, since it's specifically mentioned in the documentation. Can you post your entire code?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51613141

etl
tags question: http://stackoverflow.com/q/51638210
tags question: http://stackoverflow.com/q/51632848
type: Tag
tags question: http://stackoverflow.com/q/51587726
tags question: http://stackoverflow.com/q/51549272
tag name: etl

http://stackoverflow.com/a/51625753
downvote count: 0
has body: list(string).reverse() modifies the list in place and returns None So you are are doing: "".join(None) Hence the error.
answers question: http://stackoverflow.com/q/51625723
score: 7
upvote count: 7
type: Answer

http://stackoverflow.com/comment/90014749
type: AnswerComment
has text: Remember python2 will not be maintained any more in 2 years. Every new user should start with python3.
score: 3
type: Comment
comment on: http://stackoverflow.com/a/51522834

http://stackoverflow.com/comment/90016145
type: AnswerComment
has text: I actually haven't used K.function() before, I'll try it in a little bit and come back to you. Really appreciate!
type: Comment
comment on: http://stackoverflow.com/a/51513333
score: 0

http://stackoverflow.com/comment/90003385
score: 0
type: QuestionComment
has text: Use dictionary in a loop.
type: Comment
comment on: http://stackoverflow.com/q/51517517

http://stackoverflow.com/q/51620440
has title: Updating a dictionary with values and predefined keys
has comment: http://stackoverflow.com/comment/90206438
has answer: http://stackoverflow.com/a/51633881
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/90206818
has comment: http://stackoverflow.com/comment/90207063
tagged with: xlrd
possible better answer: http://stackoverflow.com/a/51621144
has answer: http://stackoverflow.com/a/51621144
tagged with: python
accepted answer: http://stackoverflow.com/a/51633881
tagged with: dictionary
type: AnsweredQuestion
tagged with: updates
has body: I want to create a dictionary that has predefined keys, like this: dict = {'state':'', 'county': ''} and read through and get values from a spreadsheet, like this: for row in range(rowNum): for col in range(colNum): and update the values for the keys 'state' (sheet.cell_value(row, 1)) and 'county' (sheet.cell_value(row, 1)) like this: dict[{}] I am confused on how to get the state value with the state key and the county value with the county key. Any suggestions? Desired outcome would look like this: &gt;&gt;&gt;print dict [ {'state':'NC', 'county': 'Nash County'}, {'state':'VA', 'county': 'Albemarle County'}, {'state':'GA', 'county': 'Cook County'},.... ]
type: Question
answer count: 2

http://stackoverflow.com/comment/90217144
comment on: http://stackoverflow.com/q/51626124
has text: I see but is there a way to implement my objective?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90229156
has text: @PatrickHaugh true true.
comment on: http://stackoverflow.com/q/51623839
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89968196
comment on: http://stackoverflow.com/q/51490700
has text: You may want to take a course like this: https://www.codecademy.com/learn/learn-python It's free and all the python is done in a browser, it's a good place to start
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/90208521
comment on: http://stackoverflow.com/q/51621401
score: 0
type: QuestionComment
has text: jrd1's answer is good. About the portability of the way you described using `os.system`, one issue is you don't know whether `pip` refers to the Python 3 or 2 version, and there's no portable way to force either. It's annoying.
type: Comment

http://stackoverflow.com/a/60609376
type: Answer
has body: TLDR For me it worked installing jupyter in the virtual enviroment created by pipenv with the following command: pipenv run pip install jupyter Too Short, Wanna Read! I had the same problem with python 3 versions so I started using pipenv as you show, with a simple Pipfile configuration as follows: source name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] numpy = "*" pandas = "*" matplotlib = "*" [requires] python_version = "3.7" I thought that, as I specified python version to 3.7 in that config file, whenever I wanted to run pipenv run jupyter notebook, the kernel would be running under Python 3.7... But when imported the librares indicated there from the notebook: import numpy as np import pandas as pd import matplotlib.pyplot as plt I got the "non module installed error" ModuleNotFoundError: No module named 'matplotlib' And then in the same notebook, I checked in which version was the kernel running with the following code: import sys print(sys.version) The output showed me that it was running under Python 3.6, so in that vesion I didn't have those modules installed, cause pipenv was intalling them for 3.7 version. So I tried installing again jupyter but this time under the virtual enviroment created by pipenv, using the run command and pip tool: pipenv run pip install jupyter It worked for me!
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51563702
downvote count: 0

http://stackoverflow.com/a/51503980
downvote count: 0
score: 3
has body: As Ben Jones has pointed out in the comments Removing elements from a list while iterating over that list always causes problems. So instead of removing elements from the list a, append the result directly to the list date date=[] for i in range(df['Text']): a=re.findall(r'[\d]{1,2}[/\.][\d]{1,2}[/\.][\d]{4}', df['Text'][i]) for k in a: print(k +"prems") if k[-4:].isdigit()==True and int(k[-4:])&gt;2003: print(k) date.append(k)
upvote count: 3
answers question: http://stackoverflow.com/q/51503770
has comment: http://stackoverflow.com/comment/89977104
has comment: http://stackoverflow.com/comment/89977744
type: Answer

http://stackoverflow.com/q/51524430
tagged with: lambda
has body: I have a lambda function that I'd like to add to and make a little more robust. However, I also want to follow PEP 8 and keep my line under 79 characters, correct indention, etc. but am having trouble thinking of how to split up the line. The line is currently: styled_df = df.style.apply(lambda x: ["background: rgba(255,0,0,.3)" if('BBC' in x['newsSource'] or 'Wall' in x['newsSource']) and idx==0 else "" for idx, v in enumerate(x)], axis = 1) So far, I can get to this: styled_df = df.style.apply( lambda x: ["background: rgba(255,0,0,.3)" if('BBC' in x['newsSource'] or 'Wall' in x['newsSource']) and idx == 0 else "" for idx, v in enumerate(x)], axis=1) but the third line (if('BBC' in ...) clashes with PEP 8 (E128). Also, admittedly, this isn't the clearest code the way I broke it up. Also, I'm planning on adding more conditions to this, and am wondering what's the best way to do so. Just keep adding in, and breaking the lines up as best I can? Or is there a 'best practice' for such an issue? Edit: As I thought, but forgot to mention, I likely could change this lambda in to a function, but am struggling with how. I'm new to lambdas and got this one from another problem altogether...So yes, agreed the Lambda is the root issue.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51525685
score: 7
accepted answer: http://stackoverflow.com/a/51524727
upvote count: 7
type: Question
possible better answer: http://stackoverflow.com/a/51525685
has comment: http://stackoverflow.com/comment/90017981
has comment: http://stackoverflow.com/comment/90017702
has comment: http://stackoverflow.com/comment/90018053
has comment: http://stackoverflow.com/comment/90018202
answer count: 2
tagged with: pep8
has comment: http://stackoverflow.com/comment/90018027
downvote count: 0
has title: How to break up lambda function in to its own function? (Lambda is currently 125+ characters)
has answer: http://stackoverflow.com/a/51524727
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90018134
linked to: http://stackoverflow.com/q/1428872
has comment: http://stackoverflow.com/comment/90017720
tagged with: python
has comment: http://stackoverflow.com/comment/90017948
linked to: http://stackoverflow.com/q/51521626

http://stackoverflow.com/a/51510561
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51510533
has body: You can use .loc In [324]: df = pd.DataFrame(columns=list('ABCDEF')) In [325]: l1 = [0.25, 1, [97, 99], array([18., 16., 17.]), array([ 31., 30., 29.]), array([ 0.])] In [326]: df.loc[len(df.index)] = l1 In [327]: df Out[327]: A B C D E F 0 0.25 1 [97, 99] [18.0, 16.0, 17.0] [31.0, 30.0, 29.0] [0.0] However, if you have list of lists upfront, you can pd.DataFrame([l1, l2, ..., ln], columns=list('abcdef'))
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89989825
accepted answer of: http://stackoverflow.com/q/51510533
type: Answer

http://stackoverflow.com/q/51544271
tagged with: keras
favorite count: 0
type: Question
tagged with: python
score: -1
has title: Error when checking target: expected lambda_1 to have 1 dimensions, but got array with shape (60000, 10)
tagged with: tensor
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51544728
tagged with: tensorflow
type: UnansweredQuestion
has body: i am trying to create a invertible networks, when it goes backward , the weight matrix is the transpose of the weight matrix in forward process. so i define a custom layer class Backwardlayer(Dense): def __init__(self,output_dim,b_layer,activation=None,use_bias=True,kernel_initializer='glorot_uniform',bias_initializer='zeros',kernel_regularizer=None,bias_regularizer=None,activity_regularizer=None,kernel_constraint=None,bias_constraint=None,**kwargs): self.output_dim = output_dim self.b_layer = b_layer super(Backwardlayer, self).__init__(output_dim,**kwargs) def build(self, input_shape): assert len(input_shape) &gt;= 2 input_dim = input_shape[-1] self.kernel = K.transpose(self.b_layer.kernel) if self.use_bias: self.bias = self.add_weight(shape=(self.output_dim,),initializer=self.bias_initializer, name='bias', regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None self.built = True def direction_cosine(x): return K.sqrt(K.sum(x, axis=-1, keepdims=None)) def abs(x): return K.abs(x) input_img = Input(shape=(784,)) layer_1 = Dense(512, activation=abs) layer_2 = Dense(512, activation=abs) layer_3 = Dense(256, activation=abs) layer_4 = Dense(128, activation=abs) layer_5 = Dense(10, activation=abs) encoder_layer_1 = layer_1(input_img) encoder_layer_2 = layer_2(encoder_layer_1) encoder_layer_3 = layer_3(encoder_layer_2) encoder_layer_4 = layer_4(encoder_layer_3) encoder_layer_5 = layer_5(encoder_layer_4) decoder_layer_1 = Backwardlayer(128,b_layer=encoder_layer_5,activation=abs,name='dl1')(encoder_layer_5) decoder_layer_2 = Backwardlayer(256,b_layer=layer_4,activation=abs,name='dl2')(decoder_layer_1) decoder_layer_3 = Backwardlayer(512,b_layer=layer_3,activation=abs,name='dl3')(decoder_layer_2) decoder_layer_4 = Backwardlayer(512,b_layer=layer_2,activation=abs,name='dl4')(decoder_layer_3) reconstructed_img = Backwardlayer(784,b_layer=layer_1,activation=abs,name='dl5') rms = RMSprop() (x_train,y_train), (x_test,y_test) = mnist.load_data() x…
upvote count: 0

http://stackoverflow.com/comment/90175139
score: 0
type: Comment
has text: pd.__version__ "0.23.3"
comment on: http://stackoverflow.com/a/51604717
type: AnswerComment

http://stackoverflow.com/comment/90189019
comment on: http://stackoverflow.com/a/51612107
type: Comment
has text: I am using spark 2.0.2
score: 0
type: AnswerComment

http://stackoverflow.com/q/51522993
has body: I am trying to clean up the x-axis of a vbar created by the below code, but am running into issues. The graph shows account balances by quarter dating back to the early 90s, which shows a lot of clutter by quarter. I've seen date_time referenced in this question: Datetime on an X Axis in Bokeh but I don't believe that it is directly applicable to what i'm trying to accomplish. I simply want to decrease the number of quarterly labels so that the axis is cleaner and more presentable. Currently, they are stored as strings, which I believe to be problem #1. Is there an easy way to do this in Bokeh? def create_plot(top_level_data, source): #Builds initial plot with styles #Returns Graph obj #Create figure plot = figure(x_range = sorted(set(top_level_data['QTR'])), title="Account Balance", tools=["save, wheel_zoom,box_zoom,reset, pan"], background_fill_color = "white", plot_width=1000, plot_height=800) #main title formatting plot.title.align = "center" plot.title.text_color = "midnightblue" plot.title.text_font_size = '18pt' #axis title formatting plot.yaxis.axis_label = "Millions" plot.xaxis.axis_label = "Quarters" plot.xaxis.axis_label_text_color = "midnightblue" plot.yaxis.axis_label_text_color = "midnightblue" plot.xaxis.axis_label_text_font_size = "14pt" plot.yaxis.axis_label_text_font_size = "14pt" plot.y_range.start = 0 plot.xaxis.major_label_orientation = "vertical" plot.xgrid.grid_line_color = None #formating of VBar plot.vbar(x = "x", top ="top", source=source, width = 1, fill_color="#036564", line_color="#033649") return plot
linked to: http://stackoverflow.com/q/49172201
tagged with: python
answer count: 0
score: 0
tagged with: bokeh
type: Question
has comment: http://stackoverflow.com/comment/90015581
tagged with: numpy
has comment: http://stackoverflow.com/comment/90015518
linked to: http://stackoverflow.com/q/48691083
has title: Quarterly Axis in Bokeh
type: UnansweredQuestion

http://stackoverflow.com/comment/90197483
comment on: http://stackoverflow.com/q/51615903
type: Comment
type: QuestionComment
has text: If you want sub-linear runtime (although technically it will still be linear) the only way I see is to just look at each `x/2`th element and only if those are the same inspect the ones in between. Whether that's worth the effort probably depends on your `x`.
score: 0

http://stackoverflow.com/comment/90230823
type: QuestionComment
score: 2
has text: The `list` is never passed, since the context should be a *dictionary* that maps *names* to items. So here Django would never know that there is a variable with the name `list`.
comment on: http://stackoverflow.com/q/51633309
type: Comment

http://stackoverflow.com/q/51496713
has body: Here is my problem: I'd like to select k individuals out of n, so that the distances between the selected individuals is maximized, and their average values for a given variable is maximized too. Ideally, I'd like to get a set of solutions corresponding to the 'pareto front'. Computing a weighted-index could be an option, but I am not sure how to properly scale the two objective values. Below is an example of the data I have, using R. ## create a n*m matrix, with samples as rows, variables as columns ## possible values are 0 and 1 n = 100 m = 300 set.seed(1L) rows = lapply(1:n, function(x){ p = runif(1) sample(0:1, m, replace = TRUE, prob = c(p, 1 - p)) }) ## matrix samples*variables mat = do.call(rbind, rows) ## Compute a distance matrix D = as.matrix(dist(mat)) ## Create random values 'S' S = rnorm(n) ## idx = sample of individuals idx = sample(1:n, 20) ## objective: # select nsel among n maximizing S and maximizing D # i.e. find the optimal subset idx that maximizes mean(S[idx]) and mean(D[idx, idx]) I had a look at different R packages like mco, or kofnGA. It doesn't look appropriate, but I may have missed something. Solutions in Python are welcome too. Thanks.
tagged with: mathematical-optimization
has comment: http://stackoverflow.com/comment/89968997
has title: Multi-objective fixed-size subset optimization
type: Question
tagged with: http://stackoverflow.com/tag/r
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89979183

http://stackoverflow.com/q/51600405
type: Question
has title: peewee.InterfaceError: Error binding parameter while saving big amout of data
score: 1
tagged with: database
tagged with: peewee
upvote count: 1
answer count: 1
has body: I create many records in my DB as follows: Subproducts.create(mf_id=mf_id, co=co, mf_binary=mf_binary_data.getbuffer()) mf_binary type is io.BytesIO() - it is binary representation of binary files collected into zipfile I've successfully created many records using this approach, however I have an issue with one particular dataset. It is a bigger than other and it takes ~1,2GB. When I try to save it in DB following error occurs. peewee.InterfaceError: Error binding parameter 2 - probably unsupported type. Field of mf_binary in my model is peewee.BlobField(default=b'0') How can I store this kind of data in peewee Database?
favorite count: 0
tagged with: python
tagged with: http://stackoverflow.com/tag/zip
downvote count: 0
has answer: http://stackoverflow.com/a/51601055
type: UnansweredQuestion
tagged with: orm

http://stackoverflow.com/comment/90192159
comment on: http://stackoverflow.com/q/51613370
has text: Why should the code output such stuff? What have you tried to debug your problem?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90225927
type: Comment
comment on: http://stackoverflow.com/a/51630086
type: AnswerComment
score: 0
has text: Thanks @nikos It really worked. btw what does the "_" represent ?

http://stackoverflow.com/comment/90226496
type: QuestionComment
comment on: http://stackoverflow.com/q/51630229
has text: yes, After I have changed sys.argv[1] to sys.argv[0], I have a different error like `botocore.vendored.requests.exceptions.ConnectionError: HTTPSConnectionPool(host='ec2.latest-ami.py.amazonaws.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 503 Service Unavailable',)))`
score: 0
type: Comment

http://stackoverflow.com/comment/89956018
has text: hey I am sorry for coming back. but the output I am getting is not purely chinese and subway. See the very first entry you get in the output.
comment on: http://stackoverflow.com/a/51493182
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51554599
type: Answer
answers question: http://stackoverflow.com/q/51554418
has body: you could always iterate over the dataframe and apply the conditionals. It's probably not the best solution but this should work: list1 = [] list2 = [] list3 = [] for i in range(df.shape[0]): if df['number'][i] &lt; 15: list1.append['name'] if df['number'][i] &gt;= 15 &amp; df['number'][i] &lt; 40: list2.append['name'] if df['number'][i] &gt; 15: list3.append['name'] hope this helps
score: 0

http://stackoverflow.com/q/51630427
answer count: 0
has body: I am doing some analysis on images (original image format is geotiff - .tif and did some calculations on the images and able to output the calculated pixels into csv without issue. However due to matplotlib limitations of using only inches for figure width and height, i am not able to output the new calculated image into a plot. Original map size is about 7.7k pixels by 7.7k pixels and the output image is of 3.3k by 3.3k without color bar. Below is the code i used to generate the plots import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt figure_width_inches = 40 figure_height_inches = 20 img_min = np.nanmin(img) img_max = np.nanmax(img) mid = 0 img_fig = plt.figure(figsize=(figure_width_inches, figure_height_inches)) img_ax = img_fig.add_subplot(add_subplot_RPC) cmap = plt.cm.RdYlGn img_cax = plt.imshow(img, cmap=cmap, clim=(img_min, img_max)) plt.axis(axis_mode) img_fig.savefig(img_filename.replace('.jpg', '_notitlenolegend.jpg'), dpi=figure_dpi, bbox_inches=figure_bbox_inches, pad_inches=plot_pad_inches) ax.set_title(img_title, fontsize=axis_title_fontsize, fontweight=axis_title_fontweight) cbar = img_fig.colorbar(cax, orientation=figure_colourbar_orientation, shrink=figure_colourbar_shrink) img_fig.savefig(img_filename, dpi=figure_dpi, bbox_inches=figure_bbox_inches, pad_inches=plot_pad_inches) I need the image output to be of similar size as original image (i.e. 7.7k by 7.7k pixels) for post plot processing. My challenge is that my source file is of geotiff and plt.imread is unable to open the file. I am thinking of converting the tif file to jpg to get plt.imread to open the file but i could not convert it. source = '~/some_map.tif' import PIL import PIL.Image, PIL.ImageFile img = PIL.Image.open(source) destination = source.replace('.tif', '_destination.tif') img.save(destination, "JPEG", quality=10, optimize=True, progressive=True) ... IOError: cannot write mode I as JPEG i might need to convert the color space of the single band geotiff fil…
has comment: http://stackoverflow.com/comment/90268127
has comment: http://stackoverflow.com/comment/90291972
has comment: http://stackoverflow.com/comment/90260863
type: Question
tagged with: python-imaging-library
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90253784
score: 0
has comment: http://stackoverflow.com/comment/90225188
has comment: http://stackoverflow.com/comment/90260652
has comment: http://stackoverflow.com/comment/90254007
type: UnansweredQuestion
tagged with: geotiff
tagged with: python
has comment: http://stackoverflow.com/comment/90260916
has comment: http://stackoverflow.com/comment/90228784
linked to: http://stackoverflow.com/q/13714454
has title: Using matplotlib to output file of same image size as source file

http://stackoverflow.com/comment/90177016
has text: I created a file called task.py and moved the task do_work() in this file. Unfortunately it still does not work.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51577966
type: Comment

http://stackoverflow.com/q/51583471
tagged with: python
type: AnsweredQuestion
has title: How to find the minimum value in a Dict{key:List}?
type: Question
has answer: http://stackoverflow.com/a/51583493
accepted answer: http://stackoverflow.com/a/51583493
score: 0
answer count: 2
has body: I am trying to find the minimum flight price in a dictionary that looks like: {datetime.date(2018, 12, 16): ['KL', 'AMS', '59.84'], datetime.date(2018, 12, 24): ['KL', 'AMS', '59.84'], datetime.date(2018, 12, 25): ['KL', 'AMS', '59.84'], datetime.date(2018, 12, 27): ['KL', 'AMS', '59.84'], datetime.date(2018, 12, 18): ['KL', 'AMS', '59.84'], datetime.date(2018, 12, 19): ['KL', 'AMS', '59.84'], datetime.date(2018, 12, 20): ['KL', 'AMS', '59.84'], datetime.date(2018, 12, 23): ['KL', 'AMS', '59.84'], datetime.date(2018, 12, 17): ['AF', 'AMS', '70.24'], datetime.date(2018, 12, 21): ['SK', 'AMS', '97.93'], datetime.date(2018, 12, 26): ['SK', 'AMS', '97.93'], datetime.date(2018, 12, 28): ['SK', 'AMS', '97.93'], datetime.date(2019, 1, 2): ['SK', 'AMS', '97.93'], datetime.date(2019, 1, 3): ['SK', 'AMS', '97.93'], datetime.date(2018, 12, 29): ['AF', 'AMS', '111.64'], datetime.date(2018, 12, 31): ['EW', 'AMS', '127.51'], datetime.date(2019, 1, 1): ['EW', 'AMS', '127.51'], datetime.date(2018, 12, 30): ['EW', 'AMS', '147.51'], datetime.date(2018, 12, 22): ['KL', 'AMS', '148.84']} The first key is a datetime, and value = list of info. I'm trying to simply get the max and min price over that time series. I've tried the following: _tempPairAndPrices = {} for item in permutations(destinations[1:],2): #try: key_max = max(_fltDictTemp_CachedData[item].keys(),key=(lambda k: _fltDictTemp_CachedData[item][k])) key_min = min(_fltDictTemp_CachedData[item].keys(),key=(lambda k: _fltDictTemp_CachedData[item][k])) maxPx = _fltDictTemp_CachedData[item][key_max] minPx = _fltDictTemp_CachedData[item][key_min] _tempPairAndPrices[item] = {'maxPx':maxPx,'minPx':minPx} I don't think it's properly accessing the list of information though, as it's not properly assigning max and min values... (often my min >> max) Thanks!
possible better answer: http://stackoverflow.com/a/51583650
has answer: http://stackoverflow.com/a/51583650

http://stackoverflow.com/q/51522174
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90016627
has body: I'm currently a noob to tkinter as i made this code. so kindly ignore any foolishness if found. import tkinter as tk from tkinter import ttk from tkinter import Menu win=tk.Tk() win.title('Tabs GUI') tab_control=ttk.Notebook(win) tab1=ttk.Frame(tab_control) tab_control.add(tab1,text='Tab 1') tab_control.grid() tab2=ttk.Frame(win) #1 tab_control.add(tab2,text='Tab 2') menuBar = Menu(tab1) #2 win.config(menu=menuBar) # Add menu items fileMenu = Menu(menuBar, tearoff=0) fileMenu.add_command(label="New") fileMenu.add_separator() fileMenu.add_command(label="Exit") menuBar.add_cascade(label="File", menu=fileMenu) # Add another Menu to the Menu Bar and an item helpMenu = Menu(menuBar, tearoff=0) helpMenu.add_command(label="About") menuBar.add_cascade(label="Help", menu=helpMenu) ttk.Label(tab2, text="Choose a number:").grid(column=0, row=0) numberChosen = ttk.Combobox(tab2, width=8) numberChosen['values'] = (1, 2, 4, 42, 100) numberChosen.grid(column=0, row=1) numberChosen.current(0) chVarDis = tk.IntVar() check1 = tk.Checkbutton(tab2, text="Disabled", variable=chVarDis, state='disabled') check1.select() check1.grid(column=0, row=2, sticky=tk.W) chVarUn = tk.IntVar() check2 = tk.Checkbutton(tab2, text="UnChecked", variable=chVarUn) check2.deselect() check2.grid(column=1, row=2, sticky=tk.W ) win.mainloop() now the first problem is that on #1 i gave 'tab2' master window i.e 'win', then added it to the notebook but it acts like i gave it notebook() as a master window because 'tab1' and 'tab2' are functioning same. And the second problem is why 'combobox' is auto-focused when i open 'tab2'. and the same goes for Menu() #2, i've given it parent tab1 yet it is displayed in top level window win
has title: why giving a tab master window and adding it to tk.notebook() result as the tab was given notebook as a master window
score: 1
has comment: http://stackoverflow.com/comment/90016605
type: Question
has comment: http://stackoverflow.com/comment/90016286
downvote count: 0
has comment: http://stackoverflow.com/comment/90019641
has comment: http://stackoverflow.com/comment/90015956
has comment: http://stackoverflow.com/comment/90016739
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90015922

http://stackoverflow.com/q/51626121
has body: I've been working on a house price prediction. After I've used standardscaler and gridsearch, the error turns out to be -66031776763.3788. Below is the code and the dataset. Could anyone tell me what is wrong with my code?
tagged with: svm
has answer: http://stackoverflow.com/a/51635103
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90217160
type: UnansweredQuestion
score: -4
tagged with: machine-learning
tagged with: python
has title: Very small negative mean squared error
type: Question
has comment: http://stackoverflow.com/comment/90234137
downvote count: 4
upvote count: 0
tagged with: grid-search

http://stackoverflow.com/a/51603920
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51603892
answers question: http://stackoverflow.com/q/51603892
score: 3
has body: By using np.where np.where(df['nameID'].isin(['name1','name3']),df1.value1*df1.Value2 ,df1.value1*df1.Value3) Out[182]: array([200, 525, 56, 35], dtype=int64) #df1['result'] = np.where(df['nameID'].isin(['name1','name3']),df1.value1*df1.Value2 ,df1.value1*df1.Value3)
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/q/51626028
answer count: 0
tagged with: pycharm
downvote count: 0
type: UnansweredQuestion
score: 1
has body: I am trying to make a simple Text Summarization GUI that takes an input text and generates the summary. While the program is running absolutely fine, I am getting errors in converting it into exe file. Following are two the main programs for the GUI interface- import tkinter import gensim from tkinter import from gensim.summarization import summarize #create windows object root=Tk() root.geometry("1024x800") #set the window size using .geometry command root.title("AUTOMATED TEXT SUMMARIZER") h1=Label(root,text="AUTOMATED TEXT SUMMARIZER FOR ENGLISH",font= ("arial",12,"bold"),fg="#26482B").pack() #set the label, like 'enter text' l1 = Label(root,text="Enter Some Text", font= ("arial",10,"bold"),fg="#26482B").place(x=10,y=50) #take some text as input in the textbox inp = Text(root,width=100,height=30,bg="white",font=("arial",8,"bold")) inp.place(x=10,y=90) #set another label that indicates the results l2 = Label(root,text="Summary", font= ("arial",10,"bold"),fg="#26482B").place(x=720,y=50) opt = Text(root,width=50,height=20,bg="white",font=("arial",10,"bold")) opt.place(x=640,y=90) def sum(): txt = inp.get("1.0", END) output = summarize(txt, ratio=0.2) opt.insert(0.0, output) button_a = Button(root,text="Generate Summary",width=30,height=2,bg="#9B9D9C",fg="black",font= ("arial",9,"bold"),command=sum) button_a.place(x=120,y=600) def clear(): inp.delete("1.0",END) opt.delete("1.0",END) button_b= Button(root,text="Clear",width=18,height=2,bg="#9B9D9C",fg="black",font= ("arial",9,"bold"),command=clear) button_b.place(x=450,y=600) root.mainloop() This is the setup_file.py- import os import cx_Freeze from cx_Freeze import setup, Executable import sys os.environ['TCL_LIBRARY'] = "C:/LOCAL_TO_PYTHON/PYTHON35-32/tcl/tcl86t.dll" os.environ['TK_LIBRARY'] = "C:/LOCAL_TO_PYTHON/PYTHON35-32/tcl/tk86t.dll" includefiles = ['C:/Users/praty/AppData/Local/Programs/Python/Python36- 32/DLLs/tcl86t.dll','C:/Users/praty/AppData/Local/Programs/Python/Python36- 32/DLLs/tk86t.dll'] includes = …
has title: tkinter for Text Summarization
type: Question
upvote count: 1
tagged with: user-interface
has comment: http://stackoverflow.com/comment/90223671
favorite count: 0
has comment: http://stackoverflow.com/comment/90223657
tagged with: python
tagged with: nlp
tagged with: tkinter

http://stackoverflow.com/comment/90065992
type: AnswerComment
has text: the first local min for id 2 is row 8 (value =1.5), so though row 7 is at least 2 greater than min value of row 8, row 7 comes BEFORE row 8. for id 2 only row 13 and 14 should be true. thank you for your patience, i hope this provides more clarity on what i need.
score: 0
comment on: http://stackoverflow.com/a/51543906
type: Comment

http://stackoverflow.com/comment/90064848
score: 0
comment on: http://stackoverflow.com/q/51547551
type: QuestionComment
type: Comment
has text: Minor note: the name of the library is matplotlib.

http://stackoverflow.com/comment/90171072
score: 0
type: Comment
type: QuestionComment
has text: @holdenweb , thanks for the reply. I provided a link to the screenshot of the url code. It doesn’t seem to be empty
comment on: http://stackoverflow.com/q/51584343

http://stackoverflow.com/comment/90130967
type: QuestionComment
has text: or to https://datascience.stackexchange.com/
score: 0
comment on: http://stackoverflow.com/q/51582726
type: Comment

http://stackoverflow.com/q/51603189
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51603511
type: Question
has body: I'm new to Python and Github API, currently trying to use Pygithub to access the Github enterprise API. The target is to find if a specific member is in the organization. If so, remove it from the Org. I have my current Code below: access_token = "my_ghe_org_token" g = Github(base_url="https://{my_ghe_hostname}/api/v3", login_or_token=access_token) org = g.get_organization('my_org_name') mem_exist = org.has_in_members('myu') if mem_exist: org.remove_from_members('myu') It gives below error: Traceback (most recent call last): File "disable_ghe.py", line 21, in &lt;module&gt; disable_ghe() File "disable_ghe.py", line 9, in disable_ghe mem_exist = org.has_in_members('myu') File "/Users/myu/Desktop/github/venv/lib/python3.6/site-packages/github/Organization.py", line 769, in has_in_members assert isinstance(member, github.NamedUser.NamedUser), member Anyone know where is my error? Or explain a bit if I used the function incorrectly? I'm trying to make this call: http://pygithub.readthedocs.io/en/stable/github_objects/Organization.html#github.Organization.Organization.has_in_members
score: 0
tagged with: github-api
answer count: 1
has answer: http://stackoverflow.com/a/51603511
has title: Python PyGithub usage to get/remove a member in an organization
tagged with: pygithub

http://stackoverflow.com/a/51486672
has comment: http://stackoverflow.com/comment/89944750
score: 0
has comment: http://stackoverflow.com/comment/89942522
has comment: http://stackoverflow.com/comment/89945518
type: Answer
has body: As the MSDN docs explain, MessageBox: Displays a modal dialog box that contains a system icon, a set of buttons, and a brief application-specific message, such as status or error information. The message box returns an integer value that indicates which button the user clicked. A modal dialog box is intended to block your program until it's dealt with. That's what it means: it puts your program into a special "waiting for the user" mode. Plus, it obviously can't return what the user clicked unless it waits until the user clicks something. If you really want to use MessageBox, you could push the rest of your work onto another thread, like this: def background(): time.sleep(3) os.system("TASKKILL /F /IM program.exe") t = threading.Thread(target=background) t.start() time.sleep(3) win32api.MessageBox(0,'hello','text') Alternatively, you could create a modeless dialog, but that requires integrating the rest of your program with a win32api event loop.
accepted answer of: http://stackoverflow.com/q/51486456
answers question: http://stackoverflow.com/q/51486456
has comment: http://stackoverflow.com/comment/89955559
has comment: http://stackoverflow.com/comment/89942553
has comment: http://stackoverflow.com/comment/89942471
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89942696

http://stackoverflow.com/q/51553972
score: -1
downvote count: 1
type: Question
has body: I am newbie to python .Just wondering what kind of data structure should we use to solve this problem What will be the probablity of user1 going from A ->B ,A ->C and user2 going from B->A and B->D user landing destination 1 A B 1 A B 1 A B 1 A C 1 A C 2 B D 2 B A
tagged with: hashmap
upvote count: 0
has answer: http://stackoverflow.com/a/51554380
favorite count: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: Calculating probable hits to page

http://stackoverflow.com/comment/89952475
score: 0
comment on: http://stackoverflow.com/q/51490700
has text: You may also need to see what other packages pip has collected; it is likely that getting your system administrator to approve `pip` or `python` as one of the applications permitted to access to Internet would be the most convenient outcome.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90226462
type: QuestionComment
has text: Yes, Python does not allow overloading for some operators. Also the "and" operator doesn't return a Boolean value, but the last value that was evaluated; see https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
score: 1
comment on: http://stackoverflow.com/q/51620977
type: Comment

http://stackoverflow.com/a/71465795
has body: tried the example but progress bar fails still, and I find this post, seems useful in short way to use: def tqdm_parallel_map(fn, *iterables): """ use tqdm to show progress""" executor = concurrent.futures.ProcessPoolExecutor() futures_list = [] for iterable in iterables: futures_list += [executor.submit(fn, i) for i in iterable] for f in tqdm(concurrent.futures.as_completed(futures_list), total=len(futures_list)): yield f.result() def multi_cpu_dispatcher_process_tqdm(data_list, single_job_fn): """ multi cpu dispatcher """ output = [] for result in tqdm_parallel_map(single_job_fn, data_list): output += result return output
upvote count: 5
answers question: http://stackoverflow.com/q/51601756
downvote count: 0
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/139567549

http://stackoverflow.com/comment/89952461
has text: @BearBrown That makes sense. I think that's all I needed! Thanks!
comment on: http://stackoverflow.com/q/51491923
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51564738
has body: im curious about how the logical operators work in sets. cosider this: x = set('abcde') y = set('bdxyz') # union print(x | y) # output: {'d', 'b', 'y', 'e', 'z', 'x', 'c', 'a'} print(x or y) # output: {'d', 'b', 'e', 'c', 'a'} # intersection print(x and y) # output: {'d', 'b', 'y', 'z', 'x'} print(x &amp; y) # output: {'b', 'd'} i expected the outputs for union and intersection to be the same for each. how is it possible that they are not? can anyone explain?
has comment: http://stackoverflow.com/comment/90096459
has comment: http://stackoverflow.com/comment/90096842
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/51564813
has answer: http://stackoverflow.com/a/51564867
linked to: http://stackoverflow.com/q/3845018
score: 2
has comment: http://stackoverflow.com/comment/90096567
has comment: http://stackoverflow.com/comment/90096675
duplicate of: http://stackoverflow.com/q/3845018
tagged with: set
has comment: http://stackoverflow.com/comment/90096508
has comment: http://stackoverflow.com/comment/90096448
type: Question
upvote count: 4
has title: logical operators in python sets
answer count: 2
has comment: http://stackoverflow.com/comment/90096615
favorite count: 0
linked to: http://stackoverflow.com/q/47007680
tagged with: python
has comment: http://stackoverflow.com/comment/90096457

http://stackoverflow.com/q/51549821
upvote count: 7
type: Question
type: AnsweredQuestion
score: 7
has comment: http://stackoverflow.com/comment/90067396
tagged with: sqlalchemy
has title: SQLAlchemy - How to access column names from ResultProxy and write to CSV headers
has answer: http://stackoverflow.com/a/51549947
has body: I am trying to use SQLAlchemy to establish a connection to a PostgreSQL Database, execute a SQL query and print the output of the file to a file in linux. from sqlalchemy import create_engine import yaml import csv outfile = open('/path/filename.csv', 'wb') outcsv = csv.writer(outfile, delimiter='\t') with open('config.yml') as f: cfg = yaml.safe_load(f) username = cfg['credentials']['username'] password = cfg['credentials']['password'] host = cfg['credentials']['host'] port = cfg['credentials']['port'] dbname = cfg['credentials']['dbname'] engine = create_engine('postgresql://{}:{}@{}:{}/{}'.format(username, password, host, port, dbname)) result = engine.execute("""select * from db.tablename """) # dump column titles (optional) outcsv.writerow(x[0] for x in result.description) # dump rows outcsv.writerows(result.fetchall()) outfile.close() However, I am getting the following error message - Traceback (most recent call last): File "", line 12, in AttributeError: 'ResultProxy' object has no attribute 'description' If I comment the below command, I am successfully able to get the query result but without the headers. outcsv.writerow(x[0] for x in result.description) Upon researching, I found the method - result._metadata.keys can generate the headers. However, it generates in some form of a list that I can't attach as header. Please advise if there is any way to get the file header as well as the data into a csv file. Please consider the fact that I am beginner in Python while answering the above.
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51549947

http://stackoverflow.com/comment/90232152
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51633655
has text: What will happen if first row opt1 value is non zero and second row value of opt1 is zero.? should df contain both the columns?

http://stackoverflow.com/comment/90033002
has text: @no, how can i remove it? in request.data.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51532492
score: 0

http://stackoverflow.com/comment/90147184
has text: Following on from @Mike's observation that means you should loop over the file line by line and use `json.loads` on each line instead of `json.load` for the entire lot.
type: QuestionComment
comment on: http://stackoverflow.com/q/51590965
type: Comment
score: 1

http://stackoverflow.com/a/51500631
has comment: http://stackoverflow.com/comment/89993272
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51499723
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51499723
type: Answer
has comment: http://stackoverflow.com/comment/90008213
upvote count: 1
has body: You want to use DataFrame.combine_first, which will align the DataFrames based on index, and will prioritize values in the left DataFrame, while using values in the right DataFrame to fill missing values. df1.combine_first(df2).combine_first(df3) Sample data import pandas as pd df1 = pd.DataFrame({'A': [1,0], 'B': [2,1]}) df1.index=['Y', 'Z'] df2 = pd.DataFrame({'C': [1,0], 'D': [2,1]}) df2.index=['X', 'Z'] df3 = pd.DataFrame({'C': [0,1], 'E': [1,1]}) df3.index=['Y', 'W'] Code df1.combine_first(df2).combine_first(df3) Output: A B C D E W NaN NaN 1.0 NaN 1.0 X NaN NaN 1.0 2.0 NaN Y 1.0 2.0 0.0 NaN 1.0 Z 0.0 1.0 0.0 1.0 NaN
score: 1

http://stackoverflow.com/q/51613034
favorite count: 0
tagged with: breakpoints
has answer: http://stackoverflow.com/a/51613235
linked to: http://stackoverflow.com/q/37299
tagged with: python
has title: How to halt a Python script - only if it is being debugged
type: UnansweredQuestion
upvote count: 1
has body: A similar question When developing some Windows desktop stuff in Delphi, I had a habit of inserting asm(int 3);. If a debugger is running, that acts like a breakpoint. If no debugger is running, it does nothing (NOOP). I would like to do something similar for my Python scripts. Is there some Python function like HaltDebugger()? Cross platform, of course. [Update] I am looking for something that will work with PyCharm
score: 1
type: Question
tagged with: debugging
answer count: 1
downvote count: 0

correlation
tags question: http://stackoverflow.com/q/51544953
tags question: http://stackoverflow.com/q/51596966
tag name: correlation
type: Tag
tags question: http://stackoverflow.com/q/51569099

http://stackoverflow.com/q/51565499
answer count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/90120565
has answer: http://stackoverflow.com/a/51565638
has comment: http://stackoverflow.com/comment/90097892
downvote count: 2
possible better answer: http://stackoverflow.com/a/51565711
has body: I have a list of lists of lists - essentially [ [[val1, val2...], [val3, val4...]...], [[val5, val6...], [val7, val8...]...], ...] On python, pretty printed, the output looks like: [[['a', 'b', 'c', 'test1', 'd', 'e', 'f', 'g'], ['h', 'i', 'j', 'k', 'l', 'm']], [['n', 'o', 'p', 'test2', 'q', 'r', 's', 't'], ['u', 'v', 'w', 'x', 'y', 'z']]] How can I get test1 and test2 into a list, but as two separate items: [ ['test1'], ['test2'] ] It seems easy, but I am unsure of how to use list comprehension or traversing through a list to get this, because some of the values contain 8 entities, and some contain 6.
tagged with: python
has title: List manipulation in python with 3 lists in a list
has comment: http://stackoverflow.com/comment/90099262
has comment: http://stackoverflow.com/comment/90120585
has answer: http://stackoverflow.com/a/51565586
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90120541
tagged with: list
accepted answer: http://stackoverflow.com/a/51565604
has comment: http://stackoverflow.com/comment/90100509
has comment: http://stackoverflow.com/comment/90100750
type: Question
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/51565604
has answer: http://stackoverflow.com/a/51565711
has comment: http://stackoverflow.com/comment/90120610
has comment: http://stackoverflow.com/comment/90097980
has comment: http://stackoverflow.com/comment/90118102
has comment: http://stackoverflow.com/comment/90120601

http://stackoverflow.com/q/51550617
score: 8
favorite count: 0
has body: I currently use this code: def f(): try: f() except RecursionError: f() try: f() except RecursionError: f() This results in a fatal stack overflow instantly. However, I was wondering if there is an easier way to do this which is much more Pythonic.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90068621
has comment: http://stackoverflow.com/comment/129471015
has comment: http://stackoverflow.com/comment/90068650
has comment: http://stackoverflow.com/comment/90068543
has title: How can I get a stack overflow error in Python?
downvote count: 2
upvote count: 10
type: Question
has comment: http://stackoverflow.com/comment/90068533
has comment: http://stackoverflow.com/comment/90070096
has comment: http://stackoverflow.com/comment/137794232
has answer: http://stackoverflow.com/a/78160605
has answer: http://stackoverflow.com/a/62841333
answer count: 2
has comment: http://stackoverflow.com/comment/90068521
tagged with: stack-overflow

http://stackoverflow.com/q/51500972
tagged with: python
type: AnsweredQuestion
upvote count: 0
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/51503265
accepted answer: http://stackoverflow.com/a/51503265
score: -1
answer count: 1
downvote count: 1
has title: python table app that cycles itself
favorite count: 0
has body: I am kinda new to python programming and i would need some help with a project i am trying to accomplish. So, i managed to scrape some data i needed from a website and store them to csv files. What i want to do now is to project/print them on a table/tables. But, there are some rules : 1) i want the table to be like 25 rows per page (1 data/row) and fill the whole screen. if the data i want to project/print exceed 25 rows, a new page will be created and store the next data and so on and so on. The data i am fetching are not specific every time. Sometimes could be like 10 data = 1 page/table with 10 rows, an other time could be like 70 data = 3 pages/tables (with 25 + 25 + 20 rows). 2) Then i want to cycle through pages/tables automatically Is this even possible to be made with python ? Also, is this possible to be made as an app or it would be easier to be made as a website app though Django for example ? I would love to point me to some direction guys, i am really lost on that matter. I would appreciate to get every help i can get. Thanks in advance

http://stackoverflow.com/comment/90211168
has text: @Triggernometry `get_params` should raise an error if it is not able to retrieve the parameters from the database (i.e. if `params` is still `None` after both queries). `params = query_db(d['b'])` is useful in the example case of `d2`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51622508

http://stackoverflow.com/q/51629358
favorite count: 0
has body: Please, how can i install Tensorflow in a virtual environment? I have used these commands but it doesn't work.. sudo -H pip3 install tensorflow --proxy https://XXX.XX.XX.X:3128 sudo -E pip3 install tensorflow --proxy https://XXX.XX.XX.X:3128 sudo -E pip install tensorflow --proxy https://XXX.XX.XX.X:3128 sudo -H pip install tensorflow --proxy https://XXX.XX.XX.X:3128 sudo pip install tensorflow --proxy https://XXX.XX.XX.X:3128 It resulted in: Downloading/unpacking tensorflow Cannot fetch index base URL https://pypi.python.org/simple/ These are my python and pip versions: (venv)root@graphene-62:~/tensorflow# pip -V pip 8.1.2 from /usr/local/lib/python2.7/dist-packages/pip-8.1.2-py2.7.egg (python 2.7) (venv)root@graphene-62:~/tensorflow# python -V Python 2.7.6 After I tried pip install -U tensorflow, I got the following result: Cannot uninstall 'six' Then I tried pip install -U tensorflow --ignore-installed six, and with the tf version check I got: (venv)root@graphene-62:~/tensorflow# python -c "import tensorflow as tf; print(tf.__version__)" Illegal instruction (core dumped) (venv)root@graphene-62:~/tensorflow# Is there another way to download and install Tensorflow?
has answer: http://stackoverflow.com/a/57236839
accepted answer: http://stackoverflow.com/a/51629636
has title: Install Tensorflow in virtual environment python 2.7
tagged with: python
possible better answer: http://stackoverflow.com/a/57236839
has comment: http://stackoverflow.com/comment/90223303
type: AnsweredQuestion
tagged with: pip
upvote count: 1
downvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90223320
has answer: http://stackoverflow.com/a/51629636
has comment: http://stackoverflow.com/comment/90223182
tagged with: six
score: 0
answer count: 2
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/90223248

http://stackoverflow.com/q/51560867
has comment: http://stackoverflow.com/comment/90089410
has answer: http://stackoverflow.com/a/51562235
has answer: http://stackoverflow.com/a/67204459
has comment: http://stackoverflow.com/comment/90089193
has comment: http://stackoverflow.com/comment/90089328
type: Question
has body: I have been working on a program which will take a hex file, and if the file name starts with "CID", then it should remove the first 104 characters, and after that point there is a few words. I also want to remove everything after the words, but the problem is the part I want to isolate varies in length. My code is currently like this: y = 0 import os files = os.listdir(".") filenames = [] for names in files: if names.endswith(".uexp"): filenames.append(names) y +=1 print(y) print(filenames) for x in range(1,y): filenamestart = (filenames[x][0:3]) print(filenamestart) if filenamestart == "CID": openFile = open(filenames[x],'r') fileContents = (openFile.read()) ItemName = (fileContents[104:]) print(ItemName) Input Example file (pulled from HxD): .........................ýÿÿÿ................E.................!...1AC9816A4D34966936605BB7EFBC0841.....Sun Tan Specialist.................9.................!...9658361F4EFF6B98FF153898E58C9D52.....Outfit.................D.................!...F37BE72345271144C16FECAFE6A46F2A.....Don't get burned............................................................................................................................Áƒ*ž I have got it working to remove the first 104 characters, but I would also like to remove the characters after 'Sun Tan Specialist', which will differ in length, so I am left with only that part. I appreciate any help that anyone can give me.
has title: How to remove all non-alphabetic characters from a string?
has answer: http://stackoverflow.com/a/51561220
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90088612
has comment: http://stackoverflow.com/comment/90089256
answer count: 3
has comment: http://stackoverflow.com/comment/90089826
tagged with: hex
tagged with: hexdump
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90089368
tagged with: python
score: 2

http://stackoverflow.com/q/51599456
has title: Changing Non Maximum Suppression to pick smallest box for OpenCV in Python
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
has body: Some quick googling will find you this sort of code for non maximum suppression. import numpy as np # Malisiewicz et al. def non_max_suppression_fast(boxes, overlapThresh): if len(boxes) == 0: return [] if boxes.dtype.kind == "i": boxes = boxes.astype("float") pick = [] x1 = boxes[:,0] y1 = boxes[:,1] x2 = boxes[:,2] y2 = boxes[:,3] area = (x2 - x1 + 1) * (y2 - y1 + 1) idxs = np.argsort(y2) while len(idxs) &gt; 0: last = len(idxs) - 1 i = idxs[last] pick.append(i) xx1 = np.maximum(x1[i], x1[idxs[:last]]) yy1 = np.maximum(y1[i], y1[idxs[:last]]) xx2 = np.minimum(x2[i], x2[idxs[:last]]) yy2 = np.minimum(y2[i], y2[idxs[:last]]) w = np.maximum(0, xx2 - xx1 + 1) h = np.maximum(0, yy2 - yy1 + 1) overlap = (w * h) / area[idxs[:last]] idxs = np.delete(idxs, np.concatenate(([last], np.where(overlap &gt; overlapThresh)[0]))) return boxes[pick].astype("int") This will return the largest box for a group of overlapping boxes whose area overlap by the percentage that can be indicated in the function. How might you change this to return the smallest box in a group of overlapping boxes?
tagged with: opencv
has answer: http://stackoverflow.com/a/51600178
type: Question

http://stackoverflow.com/q/51587370
score: 2
answer count: 0
downvote count: 0
tagged with: sql-execution-plan
tagged with: sqlalchemy
type: Question
tagged with: pymssql
tagged with: sql-server
upvote count: 2
has body: I am using sqlalchemy and python3 to query a database on Microsoft SQL Server. Since I do not have access to SQL Server Management Studio I am resorting to using SHOWPLAN options in my queries. I found this outlined in answer here: How do I obtain a Query Execution Plan? The problem is the output of using STATISTICS XML ON is not human friendly. I generally use sqlalchemy to retrieve data in pandas dataframes so please forgive my ignorance if I am missing something obvious to interpret this in a friendlier manner. Please find my python3 code below: from sqlalchemy import create_engine import os database_credentials = config.settings['database_credentials'] # Retrieve database credentials from config db_name = os.environ.get(database_credentials['db_name']) db_host = os.environ.get(database_credentials['db_host']) db_port = os.environ.get(database_credentials['db_port']) db_id = os.environ.get(database_credentials['db_id']) db_pwd = os.environ.get(database_credentials['db_pwd']) # Concatenate strings to create database url db_engine = create_engine('mssql+pymssql://' + db_id + ':' + db_pwd + '@' + db_host + ':' + db_port + '/' + db_name) # Connect to database db_conn = db_engine.connect() # Example query with SHOW Plan options query = 'SET STATISTICS XML ON\n SELECT TOP 5 * FROM Table' # Execute the query result = db_engine.execute(query) Is there a way to format result into something that is readable to understand the query plan? Thanks for your help
has comment: http://stackoverflow.com/comment/90141619
linked to: http://stackoverflow.com/q/7359702
has comment: http://stackoverflow.com/comment/90141784
has title: How to get a digestible query plan with sqlalchemy and 'SET STATISTICS XML ON' on Microsoft SQL Server in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/90140754
linked to: http://stackoverflow.com/q/28813876
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90143706

http://stackoverflow.com/comment/90236178
score: 0
has text: Here is a JavaScript solution, in case anyone is interested ... https://jsfiddle.net/MrPolywhirl/vt9z5csL
type: Comment
comment on: http://stackoverflow.com/a/51614380
type: AnswerComment

http://stackoverflow.com/comment/89942118
score: 0
type: Comment
type: QuestionComment
has text: NEVERMIND, all my fault!! forgot to tell the program that i was writing in python....
comment on: http://stackoverflow.com/q/51485597

http://stackoverflow.com/a/51629928
accepted answer of: http://stackoverflow.com/q/51629691
answers question: http://stackoverflow.com/q/51629691
upvote count: 2
has comment: http://stackoverflow.com/comment/90252766
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90225559
type: Answer
has comment: http://stackoverflow.com/comment/90225314
has body: collections.Counter is useful for summing values in dictionaries and adding keys where they do not exist. Since Counter is a subclass of dict, this should not break other operations. Apart from a one-off conversion cost, it is efficient and designed specifically for such tasks. from collections import Counter # convert d to dictionary of Counter objects d = {k: Counter(v) for k, v in d.items()} # add items from e for k, v in e.items(): if k in d: d[k] += Counter(e[k]) # add item from f if not found for k, v in f.items(): if k not in d: d[k] += Counter(f[k]) # add item from g if not found for k, v in g.items(): if k not in d: d[k] = Counter(v) Result: print(d) {'siteA': Counter({'00000000': 8, '11111111': 4, '22222222': 5}), 'siteB': Counter({'00000000': 1, '11111111': 2, '22222222': 5}), 'siteC': Counter({'00000000': 8})}
score: 2
downvote count: 0

http://stackoverflow.com/comment/89996379
type: Comment
has text: @JafferWilson - Not sure if understand each other. Do you need datetimes (type datetime) with format `YYYY.MM.DD HH:MM:SS` ?
type: AnswerComment
comment on: http://stackoverflow.com/a/51512094
score: 0

http://stackoverflow.com/q/51521158
tagged with: python
has body: Inputting the command 0xbin() returns False: >>> 0xbin() False Why does that happen? This syntax should have no meaning whatsoever. Functions cannot start with 0, there are no "i" and "n" in hex, and the bin function must have some arguments. 2023 update: this is soon expected to be a syntax error.
downvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90407573
has comment: http://stackoverflow.com/comment/90014448
type: Question
has comment: http://stackoverflow.com/comment/90028361
has answer: http://stackoverflow.com/a/51521235
has title: In python, why does 0xbin() return False?
possible better answer: http://stackoverflow.com/a/51521261
score: 195
linked to: http://stackoverflow.com/q/23998026
has comment: http://stackoverflow.com/comment/90015634
has answer: http://stackoverflow.com/a/51530110
has answer: http://stackoverflow.com/a/51521261
has comment: http://stackoverflow.com/comment/90064564
answer count: 4
duplicate of: http://stackoverflow.com/q/23998026
has comment: http://stackoverflow.com/comment/90091303
favorite count: 0
upvote count: 201
has answer: http://stackoverflow.com/a/51525049
has comment: http://stackoverflow.com/comment/90056520
accepted answer: http://stackoverflow.com/a/51521235

http://stackoverflow.com/a/77136961
downvote count: 0
type: Answer
has body: As @Isaac noted, the accepted answer no longer works. @jezrael's modification (in the comments of accepted answer) fails if there is more than one grouping variable. Here's an updated modification of @jezrael's answer. import numpy as np import pandas as pd from platform import python_version print(python_version()) print(pd.__version__) np.random.seed(785) N = 10000 df = pd.DataFrame({'key1':np.random.randint(30, size=N), 'key2':np.random.randint(30, size=N), 'A':np.random.choice([1,2,np.nan], size=N), 'B':np.random.choice([1,4,np.nan], size=N), 'C':np.random.choice([7,0,np.nan], size=N), 'D':np.random.choice([7,0,8], size=N)}) df = df.sort_values(['key1', 'key2']) group_keys = ['key1', 'key2'] some_cols = ['A','B','C'] df1 = df.copy() df2 = df.copy() # slow method def ffbf(x): return x.ffill().bfill() df1[some_cols] = df1.groupby(group_keys)[some_cols].transform(ffbf) # fast method gidx = df2.groupby(group_keys, sort=False).ngroup() df2 = df2.groupby(gidx).ffill().groupby(gidx).bfill() print (df2.equals(df1)) import timeit slow = """dfn = df.groupby(group_keys)[some_cols].transform(ffbf)""" print(timeit.timeit(slow, globals=globals(), number=20)) fast = """gidx = df.groupby(group_keys, sort=False).ngroup() dfn = df.groupby(gidx).ffill().groupby(gidx).bfill()""" print(timeit.timeit(fast, globals=globals(), number=20)) Output: 3.10.13 2.0.3 True 4.181147900002543 0.07793619995936751
upvote count: 1
answers question: http://stackoverflow.com/q/51604819
score: 1

http://stackoverflow.com/a/51519942
has comment: http://stackoverflow.com/comment/90008914
has comment: http://stackoverflow.com/comment/90009595
has comment: http://stackoverflow.com/comment/90008732
has body: Don't use map or a list comprehension where simple for loop will do: for x in list_of_objs: x.process() It's not significantly longer than any function you might use to abstract it, but it is significantly clearer. Of course, if process returns a useful value, then by all means, use a list comprehension. results = [x.process() for x in list_of_objs] or map: results = list(map(lambda x: x.process(), list_of_objs)) There is a function available that makes map a little less clunky, especially if you would reuse the caller: from operator import methodcaller processor = methodcaller('process') results = list(map(processor, list_of_objs)) more_results = list(map(processor, another_list_of_objs)) If you are looking for a good name for a function to wrap the loop, Haskell has a nice convention: a function name ending with an underscore discards its "return value". (Actually, it discards the result of a monadic action, but I'd rather ignore that distinction for the purposes of this answer.) def map_(f, *args): for f_args in zip(*args): f(*f_args) # Compare: map(f, [1,2,3]) # -- return value of [f(1), f(2), f(3)] is ignored map_(f, [1,2,3]) # list of return values is never built
upvote count: 12
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90009865
accepted answer of: http://stackoverflow.com/q/51519696
answers question: http://stackoverflow.com/q/51519696
score: 12
type: Answer

http://stackoverflow.com/q/51494516
has answer: http://stackoverflow.com/a/51494588
tagged with: python
upvote count: 0
type: UnansweredQuestion
type: Question
score: -2
tagged with: dataframe
has body: I got a dataframe like this: A B C 1 1 1 2 2 2 3 3 3 4 1 1 I want to 'merge' the three columns to form a D column, the rule is: if there is at least one '1' in the row, then the value of D is '1' else is '0'. How can I achieve it?
downvote count: 2
has title: dataframe merger column operation
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/24761133
tagged with: pandas

http://stackoverflow.com/a/51540449
has body: You can use functools.reduce to sum this nested list &gt;&gt;&gt; from functools import reduce &gt;&gt;&gt; a = [1,2,3,[4,5]] &gt;&gt;&gt; reduce(lambda x,y: x + (sum(y) if type(y)==list else y), [0]+a) 15 If the list can be more than one level nested, you have to use a recursive approach &gt;&gt;&gt; f = lambda x,y: x + (reduce(f, y) if type(y)==list else y) &gt;&gt;&gt; reduce(f, [0]+a) 15
score: 0
answers question: http://stackoverflow.com/q/51540270
type: Answer

http://stackoverflow.com/a/51621541
score: 0
type: Answer
has body: 5:00 does not indicate the time. Here's a relevant example. a = range(10) print(a[5:00]) print(list(a[5:00])) gives range(5,0) [] Try '5:00' instead.
answers question: http://stackoverflow.com/q/51621431

http://stackoverflow.com/comment/89974970
type: AnswerComment
comment on: http://stackoverflow.com/a/51502978
type: Comment
has text: I posted my initial attempt as a separate answer because it is so silly. This is actually a very elegant solution.
score: 0

http://stackoverflow.com/q/51551189
has title: want to get the log from the git repository having details (date , time, gmt , file path , author) in same order and line
answer count: 0
type: Question
has body: pr1 = subprocess.Popen( "C:/Program Files/Git/bin/git log --format=%ai%an --name-only --oneline HEAD" , cwd = os.path.dirname('C:/Users/Angular-GettingStarted/APM-Start' ), shell = False, stdout= logFile) pr1.wait() i m using this command but having issues
has comment: http://stackoverflow.com/comment/90069754
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/108929130
tagged with: python
tagged with: git
has comment: http://stackoverflow.com/comment/90069634

http://stackoverflow.com/comment/90216054
has text: You should confirm if `os.environ.get('ADAM_SLACK_TOKEN')` is set
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51618547

http://stackoverflow.com/comment/90174555
score: 0
has text: This question might be liable to **downvotes** since it might not be useful.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51604374

http://stackoverflow.com/comment/90055509
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51543140
type: QuestionComment
has text: @ NOhs, sorry I was wrong.

http://stackoverflow.com/comment/90127664
type: Comment
comment on: http://stackoverflow.com/a/51580854
type: AnswerComment
has text: It should be dropdown and slider selection
score: 0

http://stackoverflow.com/a/51579159
has body: The issue with your code is when iterating you are checking for 0 in list1 you are running a continue defaulting value to -9999 and 0. the following code post continue should be outside of if condition. growth = (list2[i]-list1[i])/list1[i] percent_growth.append(growth*100) if growth &gt; 0: target.append(1) else: target.append(0) You can use list comprehension. zip the two lists a=[4,3,2,5,6,0,0,1] b=[1,2,5,0,7,0,1,8] zip(a,b) create a tuple of two lists. Then use list comprehension to achieve. per_growth = [-9999 if x == 0 else (((y - x) * 100) / x) for x, y in zip(a, b) ] target = [ 1 if t &gt; 0 else 0 for t in per_growth ] print([(x,y) for x,y in zip(per_growth, target)]) Answer: [(-75.0, 0), (-33.333333333333336, 0), (150.0, 1), (-100.0, 0), (16.666666666666668, 1), (-9999, 0), (-9999, 0), (700.0, 1)] Edited answer based on comments. Thanks.
has comment: http://stackoverflow.com/comment/90123729
score: -1
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90123849
upvote count: 0
answers question: http://stackoverflow.com/q/51579054

http://stackoverflow.com/comment/90146534
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51493675
has text: How to delete perticular value from dataframe. Like `df['2'].astype('str')=='23'` and the rest column's value shift up.
type: AnswerComment

http://stackoverflow.com/comment/90227469
type: QuestionComment
comment on: http://stackoverflow.com/q/51631329
has text: @Thomas Thanks for the comment, I made an example I the question.
score: 0
type: Comment

http://stackoverflow.com/comment/89949406
type: Comment
type: QuestionComment
has text: `os.walk(".")` will look at the current folder, which is `C:\Users\DELL` when you run it from cmd, but will probably be `D:\Act\Temp\2017\Bukti_PPR`. You can do `print(os.getcwd())` to check what the current directory is to debug this.
score: 0
comment on: http://stackoverflow.com/q/51490014

http://stackoverflow.com/a/51525661
has comment: http://stackoverflow.com/comment/90060970
answers question: http://stackoverflow.com/q/51525532
has comment: http://stackoverflow.com/comment/90022592
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90093046
has comment: http://stackoverflow.com/comment/90060692
has comment: http://stackoverflow.com/comment/90060584
has comment: http://stackoverflow.com/comment/90061004
has comment: http://stackoverflow.com/comment/90060638
score: 0
has comment: http://stackoverflow.com/comment/90020323
has comment: http://stackoverflow.com/comment/90059706
has comment: http://stackoverflow.com/comment/90060920
has comment: http://stackoverflow.com/comment/90061027
has comment: http://stackoverflow.com/comment/90020538
has comment: http://stackoverflow.com/comment/90061157
has comment: http://stackoverflow.com/comment/90061133
type: Answer
has comment: http://stackoverflow.com/comment/90088265
has comment: http://stackoverflow.com/comment/90060784
has body: try bs4...? from bs4 import BeautifulSoup page = ''' Fujifilm GFX 50S Fujifilm G 0.79 ''' soup = BeautifulSoup(page, 'lxml') make = soup.find('maker') model = soup.find('model') print(f'Make: {make.text}\nModel: {model.text}') for multiple entries, just loop through them with find_all() from bs4 import BeautifulSoup page = ''' Fujifilm GFX 50S Fujifilm G 0.79 thing1 thing2 Fujifilm G 0.79 thing3 thing4 Fujifilm G 0.79 thing5 thing6 Fujifilm G 0.79 ''' soup = BeautifulSoup(page, 'lxml') make = soup.find_all('maker') model = soup.find_all('model') for x, y in zip(make, model): print(f'Make: {x.text}\nModel: {y.text}') getting data through a file: from bs4 import BeautifulSoup with open('path/to/your/file') as file: page = file.read() soup = BeautifulSoup(page, 'lxml') make = soup.find_all('maker') model = soup.find_all('model') for x, y in zip(make, model): print(f'Make: {x.text}\nModel: {y.text}') without importing any modules: with open('/PATH/TO/YOUR/FILE') as file: for line in file: for each in line.split(): if "maker" in each: each = each.replace(" ", "") print(each.replace(" ", "")) this is for the 'maker' tag only, it might be beneficial to split these up into separate definitions and iterate through them
has comment: http://stackoverflow.com/comment/90020292
has comment: http://stackoverflow.com/comment/90061064
has comment: http://stackoverflow.com/comment/90061245
accepted answer of: http://stackoverflow.com/q/51525532

http://stackoverflow.com/a/51633240
answers question: http://stackoverflow.com/q/51632254
score: 4
has body: Your problem is that you are only passing one set of coordinates to set_data()/set_3d_properties, and therefore only one point remains. You need to update all the coordinates of all your points, and then update points with those arrays. I could not figure out exactly how you were doing your math in the update function, so here's an example using random fluctuations: from matplotlib import pyplot as plt import numpy as np import mpl_toolkits.mplot3d.axes3d as p3 from matplotlib import animation fig = plt.figure() ax = p3.Axes3D(fig) q = [[-4.32, -2.17, -2.25, 4.72, 2.97, 1.74], [ 2.45, 9.73, 7.45,4.01,3.42, 1.80],[-1.40, -1.76, -3.08,-9.94,-3.13,-1.13]] v = [[ 0.0068,0.024, -0.014,-0.013, -0.0068,-0.04],[ 0.012, 0.056, -0.022,0.016, 0.0045, 0.039], [-0.0045, 0.031, 0.077,0.0016, -0.015,-0.00012]] x=np.array(q[0]) y=np.array(q[1]) z=np.array(q[2]) s=np.array(v[0]) u=np.array(v[1]) w=np.array(v[2]) points, = ax.plot(x, y, z, '*') txt = fig.suptitle('') def update_points(num, x, y, z, points): txt.set_text('num={:d}'.format(num)) # for debug purposes # calculate the new sets of coordinates here. The resulting arrays should have the same shape # as the original x,y,z new_x = x+np.random.normal(1,0.1, size=(len(x),)) new_y = y+np.random.normal(1,0.1, size=(len(y),)) new_z = z+np.random.normal(1,0.1, size=(len(z),)) # update properties points.set_data(new_x,new_y) points.set_3d_properties(new_z, 'z') # return modified artists return points,txt ani=animation.FuncAnimation(fig, update_points, frames=10, fargs=(x, y, z, points)) plt.show()
type: AcceptedAnswer
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/51632254
downvote count: 0

http://stackoverflow.com/q/51591245
upvote count: 4
answer count: 2
downvote count: 0
has title: sphinx and autodocstring from VScode with python code
has body: I'm collaborating on a project with people that use vscode. We write Python code. I asked them to generate the docstrings for their functions, and they used the Autodocstring from vscode. Here is a docstring they came up with: """ Subclass ObjectCAD renderToFile method to render the scad file in renders_dir Arguments: file_path {str} -- the destination path for the scad file Returns: None """ It's supposed to be a Google style docstring. When I generate a html doc with Sphinx, here is whet I get: While I should get something like that: Am I missing an option in sphinx configuration? Or is the Autodocstring broken?
tagged with: docstring
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/66772685
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/54251517
tagged with: visual-studio-code
score: 4

http://stackoverflow.com/q/51506029
accepted answer: http://stackoverflow.com/a/51506121
type: AnsweredQuestion
has body: I have a problem with this. When a record already exists, I like the data, but when not, obviously not. How is this validated so that the template can be seen when there is no record of a post? Image error view.py def MemoList(request, usuario): instancia = get_object_or_404(Empleado, usuario_id=usuario) lista2 = Memorandum.objects.filter(para_id=instancia) for usuarios in lista2: lista_de = usuarios.de lista_para_id = usuarios.para_id lista_asunto = usuarios.asunto lista_fecha = usuarios.fecha context = { "lista2":lista2, "lista_de": usuarios.de, "lista_para_id": lista_para_id, "lista_asunto": lista_asunto, "lista_fecha" : lista_fecha } return render(request, 'app/admin/memolist.html',context)
downvote count: 1
type: Question
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/89981203
answer count: 1
has title: DJANGO: local variable 'usuarios' referenced before assignment
favorite count: 0
has comment: http://stackoverflow.com/comment/89981329
has answer: http://stackoverflow.com/a/51506121
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89981074

http://stackoverflow.com/comment/90105260
comment on: http://stackoverflow.com/q/51569414
score: 2
has text: If I execute your code I get "JSONDecodeError: Expecting value: line 1 column 1 (char 0)" at line 10. Is it working for you ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90271432
has text: Sites can really only block by IP address, or they can try to hand you a `cookie` and if you don't accept it they assume you are a bot and will sometimes reject your request. However, most sites _want_ to be spidered, that's how they generate traffic. You could also always contact the webmaster (if it's a small site). If you've found my answer helpful, please accept it :) and welcome to StackOverflow! :)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51639210

http://stackoverflow.com/comment/90784094
type: QuestionComment
type: Comment
has text: I am working on a similar setup (Cognito + React + Django DRF). I have got the cognito working as well and receive id, session and access token. I was thinking I have to pass the access token as authorization token to DRF but not sure how to decode it in drf. Can u post ur implementation so i can use it as reference. Many Thanks.
score: 1
comment on: http://stackoverflow.com/q/51510690

http://stackoverflow.com/a/51503434
has body: One way to do this is to use pd.MultiIndex and reindex: df = pd.DataFrame({'Product':list('ABCDEF'), 'Customer':[1,1,2,3,3,3], 'Amount':[4,5,3,1,1,2]}) indx = pd.MultiIndex.from_product([df['Product'].unique(), df['Customer'].unique()], names=['Product','Customer']) df.set_index(['Product','Customer'])\ .reindex(indx, fill_value=0)\ .reset_index()\ .sort_values(['Customer','Product']) Output: Product Customer Amount 0 A 1 4 3 B 1 5 6 C 1 0 9 D 1 0 12 E 1 0 15 F 1 0 1 A 2 0 4 B 2 0 7 C 2 3 10 D 2 0 13 E 2 0 16 F 2 0 2 A 3 0 5 B 3 0 8 C 3 0 11 D 3 1 14 E 3 1 17 F 3 2
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51502595
answers question: http://stackoverflow.com/q/51502595
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89975937
type: Answer

http://stackoverflow.com/a/51567118
has body: The magnitude of your original data is 0 to 1. Your error is about 1e-16. This is totally normal, as a 64-bit floating point number has about 15 significant digits. So an error of 1e-16 on a calculation with magnitude 0.5 is to be expected. As for why the error does not occur when using inter-process communication, it may be because your local CPU uses an 80-bit internal floating point format (as x87 has always done), whereas floating point numbers sent between processes are going to be limited to 64 bits of precision. There are some special techniques to sum sets of floating point numbers more accurately. Here is one: https://en.wikipedia.org/wiki/Kahan_summation_algorithm
upvote count: 1
has comment: http://stackoverflow.com/comment/90102218
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90101459
type: Answer
answers question: http://stackoverflow.com/q/51566575

http://stackoverflow.com/comment/89973650
has text: on my configuration, `np.int64(42) == ("A", "B")` returns `array(False, False)`, but the numpy version is 1.14.0
comment on: http://stackoverflow.com/a/51501842
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51555862
accepted answer: http://stackoverflow.com/a/51556075
type: AnsweredQuestion
tagged with: git
type: Question
tagged with: sys.path
linked to: http://stackoverflow.com/q/8663076
has body: I started to build a data processing framework in Python 3. The goal is to develop own packages and write example code to use the packages. The framework will be shared (any maybe developed) with other researchers by git. What is the best way to handle the search paths on multiple computers and how should the __init__.py files look like in the directories? I was thinking about adding sys.path relative to the main_directory (Python: Best way to add to sys.path relative to the current running script) with sys.path.append(os.getcwd()) or sys.path.append(".."). I don’t know if this is a good way to import beyond top level on different machines with different absolute paths and operation systems. (The beyond top level package error/problem: beyond top level package error in relative import) The basic directory structure might be (I will add more packages and processing functions later): main_directory/ main_directory/__init__.py main_directory/packages/ main_directory/packages/__init__.py main_directory/packages/preprocessing/ main_directory/packages/preprocessing/filters.py #implementation of multiple classes: e.g. fillter1 and filter2 main_directory/packages/preprocessing/__init__.py main_directory/packages/postprocessing/ main_directory/packages/postprocessing/filters.py #implementation of multiple classes: e.g. fillterA and filterB main_directory/packages/postprocessing/__init__.py main_directory/examples/ main_directory/examples/easy_example.py #file with examples to use the filters main_directory/your_code/ main_directory/your_code/your_code.py #file with your code to use the filters
has answer: http://stackoverflow.com/a/51556075
score: 0
answer count: 1
tagged with: python-3.x
has title: Python3 framework with own packages and shared with git: How to handle sys.path and __init__.py files?
linked to: http://stackoverflow.com/q/30669474
tagged with: package
tagged with: python

http://stackoverflow.com/comment/90011468
type: QuestionComment
has text: Zip df.columns and df_out https://docs.python.org/3/library/functions.html#zip
score: 1
type: Comment
comment on: http://stackoverflow.com/q/51521333

http://stackoverflow.com/q/51594788
tagged with: python
has answer: http://stackoverflow.com/a/51595155
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90155355
upvote count: 1
type: Question
tagged with: ibm-cloud
has body: I'm trying to create a listener in python that automatically retrieve events from devices in Watson-IoT as they occur. When an event occurs I want to call a specific function. I have read through the documentation and the API-specifications but couldn't find anything. Is there a way to do this?
tagged with: iot
has title: Watson-IoT event listener in python
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51595155
tagged with: listener
tagged with: watson-iot

http://stackoverflow.com/comment/90238786
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51637149
has text: python 3+ requires parentheses, while python 2 doesn't
score: 0

http://stackoverflow.com/comment/90162834
has text: Zero is a cost function
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51598353

http://stackoverflow.com/q/51616078
type: Question
has answer: http://stackoverflow.com/a/51624680
has body: I tried to write a Policy Gradient algorithm for the Video game Pong. Here's the Code: import tensorflow as tf import gym import numpy as np import matplotlib.pyplot as plt from os import getcwd num_episodes = 1000 learning_rate = 0.01 rewards = [] env_name = 'Pong-v0' env = gym.make(env_name) x = tf.placeholder(tf.float32,(None,)+env.observation_space.shape) y = tf.placeholder(tf.float32,(None,env.action_space.n)) def net(x): layer1 = tf.layers.flatten(x) layer2 = tf.layers.dense(layer1,200,activation=tf.nn.softmax) layer3 = tf.layers.dense(layer2,env.action_space.n,activation=tf.nn.softmax) return layer3 logits = net(x) loss = tf.losses.sigmoid_cross_entropy(y,logits) train = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) saver = tf.train.Saver() init = tf.global_variables_initializer() sess = tf.Session() with tf.device('/device:GPU:0'): sess.run(init) for episode in range(num_episodes): print('episode:',episode+1) total_reward = 0 losses = [] training_data = [] observation = env.reset() while True: if max(0.1, (episode+1)/num_episodes) &gt; np.random.uniform(): probs = sess.run(logits,feed_dict={x:[observation]})[0] action = np.argmax(probs) else: action = env.action_space.sample() onehot = np.zeros(env.action_space.n) onehot[action] = 1 training_data.append([observation,onehot]) observation, reward, done, _ = env.step(action) total_reward += reward if done: break if total_reward &gt;= 0: learning_rate = 0.01 else: learning_rate = -0.01 for sample in training_data: l,_ = sess.run([loss,train],feed_dict={x:[sample[0]], y:[sample[1]]}) losses.append(l) print('loss:',l) print('average loss:',sum(losses)/len(losses)) saver.save(sess,getcwd()+'/model.ckpt') rewards.append(total_reward) plt.plot(range(episode+1),rewards) plt.ylabel('total reward') plt.xlabel('episodes') plt.savefig(getcwd()+'/reward_plot.png') But after I trained my Network, the plot which the script made seemed to suggest that the Network got worse towards the end. Also during the la…
score: 1
downvote count: 0
answer count: 1
tagged with: neural-network
has title: Policy Gradient algorithm gets worse over time
favorite count: 0
tagged with: reinforcement-learning
tagged with: python
type: UnansweredQuestion
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/a/51732062
type: Answer
has comment: http://stackoverflow.com/comment/90508281
downvote count: 0
has body: You can use sklearn.linear_model.LinearRegression. It allows you to not fit the intercept (i.e. line goes through the origin, or, with some finagling, the point of your choice). It also deals with weighted data. e.g. (mostly stolen shamelessly from @Hiho's answer) import numpy as np import matplotlib.pyplot as plt import sklearn.linear_model y = np.array([1.0, 3.3, 2.2, 4.25, 4.8, 5.1, 6.3, 7.5]) x = np.arange(y.shape[0]).reshape((-1,1)) w = np.linspace(1,5,y.shape[0]) model = sklearn.linear_model.LinearRegression(fit_intercept=False) model.fit(x, y, sample_weight=w) line_x = np.linspace(min(x), max(x), 100).reshape((-1,1)) pred = model.predict(line_x) plt.scatter(x, y) plt.plot(line_x, pred) plt.show()
accepted answer of: http://stackoverflow.com/q/51565946
upvote count: 8
answers question: http://stackoverflow.com/q/51565946
has comment: http://stackoverflow.com/comment/90510166
has comment: http://stackoverflow.com/comment/90510111
type: AcceptedAnswer
score: 8
has comment: http://stackoverflow.com/comment/90510120

http://stackoverflow.com/comment/89941328
comment on: http://stackoverflow.com/q/51486155
score: 4
type: Comment
type: QuestionComment
has text: try printing `str(df1)` to see what you get

http://stackoverflow.com/comment/90007012
type: Comment
comment on: http://stackoverflow.com/a/51517698
type: AnswerComment
score: 0
has text: You forgot the parenthesis when calling the method `transpose`: `df.transpose().grupby()``; Btw you can only create the dataframe from the dictionary if you have the same amount of columns A,B,C.

http://stackoverflow.com/q/51531399
type: Question
has comment: http://stackoverflow.com/comment/90030631
tagged with: django-models
has comment: http://stackoverflow.com/comment/90030506
has comment: http://stackoverflow.com/comment/90031297
downvote count: 0
has comment: http://stackoverflow.com/comment/90032361
has title: How to set a default value for a float field using django models?
favorite count: 0
has comment: http://stackoverflow.com/comment/90031104
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90031255
answer count: 0
has comment: http://stackoverflow.com/comment/90030968
has comment: http://stackoverflow.com/comment/90030569
score: 1
has comment: http://stackoverflow.com/comment/90030532
has body: from django.db import models class doctors(models.Model): docid = models.AutoField(primary_key=True, unique=True) # Need autoincrement, unique and primary name = models.CharField(max_length=35) regid = models.CharField(max_length=15, default="") photo = models.CharField(max_length=35, default="") email = models.EmailField(default="") phone = models.IntegerField(default=0, null=True) qualifications = models.CharField(max_length=50, default="") about = models.CharField(max_length=35, default="") specialities = models.CharField(max_length=50, default="") department = models.CharField(max_length=50, default="ENT") fees = models.FloatField(default=300.0, null=True) displayfee = models.IntegerField(default=0, null=True) slotrange = models.CharField(max_length=50) slotdurn = models.IntegerField(default=10, null=True) breakrange = models.CharField(max_length=50, default="") slotsleft = models.CharField(max_length=50, default="") What I intended: If one of the fields like phone, fees, displayfee, or slotdurn is not specified, they should be filled in a default value. Unfortunately these are filled with an automatic value of NULL when I do the following: from appointments.models import doctors doc=doctors(name="Dr Joel", regid="12524", email="joel@mydomain.com") doc.save() I checked the sql created, and it is like this: CREATE TABLE `appointments_doctors` ( `docid` int(11) NOT NULL, `name` varchar(35) NOT NULL, `regid` varchar(15) NOT NULL, `photo` varchar(35) NOT NULL, `email` varchar(254) NOT NULL, `phone` int(11) DEFAULT NULL, `qualifications` varchar(50) NOT NULL, `about` varchar(35) NOT NULL, `specialities` varchar(50) NOT NULL, `department` varchar(50) NOT NULL, `fees` double DEFAULT NULL, `displayfee` int(11) DEFAULT NULL, `slotrange` varchar(50) NOT NULL, `slotdurn` int(11) DEFAULT NULL, `breakrange` varchar(50) NOT NULL, `slotsleft` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; It seems the default value I specified is being overridden by the Null valu…
upvote count: 1

http://stackoverflow.com/comment/89979376
has text: I get and agree with your usage of extend (and am changing my code to do just that), but wouldn't the "for x in ..." method still have me modifying the list as I'm iterating it? That was one of the first things I tried.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51505120

http://stackoverflow.com/q/51619643
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: encryption
tagged with: rijndael
tagged with: python
tagged with: aes
has answer: http://stackoverflow.com/a/51620188
upvote count: 3
has title: Rijndael encryption in python
type: Question
has body: I wanna use Rijndael encryption with key and block 256bit size in python and padding should be PKCS7. either with utf-8 encode. I have searched a lot and finally wrote this code, I don't know this is a good way but that's all I know. when run the code I got this Error: Traceback (most recent call last): File "testForRijndael.py", line 1, in &lt;module&gt; from rijndael.cipher import crypt File "/opt/odoo/odoo11-venv/lib/python3.6/site- packages/rijndael/cipher/crypt.py", line 1, in &lt;module&gt; from rijndael.cipher.blockcipher import * File "/opt/odoo/odoo11-venv/lib/python3.6/site- packages/rijndael/cipher/blockcipher.py", line 64 raise Exception,"the IV length should be %i bytes"%self.blocksize ^ SyntaxError: invalid syntax If anybody can help me, I'll be appreciate him/her This is my code: from rijndael.cipher import crypt from rijndael.cipher.blockcipher import MODE_CBC from pkcs7 import PKCS7Encoder class Rijndael(): def __init__(self, key, iv): self.KEY = key self.IV = iv self.BLOCKSIZE = 32 def encrypt(self, plain_text): rjn = crypt.new(self.KEY, MODE_CBC , self.IV, blocksize=self.BLOCKSIZE) pad_text = PKCS7Encoder.encode(plain_text) return rjn.encrypt(pad_text).encode() def decrypt(self, cipher_text): rjn = crypt.new(self.KEY, MODE_CBC , self.IV, blocksize=self.BLOCKSIZE) cipher_text = cipher_text.decode() return rjn.decrypt(cipher_text) r = Rijndael('abcdefghijklmnopqrstuvwxyz123456', 'abcdefghijklmnopqrstuvwxyzgh3456') test_text = "this is a test :)" encrypt = r.encrypt(test_text) decrypt = r.decrypt(encrypt) print(test_text) print(encrypt) print(decrypt)
score: 3

http://stackoverflow.com/comment/90053495
comment on: http://stackoverflow.com/a/51529275
score: 0
type: Comment
has text: Code updated - I tried it in two places (see above) and in both cases it says it is not defined. Is it possible that the `os.path.join` needs a `\` between `folderPath, target' ? Sorry new to `os.` and python in general.
type: AnswerComment

http://stackoverflow.com/q/51509741
type: Question
upvote count: 0
score: -1
answer count: 2
has answer: http://stackoverflow.com/a/51509780
accepted answer: http://stackoverflow.com/a/51509780
possible better answer: http://stackoverflow.com/a/66216170
tagged with: pandas
has comment: http://stackoverflow.com/comment/89988627
favorite count: 0
tagged with: python-3.x
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66216170
has title: Python datetime delta format
tagged with: formatting
downvote count: 1
has body: I am attempting to find records in my dataframe that are 30 days old or older. I pretty much have everything working but I need to correct the format of the Age column. Most everything in the program is stuff I found on stack overflow, but I can't figure out how to change the format of the delta that is returned. import pandas as pd import datetime as dt file_name = '/Aging_SRs.xls' sheet = 'All' df = pd.read_excel(io=file_name, sheet_name=sheet) df.rename(columns={'SR Create Date': 'Create_Date', 'SR Number': 'SR'}, inplace=True) tday = dt.date.today() tdelta = dt.timedelta(days=30) aged = tday - tdelta df = df.loc[df.Create_Date &lt;= aged, :] # Sets the SR as the index. df = df.set_index('SR', drop = True) # Created the Age column. df.insert(2, 'Age', 0) # Calculates the days between the Create Date and Today. df['Age'] = df['Create_Date'].subtract(tday) The calculation in the last line above gives me the result, but it looks like -197 days +09:39:12 and I need it to just be a positive number 197. I have also tried to search using the python, pandas, and datetime keywords. df.rename(columns={'Create_Date': 'SR Create Date'}, inplace=True) writer = pd.ExcelWriter('output_test.xlsx') df.to_excel(writer) writer.save()

http://stackoverflow.com/comment/89957663
score: 0
has text: @user2357112 Any suggestion what I have configured wrong?
comment on: http://stackoverflow.com/q/51487479
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51588060
upvote count: 2
has body: When i type pip install plotly i get this message Cannot uninstall 'nbformat'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall. So, i type pip uninstall nbformat, message shows also Cannot uninstall 'nbformat'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall. How can i install plotly??
downvote count: 1
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: pip
tagged with: python
has title: cannot install plotly python
has comment: http://stackoverflow.com/comment/90141919
score: 1
tagged with: plotly
type: Question
has comment: http://stackoverflow.com/comment/90141384
has comment: http://stackoverflow.com/comment/90142841
linked to: http://stackoverflow.com/q/50421287

http://stackoverflow.com/a/51532516
answers question: http://stackoverflow.com/q/51530678
has body: After changing your code as little as possible, I think I have managed to get it working. from pprint import pprint # For debugging class Binary_Search_Tree: class __BST_Node: def __init__(self, value): self.value = value self.left = None self.right = None def __init__(self): self.__root = None self.__height = 0 self.__size = 0 def __in_order_str(self, root): if root is None: outcome = "[ ]" elif self.__size == 1: outcome = "[ " + str(root.value) + " ]" else: outcome = "[ " self.__in_order_str(root.left) outcome += str(root.value) + ", " self.__in_order_str(root.right) outcome += " ]" return outcome def __recur_ins(self, val, root): if root is None: root = Binary_Search_Tree.__BST_Node(val) elif root.value &gt; val: root.left = self.__recur_ins(val, root.left) elif root.value &lt; val: root.right = self.__recur_ins(val, root.right) return root def insert_element(self, value): self.__root = self.__recur_ins(value, self.__root) self.__size += 1 def test_insertion_from_empty(self): self.insert_element(50) self.insert_element(60) self.insert_element(70) # self.assertEqual('[ 30, 50, 70 ]', self.__bst.in_order()) test = Binary_Search_Tree() test.test_insertion_from_empty() pprint(vars(test)) Notes on the changes: changed some functions(_recur_ins, _in_order_str) from using '_' to '__' to make them private functions. I did it based on Python Official Documentation, private functions use at least two leading underscores and at most one trailing underscore. First line in insert_element, added 'self.__root= ' so that the returned root value will be stored as the new root Added 'self.' in front of '__recur_ins', since as far as I know, you must use self whenever you need to call a function which is located at the same class. I did not modify anything much in __in_order_str, since I think the author only asked for the insertion (?) commented assertEqual, since no function is provided in the question (?) Modified the spaces so that it can be more readable If I put the debug mod…
accepted answer of: http://stackoverflow.com/q/51530678
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90054023
has comment: http://stackoverflow.com/comment/90054377
score: 0
type: Answer

http://stackoverflow.com/a/51563103
answers question: http://stackoverflow.com/q/51562320
has body: To summarize CoderRambo and tgikal's responses, yes, I was able to uninstall BlueJeansMeetingsRestApi in that fashion: Kurts-MacBook-Pro-2:~ kurtpeek$ pip uninstall BlueJeansMeetingsRestApi Uninstalling BlueJeansMeetingsRestApi-1.0.0: Would remove: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/BlueJeansMeetingsRestApi-1.0.0-py3.7.egg-info /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/BlueJeansMeetingsRestApi/* /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/test/* Proceed (y/n)? y Successfully uninstalled BlueJeansMeetingsRestApi-1.0.0 At the root of the problem, however, was that iPython was running on Python 3.6, whereas BlueJeans was installed on Python 3.7. I confirmed this by using which ipython: Kurts-MacBook-Pro-2:~ kurtpeek$ which ipython /Library/Frameworks/Python.framework/Versions/3.6/bin/ipython I ran pip install ipython, and now it points to Python 3.7: Kurts-MacBook-Pro-2:~ kurtpeek$ which ipython /Library/Frameworks/Python.framework/Versions/3.7/bin/ipython I then re-installed the BlueJeans REST API (without specifying an egg), and now I'm able to import it: Kurts-MacBook-Pro-2:~ kurtpeek$ ipython Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) Type 'copyright', 'credits' or 'license' for more information IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: import BlueJeansMeetingsRestApi In [2]:
score: 0
type: Answer

http://stackoverflow.com/comment/90140203
has text: @nicosalto the model is an element independent of the view, for example a model can be in several views, so I ask you who should notify: the model to the views, or the views to the model?
comment on: http://stackoverflow.com/a/51587327
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51553439
downvote count: 1
type: Question
has body: I have a simple question. Please have a look at following script: def myFunc(string): res='' for i in string: if not i in res: res+i return res res=myFunc('aaaa') print(res) # return a string 'a' This script should be able to delete the repeated char in the input string. Actually, however, I got nothing. The 'res' is NULL. Do you have any ideas? Thanks!
answer count: 2
has comment: http://stackoverflow.com/comment/90074389
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/51553536
has title: String can't be extended via 'PLUS'
tagged with: string
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51553528

http://stackoverflow.com/a/51567472
has body: Instead of loop, I think you can simply use lambda with if and else condition: df['ADULT'] = df['first_name'].apply(lambda v: adults[v] if v in adults else np.nan) print(df.to_csv(index=False, na_rep='NA')) # Output is: # first_name,last_name,age,ADULT # John,Miller,42,True # Molly,Jacobson,17,False # Tina,Ali,16,NA # Jake,Milner,24,NA # Amy,Cooze,,NA In above, adults[val] if val in adults else np.nan simply looks for if val i.e. first_name for each row is in dictionary, if it is then value is kept for new column else np.nan You can use to_csv to print in above format, here without specifying filename, it converts to string with comma separated and na_rep specifies string to use for missing values.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51567397
answers question: http://stackoverflow.com/q/51567397
score: 0
type: Answer

http://stackoverflow.com/comment/90132568
score: 2
type: Comment
has text: @AndreasFinkler: By deleting the `foo` implementation, you're trying to dynamically turn a concrete class abstract. As the docs say, this is not supported.
type: AnswerComment
comment on: http://stackoverflow.com/a/51583480

http://stackoverflow.com/q/51526219
has title: create executable from python program with dependencies
downvote count: 0
tagged with: cx-freeze
linked to: http://stackoverflow.com/q/41570359
has body: I am trying to use cx_Freeze to make an executable for my program. Even though the python program works perfectly, the executable says it cant file file_cleaner. This is what the setup.py looks like import sys from cx_Freeze import setup, Executable import os.path PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__)) os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6') os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6') build_exe_options = {"packages": ["os", "glob", "itertools", "numpy", "matplotlib", "lmfit", "pandas", "scipy", "pathlib"], "includes": [ "src\\BCS_fit.py", "src\\file_cleaner.py", "src\\__init__.py", "src\\dependencies\\"], "include_files": ["test\\"]} base = None setup(name="BCS processor", version="0.1", description="Console application for processing VTS data and fitting it according to BCS theory", author="Anil Radhakrishnan", options={"build_exe": build_exe_options}, executables=[Executable("src\\Master.py", base=base)]) BCS_fit.py and file_cleaner.py are 2 other python files that I call from master.py. The Dependencies folder has .py and .pyd file from a c module converted to python. This is the first time I am trying to create an executable for a python script, please excuse any beginner errors. Thanks a lot for your assistance!
answer count: 1
tagged with: exe
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: build
score: 1
tagged with: executable
type: Question
has answer: http://stackoverflow.com/a/51526438

http://stackoverflow.com/comment/90097485
type: Comment
has text: I guess it would be `M[M < 3] *= 2` given the updated question.
score: 0
comment on: http://stackoverflow.com/a/51564739
type: AnswerComment

http://stackoverflow.com/comment/90025787
comment on: http://stackoverflow.com/q/51528617
type: Comment
type: QuestionComment
score: 1
has text: If a stack only offers push and pop operations, I don't understand what you mean by "conduct a binary search". How are you getting the items without popping?

scipy
tags question: http://stackoverflow.com/q/51508583
tags question: http://stackoverflow.com/q/51621411
tags question: http://stackoverflow.com/q/51482918
tags question: http://stackoverflow.com/q/51580218
tags question: http://stackoverflow.com/q/51563252
tags question: http://stackoverflow.com/q/51510635
tags question: http://stackoverflow.com/q/51637922
tags question: http://stackoverflow.com/q/51598353
tags question: http://stackoverflow.com/q/51580980
tags question: http://stackoverflow.com/q/51591212
tags question: http://stackoverflow.com/q/51512197
tags question: http://stackoverflow.com/q/51530882
tags question: http://stackoverflow.com/q/51565122
tags question: http://stackoverflow.com/q/51561786
type: Tag
tags question: http://stackoverflow.com/q/51564228
tag name: scipy
tags question: http://stackoverflow.com/q/51516644
tags question: http://stackoverflow.com/q/51602089
tags question: http://stackoverflow.com/q/51624061
tags question: http://stackoverflow.com/q/51553625
tags question: http://stackoverflow.com/q/51508218
tags question: http://stackoverflow.com/q/51563175
tags question: http://stackoverflow.com/q/51615540
tags question: http://stackoverflow.com/q/51522103
tags question: http://stackoverflow.com/q/51549347
tags question: http://stackoverflow.com/q/51528579
tags question: http://stackoverflow.com/q/51487479
tags question: http://stackoverflow.com/q/51637757
tags question: http://stackoverflow.com/q/51591209
tags question: http://stackoverflow.com/q/51513122
tags question: http://stackoverflow.com/q/51592831
tags question: http://stackoverflow.com/q/51617674
tags question: http://stackoverflow.com/q/51519111
tags question: http://stackoverflow.com/q/51625016
tags question: http://stackoverflow.com/q/51581025
tags question: http://stackoverflow.com/q/51637089
tags question: http://stackoverflow.com/q/51584607
tags question: http://stackoverflow.com/q/51536478
tags question: http://stackoverflow.com/q/51548826
tags question: http://stackoverflow.com/q/51570626
tags question: http://stackoverflow.com/q/51536111
tags question: http://stackoverflow.com/q/51604797
tags question: http://stackoverflow.com/q/51485146
tags question: http://stackoverflow.com/q/51492451
tags question: http://stackoverflow.com/q/51549293
tags question: http://stackoverflow.com/q/51601286
tags question: http://stackoverflow.com/q/51596966
tags question: http://stackoverflow.com/q/51534279
tags question: http://stackoverflow.com/q/51612755
tags question: http://stackoverflow.com/q/51505157
tags question: http://stackoverflow.com/q/51616762
tags question: http://stackoverflow.com/q/51570512
tags question: http://stackoverflow.com/q/51505071
tags question: http://stackoverflow.com/q/51578328
tags question: http://stackoverflow.com/q/51503398
tags question: http://stackoverflow.com/q/51498521
tags question: http://stackoverflow.com/q/51526800
tags question: http://stackoverflow.com/q/51486571
tags question: http://stackoverflow.com/q/51575947
tags question: http://stackoverflow.com/q/51528255
tags question: http://stackoverflow.com/q/51567086
tags question: http://stackoverflow.com/q/51489784
tags question: http://stackoverflow.com/q/51613581
tags question: http://stackoverflow.com/q/51607095
tags question: http://stackoverflow.com/q/51609003
tags question: http://stackoverflow.com/q/51616021
tags question: http://stackoverflow.com/q/51487626
tags question: http://stackoverflow.com/q/51565708
tags question: http://stackoverflow.com/q/51576736
tags question: http://stackoverflow.com/q/51561153
tags question: http://stackoverflow.com/q/51575544
tags question: http://stackoverflow.com/q/51637281
tags question: http://stackoverflow.com/q/51556755
tags question: http://stackoverflow.com/q/51494185
tags question: http://stackoverflow.com/q/51533442

http://stackoverflow.com/q/51592229
accepted answer: http://stackoverflow.com/a/51592322
has comment: http://stackoverflow.com/comment/90149755
type: AnsweredQuestion
upvote count: 0
has title: Each iteration replaces the previous?
has answer: http://stackoverflow.com/a/51592322
has comment: http://stackoverflow.com/comment/90149685
type: Question
has answer: http://stackoverflow.com/a/51592462
score: -2
has body: Also the last line gives: ValueError: I/O operation on closed file. import sys for i in range(1,123): if i%2 ==0: sys.stdout = open('log1.txt', 'w') print(i) sys.stdout.close() How to fix these things? About the first issue, only the last insertion is printed in the txt while it should show all the insertions. -UPDATE folder = path.Path(r"C:\Users\user\Desktop\SHAPE") shapefiles = [] for shpfile in glob.iglob('**/Desktop/SHAPE/**/' ,recursive = True): try: shapefiles.append(geopandas.read_file(shpfile)) except FionaValueError as ex: if not os.listdir(shpfile): sys.stdout = open('log.txt', 'w') print(f'{shpfile} is empty') can you tell me how to write this printed result to a txt?
possible better answer: http://stackoverflow.com/a/51592462
answer count: 2
downvote count: 2
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/90063632
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51547898
has text: With the information you provided, it is very difficult to suggest improvements

http://stackoverflow.com/comment/89954402
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51492868
has text: @Amadan Thanks. Makes sense now.
type: Comment

http://stackoverflow.com/a/51516770
upvote count: 1
score: 1
downvote count: 0
has body: Those characters are special in regular expressions and need to be escaped. Try with this: import re s = '100000|^104,500|^^0^0^0^0^0^0^0|^^^^^^^^^412824|103000|103000|103000|103000^^' nums = re.split(r'\|\^{9}', s)[1] # Find all integers and sum total = sum(map(int, re.findall(r'\d+', nums))) print(total) Output: 824824
answers question: http://stackoverflow.com/q/51516628
type: Answer

http://stackoverflow.com/a/51577858
has body: I checked your URL and not &lt;td&gt; tags, but rows, &lt;tr&gt; with align=right contain useful data. To extract them, you can use following snippet: yr_table = [] for i in player_count_list: url = url_base + str(i) print(url) with urlopen(url) as page: html_doc = bS(page, 'html5lib') for tr in html_doc.select('tr[align="right"]'): new_strings = [] for td in tr.find_all('td'): new_strings.append(td.text.strip()) yr_table.append(new_strings) pprint(yr_table, width=180) # from pprint import pprint Will print for example: http://www.espn.com/nhl/statistics/player/_/stat/points/sort/points/year/2007/count/0 [['RK', 'PLAYER', 'TEAM', 'GP', 'G', 'A', 'PTS', '+/-', 'PIM', 'PTS/G', 'SOG', 'PCT', 'GWG', 'G', 'A', 'G', 'A'], ['1', 'Sidney Crosby, C', 'PIT', '79', '36', '84', '120', '10', '60', '1.52', '250', '14.4', '4', '13', '48', '0', '0'], ['2', 'Joe Thornton, C', 'SJ', '82', '22', '92', '114', '24', '44', '1.39', '213', '10.3', '5', '10', '44', '0', '0'], ['3', 'Vincent Lecavalier, C', 'TB', '82', '52', '56', '108', '2', '44', '1.32', '339', '15.3', '7', '16', '20', '5', '4'], ['4', 'Dany Heatley, LW', 'OTT', '82', '50', '55', '105', '31', '74', '1.28', '310', '16.1', '10', '17', '22', '3', '1'], ['5', 'Martin St. Louis, RW', 'TB', '82', '43', '59', '102', '7', '28', '1.24', '273', '15.8', '7', '14', '16', '5', '6'], ['6', 'Marian Hossa, RW', 'ATL', '82', '43', '57', '100', '18', '49', '1.22', '340', '12.6', '5', '17', '27', '3', '1'], ['', 'Joe Sakic, C', 'COL', '82', '36', '64', '100', '2', '46', '1.22', '258', '14.0', '4', '16', '27', '0', '0'], ['8', 'Jaromir Jagr, RW', 'NYR', '82', '30', '66', '96', '26', '78', '1.17', '324', '9.3', '5', '7', '34', '0', '0'], ['', 'Marc Savard, C', 'BOS', '82', '22', '74', '96', '-19', '96', '1.17', '221', '10.0', '3', '10', '39', '1', '0'], ['10', 'Daniel Briere, C', 'BUF', '81', '32', '63', '95', '17', '89', '1.17', '234', '13.7', '6', '9', '21', '0', '0'], ['RK', 'PLAYER', 'TEAM', 'GP', 'G', 'A', 'PTS', '+/-', 'PIM', 'PTS/G', 'S…
accepted answer of: http://stackoverflow.com/q/51577228
score: 0
answers question: http://stackoverflow.com/q/51577228
type: Answer
has comment: http://stackoverflow.com/comment/90128902
type: AcceptedAnswer

http://stackoverflow.com/comment/89991850
has text: and `d.items()[0]` returns `IndexError` same as `.keys()`
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51511661

http://stackoverflow.com/comment/90037528
has text: What do you mean with "cluster" here?
comment on: http://stackoverflow.com/q/51534890
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90170937
type: AnswerComment
comment on: http://stackoverflow.com/a/51602350
type: Comment
has text: Also, `fill_type` isn't the sixteenth argument. `Color` just has a very confusing `__repr__` that places a lot of stuff outside the angle brackets, making it look like those are parameters for `PatternFill`.
score: 1

http://stackoverflow.com/q/51506252
has title: Python / numpy: How to replace matrix elements with specified length along axis
has answer: http://stackoverflow.com/a/51506343
has comment: http://stackoverflow.com/comment/89981582
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51506343
has body: I have an array that specifies how many elements along the last axis of a matrix I want to change to 0. How do I do this efficiently? x = np.ones((4, 4, 10)) change_to_zeros = np.random.randint(10, size=(4, 4)) # change_to_zeros = # [[2 1 6 8] # [4 0 4 8] # [7 6 6 2] # [4 0 7 1]] Now what I want to do is something like x[:, :, :change_to_zeros] = 0 - for example for the first element of change_to_zeros, I have change_to_zeros[0, 0] = 2 so I want to change the first (or last, or whatever) 2 elements along the last axis of x (length 10) to 0. Clarification: For example at x[0, 0, :] I have ones with length 10. I want to change 2 of these (change_to_zeros[0, 0] = 2) to 0, keeping the rest with ones.
tagged with: python
has comment: http://stackoverflow.com/comment/89981639
type: AnsweredQuestion
type: Question
tagged with: numpy

http://stackoverflow.com/comment/90125127
type: AnswerComment
type: Comment
has text: Since the parameters could be long
comment on: http://stackoverflow.com/a/51579818
score: 0

http://stackoverflow.com/a/51607572
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51587656
type: Answer
has body: This solved issue, Thanks FlyingTeller An example of y=x**3 graph: import pylab import numpy x = numpy.linspace(-15,15,100) # 100 linearly spaced numbers y = x**3 # we change this to tracer graphs as we want # compose plot pylab.plot(x,y) pylab.show()
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51587656
type: AcceptedAnswer

http://stackoverflow.com/q/51531713
has answer: http://stackoverflow.com/a/51533000
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51532440
score: 0
has body: I know they practically do the same thing, but if you were to lets say do something like... curpop = this_other_ndarray i = 0; while i&lt;20: curpop[:] = select(curpop, parameter, parameter1) stuff more stuff curpop[:] = some_stuff_I_did i += 1; So the above code is just saying, before I enter a generational loop I am going to take an initial generation of populations from 'this other ndarray'. Then I am planning on changing that array over and over and everytime I restart the loop I will only select some from itself but I will declare that as what it is equal to now. Is this okay to do in Python3? Is the declaration of 'array[:] = some of it self' versus 'array = some of itself' different at all?
tagged with: python-3.x
type: UnansweredQuestion
has title: Difference between 'array[:] = something' and 'array = something'
has comment: http://stackoverflow.com/comment/90031599
tagged with: python

http://stackoverflow.com/a/51523332
has comment: http://stackoverflow.com/comment/90194773
has comment: http://stackoverflow.com/comment/90139223
has comment: http://stackoverflow.com/comment/90207445
has comment: http://stackoverflow.com/comment/90018855
score: 1
has comment: http://stackoverflow.com/comment/90142871
has comment: http://stackoverflow.com/comment/90134162
has body: You need to use use related fields and relate discount_type and discount on purchase.order.line to the purchase.order. For example: discount = fields.Float(related="order_id.global_order_discount") Update discount and discount_type for each line when global_order_discount and global_discount_type respectively: @api.onchange('global_order_discount', 'global_discount_type') def onchange_field(self): for line in self.order_line: line.discount = self.global_order_discount line.discount_type = self.global_discount_type
downvote count: 0
answers question: http://stackoverflow.com/q/51518500
has comment: http://stackoverflow.com/comment/90189649
has comment: http://stackoverflow.com/comment/90140999
has comment: http://stackoverflow.com/comment/90131770
type: Answer
has comment: http://stackoverflow.com/comment/90058888
has comment: http://stackoverflow.com/comment/90214647
has comment: http://stackoverflow.com/comment/90142924
has comment: http://stackoverflow.com/comment/90138996
upvote count: 1
has comment: http://stackoverflow.com/comment/90206420

http://stackoverflow.com/comment/90056207
comment on: http://stackoverflow.com/q/51542994
score: 1
has text: Does pip work at all on your system?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90117774
type: QuestionComment
comment on: http://stackoverflow.com/q/51570995
score: 0
has text: I am sure that is not the correct library, also that is not how you install it. With the level of knowledge you have it would be easiest to Uninstaller your python and then download ana/miniconda. Then use `conda install av`
type: Comment

http://stackoverflow.com/comment/90097017
comment on: http://stackoverflow.com/q/51565019
score: 0
type: Comment
type: QuestionComment
has text: https://httpstatuses.com/ Status 404 means page not found. So whatever URL you're trying to access does not exist.

http://stackoverflow.com/q/51621535
has comment: http://stackoverflow.com/comment/90209254
tagged with: email
downvote count: 1
has title: Saving email from Outlook into folder with Python
has comment: http://stackoverflow.com/comment/90208892
has comment: http://stackoverflow.com/comment/90208990
favorite count: 0
has answer: http://stackoverflow.com/a/55969280
upvote count: 5
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90209516
has comment: http://stackoverflow.com/comment/90208911
has answer: http://stackoverflow.com/a/52471487
has answer: http://stackoverflow.com/a/51622523
type: Question
tagged with: outlook
has comment: http://stackoverflow.com/comment/90209017
has comment: http://stackoverflow.com/comment/90208541
score: 4
has comment: http://stackoverflow.com/comment/90210305
answer count: 3
linked to: http://stackoverflow.com/q/22399835
has body: I'm trying to automate saving emails in our folders from outlook. I don't see a code for saving an email as .msg or any other type. import win32com.client import os os.chdir("filepathhere") outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") accounts= win32com.client.Dispatch("Outlook.Application").Session.Accounts; Tokyo = "email from Tokyo" inbox = outlook.GetDefaultFolder(6) subject = Tokyo messages = inbox.Items message = messages.GetFirst() for msg in messages: if msg.subject == Tokyo: msgname = msg.subject msgname=str(msgname) print msgname message.saveasfile(msgname+".msg") I get the error message: AttributeError: .saveasfile

http://stackoverflow.com/comment/90239159
has text: Actually your answer is more accurate...I don't know why crosstab doesn't give me the correct result, maybe it is cumulative?
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51637215

http://stackoverflow.com/comment/90121411
type: AnswerComment
has text: Ohhh, and then just assign the `myPlayer` to one of the classes? If so, that solution actually makes a TON of sense! Thank you.
comment on: http://stackoverflow.com/a/51578008
type: Comment
score: 1

http://stackoverflow.com/comment/90151435
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51592945
has text: @jonrsharpe I will try that out. is that a typo in your comment too? 'In' instead of 'for key n dictyy' ?

http://stackoverflow.com/comment/90183695
has text: @Codevan - Added solution for dict, for write dictionary to file and for read this file to dictionary again.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51608602
type: Comment

http://stackoverflow.com/a/51573691
has comment: http://stackoverflow.com/comment/90118099
has body: If it's really just to do what you say, you could set the facecolor of the rectangle to white, and the zorder of the circle to 0 so it gets plotted behind: def plot_pic(ax=None, color='black', lw=2, scale = 15): # get the current ax if ax is None if ax is None: ax = plt.gca() # Plot the rectangle rec = Rectangle((-(7.32 * scale / 2+ 5.5 * scale +11 * scale),0), width = (5.5 * scale * 2 + 11 * scale * 2 + 7.32 * scale), height = 16.5 * scale, linewidth = lw, color = color, fc='white') testCircle = Circle((0, 11 * scale), radius = 9.15 * scale, color = color, lw = lw, fill = False, zorder=0) # List of elements to be plotted pic_elements = [rec, testCircle] # Add the elements onto the axes for element in pic_elements: ax.add_patch(element) return ax
has comment: http://stackoverflow.com/comment/90187054
has comment: http://stackoverflow.com/comment/90133316
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51573606
accepted answer of: http://stackoverflow.com/q/51573606
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90185938

http://stackoverflow.com/q/51626973
tagged with: matlab
type: AnsweredQuestion
has title: EngineError: Transport stopped. by using MATLAB Engine for Python after activation of MATLAB
upvote count: 1
linked to: http://stackoverflow.com/q/50488997
type: Question
score: 1
has answer: http://stackoverflow.com/a/51668717
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51668717
has body: I installed the MATLAB Engine according to this solution and it also start, but by executing it, the following error occurs: Traceback (most recent call last): File "&lt;ipython-input-1-7f0848dd34ed&gt;", line 1, in &lt;module&gt; runfile('/media/geodasie/dat/Dennis/Python/PythonProgram/CryoSat2_main_Test.py', wdir='/media/geodasie/dat/Dennis/Python/PythonProgram') File "/home/geodasie/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/home/geodasie/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/media/geodasie/dat/Dennis/Python/PythonProgram/CryoSat2_main_Test.py", line 288, in &lt;module&gt; eng = matlab.engine.start_matlab() # start Matlab File "/home/geodasie/anaconda3/lib/python3.6/site-packages/matlab/engine/__init__.py", line 115, in start_matlab eng = future.result() File "/home/geodasie/anaconda3/lib/python3.6/site-packages/matlab/engine/futureresult.py", line 67, in result return self.__future.result(timeout) File "/home/geodasie/anaconda3/lib/python3.6/site-packages/matlab/engine/matlabfuture.py", line 87, in result handle = pythonengine.getMATLAB(self._future) EngineError: Transport stopped. The code sequence, in which the error occurs is this one: Path_year = fileName[19:23] + '/' Path_month = fileName[23:25] + '/' # read DBL file with the help of the Matlab function provided by ESA eng = matlab.engine.start_matlab() # start Matlab DATA = eng.main_read(path_saveFilefromFTP + Path_year + Path_month + fileName) # run matlab script eng.quit() # end Matlab This code was already running on another pc, but sadly on this one the error occurs. I installed the MATLAB Engine several times but the result is the same. According to the futureresult.py function which is called, the timeout is the number of seconds it waits before returning a result. But per default the function w…
tagged with: python
tagged with: matlab-engine

http://stackoverflow.com/q/51535102
has title: converting hex string to ascii
has comment: http://stackoverflow.com/comment/90768967
score: 0
answer count: 1
tagged with: python-2.x
tagged with: hex
linked to: http://stackoverflow.com/q/6624453
tagged with: encode
tagged with: python
has answer: http://stackoverflow.com/a/51535181
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51535181
type: Question
has body: I have a string that looks like \x01\x03\x00\x00\x00\x01\x00\x00\x00\x1f\x00\x00\x00q~5\xf1\xacHhA\xd7[\x18&gt;\x9erCA\x13\xf5Q\xa3\xadHhA\x17V\xde\x9f\x97rCA\xeb\x8a\x90\xea\xadHhA\x11\x1e\xaf5\x92rCA\xeb\x8a\x90\xea\xadHhA\xad\x8c\x8a\xff\x8drCA\xd7\xd5/\x0e\xaeHhA\xedPkc\x8arCAY\xe2\x8a\x07\xafHhAj|7_\x84rCA\x0f\x0e\x08\x96\xafHhA\x93\xcc\xfe\xc0}rCA\xe7\xa3F\xdd\xafHhAQ\xac\xd0VxrCA\xe7\xa3F\xdd\xafHhA\x80%\xb7TurCA\x0f I'd like to convert it to binary encoded hex like 0102000020110F0000B802000060CB38045D344E4167866F87E25C4D41C88730520F344E4133683205B35C4D41A6719BE3C2334E41F2A9DA95665C4D41A2D14537D1334E415CFC777B285C4D41528DB9E018344E4180C29B0A075C4D4117D477C186344E41C1E177EEF35B4D41D83AC468F9344E41B9C5ECB5F85B4D41FED020BD32354E4178A8C9EEC85B4D4188F6371241354E41A60F877E7C5B4D41FDF0AE8337354E41AF16059E0E5B4D41EE45D6850C354E41B0F6E4D9B35A4D41B2644B87B6344E41ACAEE167 in python 2.7 As an added bonus, anyone know whats the q~5\xf1\xacHhA\xd7[\x18&gt;\ part that doesn't look like hex :/

http://stackoverflow.com/comment/90121487
type: QuestionComment
has text: what does it mean to be **optimal**?
score: 1
comment on: http://stackoverflow.com/q/51578000
type: Comment

http://stackoverflow.com/q/51626333
has title: Passing arguments to a list of functions in Pandas GroupBy `agg()`
type: AnsweredQuestion
has body: I am trying to find the min, max, mean, sum and std of some columns of GroupBy object in Pandas. To do that my original code was this: df_agg = df.groupby('id')[column_list].agg(['mean', 'max', 'min', 'sum', 'std']) But this was producing a lot of NaNs in the std columns. Upon searching, I found that std accepts an argument - ddof(Delta Degrees of Freedom) - which is set to 1 by default. This was causing a division by 0 error and giving those NaN values. Now, I want to send an argument ddof=0 in the std that is used in the above code but I don't understand how I can do that. Please help.
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51626358
type: Question
tagged with: pandas
score: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/51626358
answer count: 1
upvote count: 3

http://stackoverflow.com/q/51512052
has comment: http://stackoverflow.com/comment/89994249
tagged with: ssl-certificate
has comment: http://stackoverflow.com/comment/89992525
favorite count: 0
answer count: 0
has title: How to import OpenSSL in Python to fetch the serial number of the certificate
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: pyopenssl
has comment: http://stackoverflow.com/comment/89992791
score: 1
has comment: http://stackoverflow.com/comment/89994022
type: Question
downvote count: 0
has body: I have a certificate and i used the regular expression to strip the beginning and ending from certificate. How can i decode the serial number of the certificate using OpenSSL. I have the cli command to decode: openssl x509 -serial -noout how can fetch it from Python

http://stackoverflow.com/comment/90234836
comment on: http://stackoverflow.com/a/51560259
score: 0
type: Comment
has text: @wigging where did you start the ipython server, and did you modify your path before, while, or since using ipython?
type: AnswerComment

http://stackoverflow.com/a/54455559
score: 1
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51491307
has body: Please create a virtual environment and then install tensorflow into that. It works fine.

http://stackoverflow.com/a/51633058
answers question: http://stackoverflow.com/q/51589068
score: 1
upvote count: 1
has body: Turns out that ALT + / also works in PyCharm.
type: Answer
downvote count: 0

http://stackoverflow.com/q/51563552
downvote count: 0
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51564073
has answer: http://stackoverflow.com/a/51563679
has title: Aggregate unique values in list to new list
type: Question
upvote count: 1
has body: Trying to find the best way to aggregate values (value pairs) from a list in python. foo = [ {'color': 'yellow', 'type': 'foo'}, {'color': 'yellow', 'type': 'bar'}, {'color': 'red', 'type': 'foo'}, {'color': 'red', 'type': 'foo'}, {'color': 'green', 'type': 'foo'}, {'color': 'red', 'type': 'bar'} ] end goal is something like newFoo = [ {'color': 'yellow', 'type': 'foo', 'count': 1}, {'color': 'yellow', 'type': 'bar', 'count': 1}, {'color': 'red', 'type': 'foo', 'count': 2}, {'color': 'red', 'type': 'bar', 'count': 1}, {'color': 'green', 'type': 'foo', 'count': 1} ] I'm not very good with python but have been trying to accomplish it sort of but this is about as far as I can get: def loop(ar): dik = [] for line in ar: blah = [] for k,v in line.items(): blah.append({k,v}) blah.append({'count':'1'}) dik.append(blah) print(dik) any help appreciated.
has comment: http://stackoverflow.com/comment/90094246
has answer: http://stackoverflow.com/a/51563699
favorite count: 0
has answer: http://stackoverflow.com/a/51564350
tagged with: python
answer count: 4

http://stackoverflow.com/comment/90203750
type: QuestionComment
comment on: http://stackoverflow.com/q/51602694
has text: Can you share the Excel file? Or create a similar one with the same effect that you can share?
score: 0
type: Comment

http://stackoverflow.com/a/68183863
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51540404
has body: pip install -U pipenv solved for me on Ubuntu 21.04 - Hirsute Hippo - python Version 3.9.5 This command installed those packages: appdirs-1.4.4 certifi-2021.5.30 distlib-0.3.2 filelock-3.0.12 pipenv-2021.5.29 six-1.16.0 virtualenv-20.4.7 virtualenv-clone-0.5.4
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/51568501
has body: I try to capture my screen using python and see any movement in my screen. The screen is been captured always and updated. Here is my code: import numpy as np import cv2 from PIL import ImageGrab while(True): screen = np.array(ImageGrab.grab(bbox=(0,40,800,640))) cv2.imshow('window', cv2.cvtColor(screen, cv2.COLOR_BGR2RGB)) if cv2.waitKey(25) &amp; 0xFF == ord('q'): cv2.destroyAllWindows() break And this is the result (kind of nesting images inside..): So.. where am I wrong in the code?
tagged with: python-3.5
has answer: http://stackoverflow.com/a/51568539
answer count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51568539
score: 0
type: Question
tagged with: opencv
has title: How to capture my screen with python properly?
tagged with: python-imaging-library

http://stackoverflow.com/comment/90188225
score: 0
comment on: http://stackoverflow.com/q/51611715
type: Comment
type: QuestionComment
has text: Can it be that you are receiving stderr output?

http://stackoverflow.com/comment/90178736
score: 0
has text: I'm not familiar with the technologies mentioned but it sounds more like you have multiple threads, not multiprocessing. You can see if there is an option to create a process pool.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51606105

http://stackoverflow.com/comment/89992011
comment on: http://stackoverflow.com/q/51511714
has text: `key=(lambda x:int(x[0]))`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90059727
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51529556
has text: The code is really long, the error it gives me is that MyStream() has no attribute flush. Does that help ?
score: 0

http://stackoverflow.com/comment/90028953
comment on: http://stackoverflow.com/q/51530358
has text: The shell would expand the wildcard into all matching filenames. Your python script would receive each individual filename in `argv`. Well, in Unix it would; I'm not sure about DOS/Windows...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51618455
answers question: http://stackoverflow.com/q/51618025
accepted answer of: http://stackoverflow.com/q/51618025
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/90203925
has body: Have you tried this: col = 'current' minVal = -380 maxVal = -360 begin = df.loc[np.logical_and(df[col]&lt;maxVal, df[col]&gt;minVal)].index[0] end = df.loc[np.logical_and(df[col]&lt;maxVal, df[col]&gt;minVal)].index[-1] What it basically does is select all the values in your given range and get the min index and max index. Note that noisy data points may cause problems.
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90268626
type: Comment
has text: thank you sir for your reply,but timer is not showing any values on the button
comment on: http://stackoverflow.com/a/51627317
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90492730
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51535808
score: 1
has text: @Naveen Not yet bro. I created a temporary table and used Many2one field instead of Selection field.

http://stackoverflow.com/a/51590487
downvote count: 0
has body: You need a complete 3D slice and hence you should be using images[:,:,0]. i.e imgplot = plt.imshow(images[:,:,0]) which gives:
type: Answer
score: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51589678
upvote count: 3
answers question: http://stackoverflow.com/q/51589678

http://stackoverflow.com/comment/90005410
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51510959
has text: Is it always less when it's different?
score: 0

http://stackoverflow.com/comment/90139635
has text: Yes @WillemVanOnsem I'm trying to extract log but not getting exact log which is to be useful
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51559555

http://stackoverflow.com/comment/95501496
has text: For production environments, the [`--deploy`](https://pipenv.readthedocs.io/en/latest/#cmdoption-pipenv-install-deploy) option is also useful: "Abort if the Pipfile.lock is out-of-date, or Python version is wrong.".
type: Comment
comment on: http://stackoverflow.com/a/54342856
type: AnswerComment
score: 1

while-loop
tags question: http://stackoverflow.com/q/51554322
type: Tag
tags question: http://stackoverflow.com/q/51568034
tags question: http://stackoverflow.com/q/51497066
tags question: http://stackoverflow.com/q/51572195
tags question: http://stackoverflow.com/q/51575909
tags question: http://stackoverflow.com/q/51555288
tags question: http://stackoverflow.com/q/51586625
tags question: http://stackoverflow.com/q/51528810
tags question: http://stackoverflow.com/q/51502090
tags question: http://stackoverflow.com/q/51553280
tags question: http://stackoverflow.com/q/51548364
tag name: while-loop

http://stackoverflow.com/a/51488358
has comment: http://stackoverflow.com/comment/89945755
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51488111
downvote count: 0
answers question: http://stackoverflow.com/q/51488111
upvote count: 2
has body: I don't know, why this bug happens.* But you can enforce autoscale. If you want to autoscale only one axis, you can specify it: #not messed up anymore import pandas as pd df = pd.DataFrame([range(1, 4)] * 5, columns=list('ABC')).assign(B=lambda d: -d.B).cumsum() df.C.plot.area(stacked=False) df.A.plot() df.B.plot() plt.autoscale(True, axis = "y") plt.show() Output: *As @ImportanceOfBeingErnest points out in the comments, it is not a bug but the desired behavior for area plots, which unluckily collides with the line plot here.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89945717

http://stackoverflow.com/q/51541359
answer count: 2
tagged with: pandas
tagged with: xgboost
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51541471
tagged with: python
has body: I have a directionary of json files to read, so I use the following code: test_filelist = os.listdir('myDir') df_test_list = [pd.read_json( os.path.join('myDir',file),lines=True ) for file in test_filelist if file.endswith('json') ] df_test = pd.concat(df_test_list) The total size of my directionary is 4.5G, but when I use top to check the memory that my process use, I find that this process use 30G when the read was done. Why this happen? I only read 4.5G json files, but 30G memory had been used, how to avoid this ? I printed the df_test.info(), it told me that this dataframe only use 177.7 MB memory, why?
score: 1
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51541414
tagged with: machine-learning
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/39100971
downvote count: 0
has title: Why my pandas dataframe use so many memory?

http://stackoverflow.com/q/51619195
accepted answer: http://stackoverflow.com/a/51620445
type: Question
answer count: 2
tagged with: visual-studio-code
linked to: http://stackoverflow.com/q/51601594
has title: How can I set up a python environment path for executable and libraries in Visual Studio Code
score: 0
tagged with: windows
has answer: http://stackoverflow.com/a/51623648
has body: I am not a python programmer, and I got tasked with using existing python code that comes shipped with its own python executable (as I understand its called interpreter) and its own python modules. I understand this is what defines a python environment, except that there is no env/scripts folder or env.txt file. I just have the version of python and separately in another folder I have the modules. What I would like to do is create a Visual Studio Code project/workspace that uses that python.exe to run and debug, and has a reference to the folder that has the python modules. I cannot find this option to configure paths anywhere in Visual Studio code. I tried doing this in Visual Studio 2017, but it refused to use the path I provided to the modules. This is my original question for Visual Studio, it was unanswered so I decided to try Visual Studio code Python in Visual Studio 2017 fails to find modules via the Seath Paths If this is not possible, and I need to set up some scripts or it to use the directory for the modules and a directory for the interpreter, I can do this, but I cannot find any tutorials on setting it up, and documentation is scarce and unreliable. Is there a tool which can set up the environment, so I don't have to write any scripts by hand?
has answer: http://stackoverflow.com/a/51620445
possible better answer: http://stackoverflow.com/a/51623648
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90017122
score: 0
comment on: http://stackoverflow.com/q/51524151
type: Comment
type: QuestionComment
has text: You need a python interpreter to open .py files

http://stackoverflow.com/q/51567750
has answer: http://stackoverflow.com/a/64450523
score: 17
has title: Extract specific pages of PDF and save it with Python
has answer: http://stackoverflow.com/a/75696102
linked to: http://stackoverflow.com/q/49939085
tagged with: http://stackoverflow.com/tag/pdf
upvote count: 17
has answer: http://stackoverflow.com/a/75909038
favorite count: 0
tagged with: extract
tagged with: python
possible better answer: http://stackoverflow.com/a/64450523
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51885963
accepted answer: http://stackoverflow.com/a/51885963
downvote count: 0
tagged with: pypdf
has body: I have some sources and tried to code which extract some pages and create pdf files. I have a list which looks like this information = [(filename1,startpage1,endpage1), (filename2, startpage2, endpage2), ...,(filename19,startpage19,endpage19)]. This is my code. from PyPDF2 import PdfFileReader, PdfFileWriter reader = PdfFileReader("example.pdf") for page in range(reader.getNumPages() - 1): writer = PdfFileWriter() start = information[page][1] end = information[page][2] while start < end: writer.addPage(reader.getPage(start)) start += 1 output_filename = "{}_{}_page_{}.pdf".format( information[page][0], information[page][1], information[page][2] ) with open(output_filename, "wb") as out: writer.write(out) But the output is weird.. some has nothing inside and some has just one page in it. How can I correct this?
has comment: http://stackoverflow.com/comment/133892318
type: Question

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/51502812
type: Tag
tags question: http://stackoverflow.com/q/51547183
tags question: http://stackoverflow.com/q/51526263

http://stackoverflow.com/comment/90060187
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51545528
score: 0
has text: There are a few post already about this exact problem. [here](https://stackoverflow.com/questions/731887/resetting-the-main-gui-window) and [here](https://stackoverflow.com/questions/41655618/restart-program-tkinter). Probably a good place to start.

http://stackoverflow.com/comment/89974115
score: 0
type: Comment
has text: Yes my bad it should be `262142`
type: AnswerComment
comment on: http://stackoverflow.com/a/51502565

http://stackoverflow.com/q/51612755
type: AnsweredQuestion
tagged with: matplotlib
tagged with: scipy
possible better answer: http://stackoverflow.com/a/51612886
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51612886
has body: I want to display Heavy Tailed (Levy) distribution with Gaussian (in same plot). I did it for Gauss: from pylab import plot, show, grid, axis, xlabel, ylabel, title, rcParams import matplotlib.pyplot as plt import numpy as np import matplotlib.mlab as mlab import math mu = 0 variance = 1 sigma = math.sqrt(variance) plt_z = np.linspace(-4, 4, 100) 1./(np.sqrt(2*np.pi)*sigma)*np.exp(-0.5 * (1./sigma*(x - mu))**2) plt.plot(plt_z, mlab.normpdf(plt_z, mu, sigma)) plt.show() and I get Now I want to add Levy distribution in that plot, but not getting it right. I tried with scipy.stats.levy and manually adding equation: 1./(x * np.sqrt(2*np.pi*x)) * np.exp(-1/(2*x)) but not getting correct plot This is what i want to get: just heavy tailed Levy distribution in same plot
has title: Heavy tailed and Normal distribution in same plot
has comment: http://stackoverflow.com/comment/90190277
tagged with: statistics
score: 0
has answer: http://stackoverflow.com/a/52386331
has comment: http://stackoverflow.com/comment/90190460
tagged with: python
accepted answer: http://stackoverflow.com/a/52386331

http://stackoverflow.com/q/51584574
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90134885
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90134732
has comment: http://stackoverflow.com/comment/90134856
type: Question
has comment: http://stackoverflow.com/comment/90134714
has comment: http://stackoverflow.com/comment/90134908
has title: Python 3, 2D List - Adjust Values of Neighboring Cells (Homework)
score: 0
has comment: http://stackoverflow.com/comment/90134779
has body: NOTE: I can not import anything like pygame or numpy. Working on a version of Conway's Game of Life, and I was able to get a "U" shape moving around. At this point I've got no clue on how to adjust values of the neighboring cells, or if it's even possible with my code. In the function "setInitialPatternList" I've added if statements to print out "PASS" to see if I'm on the right track. From what it's printing out, I can tell it's not looking at all of the "X"s I have individually. I'm unsure of where to go at this point, or if my "if" functions in "setInitialPatternList" need to be moved elsewhere. I need help trying to figure out how I can adjust the cells neighboring the "X"s on the board. from random import randint from os import system MAX_ROW = 30 MAX_COL = 60 currentGen = [] tempGen = [] def displayMenu(): print("[P]lay – Press 'P' to play.") print("[Q]uit – Press 'Q' to exit.\n") def setZeroList(listName): for row in range(MAX_ROW): for col in range(MAX_COL): listName[row][col] = "." def setInitialPatternList(listToFormat): rowChoice = randint(0,MAX_ROW-7) columnChoice = randint(0,MAX_COL-7) for foundation in range(1,7): listToFormat[rowChoice + foundation][columnChoice] = "X" listToFormat[rowChoice + foundation][columnChoice + 6] = "X" listToFormat[rowChoice + 6][columnChoice + foundation] = "X" counter = 0 if listToFormat[rowChoice + 1][columnChoice] == "X": print("Check1") if listToFormat[rowChoice - 1][columnChoice] == "X": print("Check2") if listToFormat[rowChoice][columnChoice + 1] == "X": print("Check3") if listToFormat[rowChoice][columnChoice - 1] == "X": print("Check4") if listToFormat[rowChoice + 1][columnChoice + 1] == "X": print("Check5") if listToFormat[rowChoice + 1][columnChoice - 1] == "X": print("Check6") if listToFormat[rowChoice - 1][columnChoice - 1] == "X": print("Check7") if listToFormat[rowChoice - 1][columnChoice + 1] == "X": print("Check8") if counter == 0: print("Counter Check") def copyList(tempList, currentList): for row in range(M…
has comment: http://stackoverflow.com/comment/90134741
tagged with: python-3.x
tagged with: conways-game-of-life

http://stackoverflow.com/comment/89985893
has text: Round() is not differentiable, causing errors in Keras when Keras tries to compute gradient it seems. However Relu is not differentiable but it works fine as everyone knows, so maybe there is similarly a way to get Round to make Keras happy.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51486073

http://stackoverflow.com/comment/90038867
type: QuestionComment
type: Comment
score: 0
has text: How do I use git clone? Please tell me because I really don't know much about this
comment on: http://stackoverflow.com/q/51535431

http://stackoverflow.com/a/51529576
downvote count: 0
type: Answer
has body: x = ['subdir{}'.format(i) for i in range(100)] max(x, key=lambda n: int(n[6:])) The max function will sort lexicographically, but that will place '99' after '100' (9 > 1). So first extract the integer part (n[6:]), convert to an int, and get the max from there.
upvote count: 1
answers question: http://stackoverflow.com/q/51529531
score: 1

http://stackoverflow.com/comment/90056804
has text: Please check your variable names. None of this will work. Paste your own code into an interpreter after you paste it in here.
comment on: http://stackoverflow.com/q/51544453
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51485188
has comment: http://stackoverflow.com/comment/89940210
has comment: http://stackoverflow.com/comment/89940065
upvote count: 2
has comment: http://stackoverflow.com/comment/89940503
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89940627
has comment: http://stackoverflow.com/comment/89940637
has comment: http://stackoverflow.com/comment/89939927
has comment: http://stackoverflow.com/comment/89939728
has comment: http://stackoverflow.com/comment/89940572
has comment: http://stackoverflow.com/comment/89940679
type: Answer
has comment: http://stackoverflow.com/comment/89940160
has comment: http://stackoverflow.com/comment/89940423
has comment: http://stackoverflow.com/comment/89940847
has comment: http://stackoverflow.com/comment/89940525
accepted answer of: http://stackoverflow.com/q/51484970
has comment: http://stackoverflow.com/comment/89940138
has comment: http://stackoverflow.com/comment/89940334
score: 2
has comment: http://stackoverflow.com/comment/89940945
answers question: http://stackoverflow.com/q/51484970
downvote count: 0
has body: Just setting categorical variables as dtype="category" is not sufficient and won't work. You need to convert categorical values to true categorical values with pd.factorize(), where each category is assigned a numerical label. Let's say df is your pandas dataframe. Then in general you could use this boilerplate code: df_numeric = df.select_dtypes(exclude=['object']) df_obj = df.select_dtypes(include=['object']).copy() # factorize categoricals columnwise for c in df_obj: df_obj[c] = pd.factorize(df_obj[c])[0] # if you want to one hot encode then add this line: df_obj = pd.get_dummies(df_obj, prefix_sep='_', drop_first = True) # merge dataframes back to one dataframe df_final = pd.concat([df_numeric, df_obj], axis=1) Since your categorical variables already are factorized (as far as I understand), you can skip the factorization and just try one hot encoding. See also this post on stats.stackexchange. If you want to standardize/normalize your numerical data (not the categorical) use this function: from sklearn import preprocessing def scale_data(data, scale="robust"): x = data.values if scale == "minmax": scaler = preprocessing.MinMaxScaler() x_scaled = scaler.fit_transform(x) elif scale == "standard": scaler = preprocessing.StandardScaler() x_scaled = scaler.fit_transform(x) elif scale == "quantile": scaler = preprocessing.QuantileTransformer() x_scaled = scaler.fit_transform(x) elif scale == "robust": scaler = preprocessing.RobustScaler() x_scaled = scaler.fit_transform(x) data = pd.DataFrame(x_scaled, columns = data.columns) return data scaled_df = scale_data(df_numeric, "robust") Putting it all together for your dataset: from sklearn import preprocessing df = pd.read_excel("default of credit card clients.xls", skiprows=1) y = df['default payment next month'] #target variable del df['default payment next month'] c = [2,3,4] # index of categorical data columns r = list(range(0,24)) r = [x for x in r if x not in c] # get list of all other columns df_cat = df.iloc[:, […

http://stackoverflow.com/comment/90004628
type: QuestionComment
has text: this driver setup was included as a pre-requestie with in my Release_setup.exe. everytime i run the release setup, i want the driver installation without user intervention using python
comment on: http://stackoverflow.com/q/51499021
score: 0
type: Comment

http://stackoverflow.com/q/51582436
answer count: 1
has comment: http://stackoverflow.com/comment/90130424
has body: attributes = {"Health": 0, "Strength": 0, "Dexterity": 0, "Intelligence": 0} points = 40 def add_points(attributes): type = input("Which attribute would you like to adjust?: ") if type in attributes: how_many = int(input("Add how many points?: ")) if how_many &lt;= points: type += how_many return type add_points(attributes) Some context. The code above is a piece of my character creator program I am building. I have the entire program written, however I want to use a function rathre than typing a bunch of loops. Trying to make my code more concise and Pythonic. I cannot figure out how to take the value of whatever key is chosen by the user and add x amount of points (also chosen by the user) to the value assigned to said key. Any help would be greatly appreciated!
has comment: http://stackoverflow.com/comment/90130282
has title: Adding/Subtracting values in dictionary via user inputs
type: UnansweredQuestion
tagged with: input
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90130311
type: Question
has comment: http://stackoverflow.com/comment/90130260
has comment: http://stackoverflow.com/comment/90130320
has answer: http://stackoverflow.com/a/51582532
tagged with: function
has comment: http://stackoverflow.com/comment/90130174
score: 0
linked to: http://stackoverflow.com/q/10568087

http://stackoverflow.com/comment/90140548
has text: This is a different question. Please update your original post accordingly.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51586112

http://stackoverflow.com/a/51494645
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89957718
answers question: http://stackoverflow.com/q/51494140
type: Answer
has body: You can do it with BeautifulSoup, using the Comment object: import requests from bs4 import BeautifulSoup, Comment resp = requests.get('https://www.meteoclimatic.net/feed/rss/ESCYL2400000024153A') soup = BeautifulSoup(resp.content, 'xml') for item in soup.select('item'): comments = item.description.find_all(text=lambda text:isinstance(text, Comment)) print([c for c in comments[0].split('\n') if c][1:-1]) Prints: ['&lt;ESCYL2400000024153A;(24,4;24,5;12,1;sun);(49,0;91,0;49,0);(1021,0;1021,2;1019,9);(5,0;10,0;219);(0,0);Sta Mar&amp;#237;a del Condado&gt;'] Edit: This code iterates through all &lt;item&gt; tags. In each &lt;item&gt; tag it will find in &lt;description&gt; all texts, that's instance of Comment object (in other words anything that is between &lt;!-- and --&gt; tags. Then it will split first comment according newlines and writes all lines but first and last.
accepted answer of: http://stackoverflow.com/q/51494140
score: 1
upvote count: 1

http://stackoverflow.com/comment/90204733
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51619527
has text: It Works :-) Thanks for helping and your advice

http://stackoverflow.com/q/51499045
has body: I'm trying to dynamically load modules as explained here. I have written a script that requires some modules that may not be installed by default on some systems (such as requests). The script code assumes that a regular import has been done (it uses requests.get). If I use the code in the link above, to import requests I would have to use: requests=importlib.import_module('requests') But this leads to a lot of code duplication since I have several modules. I can't use that in a loop since the variable name must change with the imported module. I have found that I can use: for m in list_of_modules: locals()[m]=importlib.import_module(m) And everything happens as if I had done regular import's. (of course the real code catches exceptions...). So the question is how valid/risky this is? Too good to be true or not? (Python 2.7 if that makes a difference)
has answer: http://stackoverflow.com/a/51499472
has comment: http://stackoverflow.com/comment/89966431
type: Question
answer count: 1
downvote count: 0
has title: How bad is it to explicitly add things to locals()?
favorite count: 0
linked to: http://stackoverflow.com/q/301134
score: 3
accepted answer: http://stackoverflow.com/a/51499472
tagged with: python
has comment: http://stackoverflow.com/comment/89966800
upvote count: 3
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89966787

http://stackoverflow.com/q/51577894
tagged with: if-statement
has body: this image shows how every input results in execution in triangleCalc() function block I'm new to Python and while practicing I made this program, It asks the user to choose one of the two shapes among circle and triangle. But every time I enter an input, no matter if it's a 'c', 't', 'r' or anything else, the function to calculate triangle area gets executed. ''' This is a Calculator program which asks the user to select a shape and then calculate its area based on given dimensions ''' print ('Shape Area Calculator is now running') def triangleCalc(): base = float(input('Enter Base of triangle: ')) height = float(input('Enter Height of triangle: ')) areaT = 0.5 * base * height print ('The area of triangle is: ' + str(areaT)) def circleCalc(): radius = float(input('Enter radius of Circle: ')) areaC = 3.14159 * radius * radius print ('The area of Circle is ' + str(areaC)) print('Which shape would you like to calculate the Area of?') print('Enter C for Circle or T for Triangle') option = input() if option == 't' or 'T': triangleCalc() elif option == 'c'or 'C': circleCalc() else: print ('Invalid Choice')
has answer: http://stackoverflow.com/a/51577967
linked to: http://stackoverflow.com/q/15112125
type: Question
answer count: 2
tagged with: function
possible better answer: http://stackoverflow.com/a/51577967
has answer: http://stackoverflow.com/a/51577905
linked to: http://stackoverflow.com/q/15008758
has title: How do I get input from user and call a function based on the input?
score: 0
has comment: http://stackoverflow.com/comment/90121151
accepted answer: http://stackoverflow.com/a/51577905
tagged with: python
has comment: http://stackoverflow.com/comment/90121209
type: AnsweredQuestion

http://stackoverflow.com/q/51535027
tagged with: python
tagged with: logging
has title: Silence h264 decoding warnings when called from OpenCV in Python
has body: I have the following script with which I read RTSP streams from withing Python3 using OpenCV. cap = cv2.VideoCapture(ID) ret, frame = cap.read() The streams are encoded using h264 and I get tons of warnings and error messages. [h264 @ 0x7f74cc430c80] co located POCs unavailable [h264 @ 0x7f74b4258160] error while decoding MB 38 2, bytestream -19 I tried to silence them using a context manager for redirecting stdout and stderr but with no success: class SilenceOutput(object): def __enter__(self): self._original_stdout = sys.stdout self._original_stderr = sys.stderr sys.stdout = None sys.stderr = None def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout = self._original_stdout sys.stderr = self._original_stderr
tagged with: opencv
has comment: http://stackoverflow.com/comment/90051939
answer count: 0
type: Question
score: 5
upvote count: 5
tagged with: h.264
downvote count: 0
linked to: http://stackoverflow.com/q/5081657
favorite count: 0
has comment: http://stackoverflow.com/comment/90050801
tagged with: ffmpeg
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/11130156

http://stackoverflow.com/q/51550074
has comment: http://stackoverflow.com/comment/90067881
score: 0
has answer: http://stackoverflow.com/a/51550250
has comment: http://stackoverflow.com/comment/90067796
answer count: 1
has title: How to do nested loop in python
tagged with: nested-loops
tagged with: numpy
has comment: http://stackoverflow.com/comment/90067836
accepted answer: http://stackoverflow.com/a/51550250
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90067788
has body: I would like to do nested loop in my programming. However, this code did not meet my expectation. X=[0,1,1,1,0] length=len(X) for i,val in enumerate(X): a=0 count=0 while (count&lt;length): a=15+a print (a) HWPQ=np.matrix([[1, 0, 0, 0], [0, math.cos(4*math.radians(a)), math.sin(4*math.radians(a)), 0], [0, math.sin(4 * math.radians(a)), - math.cos(4 * math.radians(a)), 0], [0, 0, 0, -1]]) result=HWPQ*val print (result) count=count +1 print ("\n") Supposedly, in this program, I would like to update the value of a for each element using the loop. For example: X=0 for a=0 X=1 for a=15 X=1 for a=30 X=1 for a=45 X=0 for a=60 The result should be, as I calculated it manually: [[ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]] [[ 1. 0. 0. 0. ] [ 0. 0.5 0.8660254 0. ] [ 0. 0.8660254 -0.5 0. ] [ 0. 0. 0. -1. ]] [[ 1. 0. 0. 0. ] [ 0. -0.5 0.8660254 0. ] [ 0. 0.8660254 0.5 0. ] [ 0. 0. 0. -1. ]] [[ 1.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00] [ 0.00000000e+00 -1.00000000e+00 1.22464680e-16 0.00000000e+00] [ 0.00000000e+00 1.22464680e-16 1.00000000e+00 0.00000000e+00] [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 -1.00000000e+00]] [[ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]]
has comment: http://stackoverflow.com/comment/90067861
type: Question
tagged with: python

http://stackoverflow.com/comment/90286303
type: Comment
score: 0
has text: You'll note, using that recursive sizeof recipe, will give you: `total_size([None]*100) == 880`, which is precisely `16` bytes more than `sys.getsizeof([None]*100)`, i.e. `864`, because `None` is a singleton object (in any case, the repetition operator never copies objects, and simply copies references)
type: AnswerComment
comment on: http://stackoverflow.com/a/51619941

http://stackoverflow.com/comment/90228534
comment on: http://stackoverflow.com/a/51618710
has text: so the os library has two nice functions, os.isfile(currentPathHere) and os.isdir(currentPathHere). These two are boolean functions, you can use these, if isdir is true, then change the path to look into the contents of this folder, and repeat the process. You can make this a recursive function that recursively goes into every single folder starting from the root inward, and looks at files, removing those that meet your criteria.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51601282
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90173354
answers question: http://stackoverflow.com/q/51601140
type: Answer
accepted answer of: http://stackoverflow.com/q/51601140
score: 4
has comment: http://stackoverflow.com/comment/90173140
has body: Method 1 You can use: df.to_csv('output.csv', sep = ';', encoding='ANSI', index=False, decimal=",") Method 2 As an alternative you can also use. df = df.applymap(lambda x: str(x).replace('.',',')) instead of df = df.astype(str).replace('.',',') It would give: A B C 0 1,2 2,2 6,5 1 3,5 5,4 7,8 And then df.to_csv('output.csv', sep = ';', encoding = 'ANSI', index=False)
upvote count: 4
has comment: http://stackoverflow.com/comment/90173454
has comment: http://stackoverflow.com/comment/90180775

http://stackoverflow.com/comment/89963583
has text: Please make this a [mcve]; your code as shown (minus possible indentation mishaps) cannot ever show the result you want.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51497747
score: 0

http://stackoverflow.com/q/51572702
accepted answer: http://stackoverflow.com/a/51593933
has answer: http://stackoverflow.com/a/65255831
type: AnsweredQuestion
tagged with: django-templates
has title: django: choice display with queryset values
score: 0
tagged with: django
type: Question
has body: I want to use get_status_display on template, from a queryset with just some fields from model. I have a model with a choices field (status). class Operation(models.Model, ModelMixin): operation_area = models.ForeignKey('operations.OperationArea', null=True) created = models.DateTimeField(auto_now=True) indication = models.NullBooleanField() observation = models.TextField(blank=True, null=True) rate = models.IntegerField(blank=True, null=True) scheduling = models.DateTimeField(blank=True, null=True) status = models.IntegerField(choices=OPERATION_TYPE) class OperationArea(models.Model, ModelMixin): campaign = models.ForeignKey('campaigns.Campaign') person = models.ForeignKey('registrations.Person') user = models.ForeignKey('authentication.User') area = models.CharField(max_length=1, choices=OPERATION_AREA) My query is: Operation.objects.filter(operation_area__user=user).values('id', 'created', 'operation_area__person__name', 'status') From this a get a dict, but get_FOO_dislpay is a instance method and don't works on a dict. I don't want to use .only() because he brings operation_area object and to get the person.name he makes another query, like this operation.operation_area.person.name. Any thoughts how to work with one query and get_FOO_display?
answer count: 2
has answer: http://stackoverflow.com/a/51593933
tagged with: django-queryset
tagged with: choicefield
tagged with: python
possible better answer: http://stackoverflow.com/a/65255831

http://stackoverflow.com/comment/89943429
score: 0
has text: @JamesKPolk: thanks for pointing this out. Of course it will block. I've fixed it in the answer.
comment on: http://stackoverflow.com/a/51483583
type: AnswerComment
type: Comment

syntactic-sugar
tags question: http://stackoverflow.com/q/51540966
type: Tag
tag name: syntactic-sugar

http://stackoverflow.com/q/51533534
tagged with: copy
answer count: 0
tagged with: share
has comment: http://stackoverflow.com/comment/90034848
linked to: http://stackoverflow.com/q/7169845
type: Question
tagged with: windows
tagged with: python
has body: I try to copy txt file from WinPC1 to WinPC2 In my WinPC1 i created local txt file in: C:\temp\1.txt I want to copy that txt file to windows network drive to folder: OUT\temp WinPC2 on WinPC1 seen: by net use like nam1\\box1\\IKQ by explorer like Z:\ so full paths are: full path witn net use will be \\\\nam1\\box1\\IKQ\\OUT\\temp or in explorer will be Z:\OUT\tmp First of all I tried to use os: copy C:\temp\1.txt Z:\OUT\tmp - check it in cmd, it was sucsessfull os.system(r"copy C:\\temp\\1.txt Z:\\OUT\\tmp") - try by python, it wasn't sucsessfull Then I read about shutil, and try to use it: it didn't work too, try to copy like that: shutil.copy(r'C:\temp\1.txt', "Z:\OUT\tmp") shutil.copy(r'C:\temp\1.txt', "\\\\nam1\\box1\\IKQ\\OUT\\temp") What i need to do?
has title: How to copy file to windows network drive folder using python?
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90040035
has comment: http://stackoverflow.com/comment/90036200

http://stackoverflow.com/a/51550683
has body: As indicated by the Python docs most_common([n]) Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily: So the order of the ones listed with a count of 1 are not guaranteed in any particular order because the underlying structure is a dict. If you want your results alphabetically, you'll need to do some more processing. from collections import Counter c = Counter() #counter generating code print sorted(c.most_common(), key=lambda i: (-i[1], i[0]))[:3] This basically grabs all your results first via. .most_common(), then sorts them by 2nd parameter (the word frequency) in descending order, then 1st parameter (the word) in ascending order. Finally taking the slice of the first 3 elements for your result. Edit: I realized that I wasn't sorting properly, and itemgetter is limited to only ascending order.
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/90068623
answers question: http://stackoverflow.com/q/51550654
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/90085974
has comment: http://stackoverflow.com/comment/90068895

http://stackoverflow.com/q/51562280
has body: Say I have a decorator like this: def repeat(repeat_count): def decorator(func): def wrapped(self): for X in range(repeat_count): func() # Do Function return wrapped return decorator and a class like this class SomeClass(object): def __init__(self, do_count): self.some_method = repeat(do_count)(self.some_method) def some_method(self): print("I'm Doing Something") Because a decorator just returns a method, it's clear that this works. However it unbinds the some_method function from the class instance, so I can no longer do something like: &gt;&gt;&gt; sc = SomeClass(10) &gt;&gt;&gt; sc.some_method() # TypeError: wrapped() missing 1 required positional argument: 'self' I get an exception because self is no longer automatically passed. To make this work I can simply do this: sc.some_method(sc) but I'd much rather not. Is there any way to rebind the method to the instance, preferably without any extra imports (as TypeMethod) would be able to accomplish.
has comment: http://stackoverflow.com/comment/90091773
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90091844
type: Question
has comment: http://stackoverflow.com/comment/90091839
answer count: 2
has answer: http://stackoverflow.com/a/51562782
has answer: http://stackoverflow.com/a/51562424
tagged with: python
has comment: http://stackoverflow.com/comment/90091892
has comment: http://stackoverflow.com/comment/90097606
score: 4
has title: How to dynamically decorate a class method, while not losing the methods bound status?
linked to: http://stackoverflow.com/q/972
has comment: http://stackoverflow.com/comment/90098493
has comment: http://stackoverflow.com/comment/90091861
has comment: http://stackoverflow.com/comment/90091747
has comment: http://stackoverflow.com/comment/90092162
has comment: http://stackoverflow.com/comment/90092085
has comment: http://stackoverflow.com/comment/90099136
upvote count: 4
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51577205
has answer: http://stackoverflow.com/a/51577232
score: 4
tagged with: ipython
has body: Real beginner question here, but it is so simple, I'm genuinely stumped. Python/DataFrame newbie. I've loaded a DataFrame from a Google Sheet, however any graphing or attempts at calculations are generating bogus results. Loading code: # Setup !pip install --upgrade -q gspread from google.colab import auth auth.authenticate_user() import gspread from oauth2client.client import GoogleCredentials gc = gspread.authorize(GoogleCredentials.get_application_default()) worksheet = gc.open('Linear Regression - Brain vs. Body Predictor').worksheet("Raw Data") rows = worksheet.get_all_values() # Convert to a DataFrame and render. import pandas as pd df = pd.DataFrame.from_records(rows) This seems to work fine and the data looks to be correctly loaded when I print out the DataFrame but running max() returns obviously false results. For example: print(df[0]) print(df[0].max()) Will output: 0 3.385 1 0.48 2 1.35 3 465 4 36.33 5 27.66 6 14.83 7 1.04 8 4.19 9 0.425 10 0.101 11 0.92 12 1 13 0.005 14 0.06 15 3.5 16 2 17 1.7 18 2547 19 0.023 20 187.1 21 521 22 0.785 23 10 24 3.3 25 0.2 26 1.41 27 529 28 207 29 85 ... 32 6654 33 3.5 34 6.8 35 35 36 4.05 37 0.12 38 0.023 39 0.01 40 1.4 41 250 42 2.5 43 55.5 44 100 45 52.16 46 10.55 47 0.55 48 60 49 3.6 50 4.288 51 0.28 52 0.075 53 0.122 54 0.048 55 192 56 3 57 160 58 0.9 59 1.62 60 0.104 61 4.235 Name: 0, Length: 62, dtype: object Max: 85 Obviously, the maximum value is way out -- it should be 6654, not 85. What on earth am I doing wrong? First StackOverflow post, so thanks in advance.
has title: DataFrame max() not return max
answer count: 1
favorite count: 0
tagged with: python
upvote count: 4
linked to: http://stackoverflow.com/q/3270680
tagged with: gspread
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/51577232
type: Question
tagged with: dataframe

http://stackoverflow.com/q/51635676
type: Question
possible better answer: http://stackoverflow.com/a/51636535
answer count: 2
has answer: http://stackoverflow.com/a/51636894
has body: I have wrote my first flask program, which logs into my device via telnet and gives me the output of a cat command. But I always get the error: Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. This call of the function GetLogs does not work (doesn't even come into the function - tried it with a print() within the function to see) @app.route('/GetLogs/&lt;name&gt;&amp;path=&lt;path&gt;/') def GetLogs(name, path): tempStr='' HOST = name user = "root" password = "password" tn = telnetlib.Telnet(HOST, timeout=5) tn.read_until(b"login: ") time.sleep(1) tn.write(user.encode('ascii') + b"\n") tn.read_until(b'Password: ') time.sleep(1) tn.write(password.encode('ascii') + b"\n") time.sleep(2) PATH_TO_LOG = "cat " + path + "\n" tn.write(PATH_TO_LOG.encode('ascii') + b"\n") tn.write(b"exit\n") tempStr=tn.read_all().decode('ascii') return tempStr.replace("\r\n", "&lt;br /&gt;") The other function Unlock works with basically the same code for app.route(...) but with only 1 parameter @app.route('/Unlock/&lt;name&gt;/') def Unlock(name): return "unlocked" Here is the rest of the code, that adds a small HTML UI with 2 textfields and 2 buttons: @app.route('/') def main_form(): return '''&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;body&gt; &lt;form action="/" method="POST"&gt; &lt;input type="text" name="text"&gt; &lt;br&gt;&lt;br&gt;&lt;br&gt; &lt;input type="submit" name="Buttons" value="Unlock"&gt; &lt;br&gt;&lt;br&gt; &lt;input type="submit" name="Buttons" value="GetLogs"&gt;&lt;input type="text" name="LogText"&gt; &lt;br&gt;&lt;br&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; ''' @app.route('/', methods=['POST', 'GET']) def ExecuteButtons(): if request.method == 'POST': inputtext = request.form['text'] inputtext = inputtext.replace("http://", "") inputtext = inputtext.replace("/","") inputtext = inputtext.replace(".com","") if request.form['Buttons'] == 'Unlock': #inputtext = request.form['tex…
accepted answer: http://stackoverflow.com/a/51636894
downvote count: 0
tagged with: flask
tagged with: python
has answer: http://stackoverflow.com/a/51636535
favorite count: 0
has title: python flask website error: the requested URL was not found on the server
score: 2
type: AnsweredQuestion
upvote count: 2

http://stackoverflow.com/q/51604302
score: 0
has comment: http://stackoverflow.com/comment/90174726
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90174428
has answer: http://stackoverflow.com/a/51604329
has body: I am new to programming and to test myself, I tried making a text-based game. The problem is, in the selection of dialogue, I included a speech check where it will be based on RNG but I just can't get it right. I am sorry if this is a dumb question but I am really lost. Here is the part of the code: def scene1part2(): option2 = ["1. Okay. Here you go you cheeky guard.", "2. What?! No.", "3. [Luck] Let me in for free?"] option2_1 = ["Okay. Here you go you cheeky guard.", "What?! No.", "3.Let me in for free?"] for o2 in option2: print(o2) answer2 = input("&gt; ") if answer2 == "1": print(option2_1[0]) print("Lost 500 Chromosomes") print("Guard: You can go ahead now.") chromosomes = (chromosomes) - 500 elif answer2 == "2": print(option2_1[1]) print("Guard: Get out of here then you piece of crap.") sys.exit() elif answer2 == "3": for rng in range(1): rng = random.randint(1, 101) print(rng) if rng &lt;= 50: print("Guard: You wish. Get out of here then you piece of crap. ") elif rng &gt;= 50: print("Guard: *sigh* Okay. Come inside already")
type: Question
has title: RNG for my text-based game in python3
has comment: http://stackoverflow.com/comment/90174589
answer count: 1
has comment: http://stackoverflow.com/comment/90174488

http://stackoverflow.com/q/51621919
has answer: http://stackoverflow.com/a/51640157
type: Question
score: 0
has body: Scenario: A quiz program with questions worth different amounts of points. Sqlite database with a table Table1 with a field RunningTotal of type Int. I'm looking to update the RunningTotal by the quantity 'updateby' passed to the function. This is a numerical value (but may be a string, so i'm converting it to integer to be sure. tableid is used to identify which row to update. eg (non-working code : error is that updateby is not a column name) def UpdateRunningTotal(tableid,updateby) updateby = int(updateby) conn.execute("UPDATE Table1 RunningTotal=RunningTotal+updateby WHERE tableid=?", (tableid,)) I know if I put the following it works to increment the field by 1, but as a function i want more flexibility to increment by different amounts. conn.execute("UPDATE Table1 RunningTotal=RunningTotal+1 WHERE tableid=?", (tableid,)) I'm trying to avoid doing a SELECT statement to read the current value of RunningTotal, do the math on that, and then use that result in the UPDATE statement...that seems inefficient to me (but may not be?)
tagged with: sqlite
answer count: 1
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51640157
tagged with: increment
tagged with: python
has title: Python 3 update sqlite column by an amount specified in a variable
type: AnsweredQuestion

http://stackoverflow.com/q/51580013
has title: How to convert a labelmap.prototxt into a set ? Caffe
tagged with: caffe
score: 0
answer count: 1
tagged with: python
tagged with: dictionary
has body: I have the labelmap.prototxt and I want to convert it into a set because I want to use it with Intel Neural Compute Stick SDK. Input home/labelmap.prototxt item { name: "none_of_the_above" label: 0 display_name: "background" } item { name: "1" label: 1 display_name: "person" } item { name: "2" label: 2 display_name: "bicycle" } item { name: "3" label: 3 display_name: "car" } Output: set(["background","person","bicycle","car"]) I tried as follow: &gt;&gt;&gt; with open('labelmap_coco.prototxt') as f: ... d = literal_eval(f) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; File "/usr/lib/python2.7/ast.py", line 80, in literal_eval return _convert(node_or_string) File "/usr/lib/python2.7/ast.py", line 79, in _convert raise ValueError('malformed string') ValueError: malformed string
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52239992
type: Question

http://stackoverflow.com/q/51597199
score: 1
has comment: http://stackoverflow.com/comment/90160505
has answer: http://stackoverflow.com/a/51598105
answer count: 2
tagged with: pandas
downvote count: 0
has title: Split Column (Delimit) in Pandas DataFrame ; columns same length as key error
favorite count: 0
has answer: http://stackoverflow.com/a/63739252
has body: I have a DataFrame that has a column, called "Financial Week Name", that has something like 'week 17' for each financial week. Financial Week Name Day Part week 0 Breakfast week 0 Lunch week 0 Dinner week 1 Breakfast week 1 Lunch The problem is that I can't sort these from smallest to largest. My thought was to hack out anything after the space after the word 'week'; essentially delimiting. I added an empty column (named 'weekNo') to the dataframe, and then tried to use the .str.split method to push the numbers in to the newly created column: df'Financial Week Name', 'weekNo' = df['Financial Week Name'].str.split(' ', expand=True) but got the following error: " ValueError: Columns must be same length as key" I'm not sure how get the number value from the end the string "week x" to get to a separate column, and have tried to use .iloc to unsuccessfully slice out the values. I'm pretty stumped; Any help would be greatly appreciated.
tagged with: python
type: UnansweredQuestion
upvote count: 1
type: Question

http://stackoverflow.com/a/51507954
type: Answer
upvote count: 4
downvote count: 0
has body: Here basics of how I set up a custom user model: In Settings.py add: AUTH_USER_MODEL = "accounts.User" accounts can be where ever you store you user model. User model: from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) from django.conf import settings from django.db import models from django.utils import timezone import binascii import os class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model.objects.create( email=self.normalize_email(email), first_name = first_name, last_name = last_name, ) user.set_password(password) user.save() return user def create_superuser(self, email, first_name, last_name, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, first_name, last_name, password ) user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=40, null=True, blank=True) last_name = models.CharField(max_length=140, null=True, blank=True) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.first_name def __str__(self): # __unicode__ on Python 2 return self.first_name def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms…
score: 4
has comment: http://stackoverflow.com/comment/90020416
answers question: http://stackoverflow.com/q/51507794
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51507794

http://stackoverflow.com/a/51491709
answers question: http://stackoverflow.com/q/51491502
type: Answer
has body: You can user itertools and numpy for this problem. import numpy as np from itertools import groupby total = [(1, 'red'), (10, 'green'), (9, 'red'), (10, 'blue'), (5, 'blue')] total_sorted = sorted(total, key=lambda x: x[1]) result = [] for key, group in groupby(total_sorted, key=lambda x: x[1]): result.append((key, np.mean(list(map(lambda x: x[0], group))))) print(result) # [('blue', 7.5), ('green', 10.0), ('red', 5.0)]
score: 0

http://stackoverflow.com/a/51616008
downvote count: 0
score: 16
has comment: http://stackoverflow.com/comment/90198692
has body: MEDIA_ROOT should be a string not a list. Change to MEDIA_ROOT = os.path.join(BASE_DIR,'media')
type: AcceptedAnswer
upvote count: 16
accepted answer of: http://stackoverflow.com/q/51615227
type: Answer
answers question: http://stackoverflow.com/q/51615227

http://stackoverflow.com/a/51601800
has body: Check this post out. Possibly gig into pipeline and change opencv C++ code. "This is full pipleline of OPencv Stitching code. You can see that there are lot of parameters you can change to make your code give some good stitching result. Also I would suggest using a small image (640 X480) for the feature detection step. Using small images is better than using very large images" Technically you should be able to change the parameter from python, but hopeful somebody else knows how to do that.s
score: 1
upvote count: 1
downvote count: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51504806
answers question: http://stackoverflow.com/q/51504806

http://stackoverflow.com/comment/90166595
comment on: http://stackoverflow.com/a/51600160
score: 0
type: Comment
has text: Why are you calling `best_power_strategy` three times if the result of each call is exactly the same?
type: AnswerComment

http://stackoverflow.com/comment/90123561
type: Comment
has text: @user4815162342 I don't have my head around scope within asyncio - I'm not even sure yet if scope is any different - but as it stands, proc is out of scope in that callback - can you suggest what "the right way" is for me to get it into socket_png_receiver so I can execute it?
comment on: http://stackoverflow.com/q/51578522
score: 0
type: QuestionComment

http://stackoverflow.com/q/51571311
type: Question
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/90108649
score: 0
has body: first time posting and very new to python (3 weeks in). As I'm trying to get a better understanding of classes, this is a job generator that outputs teams (lists) of two or more different names: one with value over 3 (or “M”) and one lower. Need help with the part beginning with the 2 asteriks. Keeps giving me error that str object has no attribute “name. import random class Rankings: ranks = ["","T","B","M","P","C"] #rankings going in order #from least to greatest with index being a respective value of #the ranking. Ex. C = 5, P = 4.... listofranks = [] num_of_emps =[] def __init__(self,name,ranking): self.name = name #mover’s name Rankings.num_of_emps.append(self.name)#adds #mover to list once created self.ranking = ranking #mover’s ranking Rankings.listofranks.append(self.ranking) #adds ranking #to list once created def rank(self): self.ranking = Rankings.ranks[self.ranking] return self.ranking #returns the mover’s respective rank #letter def find_hi_rank(self): **hirank = [self.name in Rankings.num_of_emps for i in Rankings.listofranks if i &gt; 3 ]** #Obviously this part is #confusing as I don’t know what to do to get what I want. I #want it to print name for each item w value greater than 3 return hirank @classmethod def fromstring(cls,rank_str): name,ranking = rank_str.split("-") return cls(name,ranking) Tim = Rankings("Tim", 5) Luis = Rankings("Luis", 5) Chris = Rankings("Chris", 4) Fab = Rankings("Fab",3) G = Rankings("G", 3) Everett = Rankings("Everett", 3) print(Rankings.num_of_emps) numofjobs = 3 numofmovers = len(Rankings.num_of_emps)#how ever #many movers were added is the number of movers that can #be chosen from movers = Rankings.num_of_emps job = 0 while numofjobs &gt;0: job +=1 crew = int(input(f"How many movers are on job {job} ? ")) #if crew &lt; movers: #raiseError: Not enough movers groups = [] numofmovers -= crew numofjobs -=1 for i in range(crew): if i == 0: new = list(map(Rankings.find_hi_rank, movers)) ",".split(new)# creates a list of move…
has comment: http://stackoverflow.com/comment/90109602
tagged with: methods
has title: Need job generator to output two items from lists
type: UnansweredQuestion
tagged with: class
answer count: 0

http://stackoverflow.com/comment/90207086
type: Comment
comment on: http://stackoverflow.com/q/51620072
score: 0
type: QuestionComment
has text: @Phiber Does pressing buttons count as modifying the GUI? Even when a button is connected to a slot that simply prints out something in the console the program crashes when it is pressed.

http://stackoverflow.com/comment/90107831
comment on: http://stackoverflow.com/q/51570291
has text: I don't understand, what "Color" is supposed to mean in this context. You have nine intervals to fill, but ten values for "Color".
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51628255
answer count: 1
score: 1
accepted answer: http://stackoverflow.com/a/51628668
favorite count: 0
has comment: http://stackoverflow.com/comment/90221245
tagged with: python
has body: So, for the main action sequence of my game, I have this code for the battle. It works, sort of. I can choose the moves and all the text will display, but it doesn't take health off of the opponent, and the turn doesn't change over. I can't for the life of me figure out what I've done wrong. Here is the code: I'm using python 2.7. play_again = True while play_again is True: winner = None player_health = 100 computer_health = random.randrange(1,200) player_turn = True computer_turn = False while (player_health != 0 or computer_health != 0): heal_up = False miss = False moves = {"Punch": random.randint(18, 25), "Slap": random.randint(10, 35), "Kick": random.randint(10, 25)} if player_turn is True: print("""1. Punch 2. Slap 3. Kick """) player_move = raw_input("&gt;&gt;&gt; ") move_miss = random.randint(1,10) if move_miss == 1: miss = True else: miss = False if miss: player_move = 0 print("You missed!") else: if player_move in ("1", "punch"): player_move = moves["Punch"] print("You used Punch! It dealt %s damage!") % player_move elif player_move in ("2", "slap"): player_move = moves["Slap"] print("\nYou used Slap!. It dealt %s damage.") % player_move elif player_move in ("3", "kick"): player_move = moves["Kick"] print("\nYou used Kick! It dealt %s damage.") % player_move else: print("\nThat is not a valid move. Please try again.") else: move_miss = random.randint(0, 10) if move_miss == 1: miss = True else: miss = False if miss: computer_move = 0 print('The Opponent Missed!') else: imoves = ["Punch", "Slap","Kick"] imoves = random.choice(imoves) CPU_move = moves[imoves] if CPU_move == moves["Punch"]: print("The opponent used Punch. It dealt %s Damage.") % CPU_move player_health -= CPU_move if CPU_move == moves["Slap"]: print("\nThe opponent used Slap. It dealt %s Damage.") % CPU_move player_health -= CPU_move if CPU_move == moves["Kick"]: print("\nThe opponent used Kick. It dealt %s Damage.") % CPU_move player_health -= CPU_move if player_turn is true: computer_health -…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90221932
upvote count: 2
downvote count: 1
type: Question
has title: Opponents health not decreasing, and turns not flipping over
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51628668
has comment: http://stackoverflow.com/comment/90222223
has comment: http://stackoverflow.com/comment/90221141

http://stackoverflow.com/comment/90149176
comment on: http://stackoverflow.com/q/51591849
type: QuestionComment
has text: Use Selenium http://selenium-python.readthedocs.io/
score: 0
type: Comment

http://stackoverflow.com/comment/90185749
has text: Thanks, that's a great solution!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51610514

http://stackoverflow.com/comment/90163805
has text: @NirmalRaj, the directory appears to be hard coded within your 'python program', not provided by the user. If the user is providing it somewhere in the process then there should be some form of coding to verify it as a genuine and existing path, preferably at some stage early on, _read as in your python program_. For that reason you should be concentrating on getting your python code correct, the [batch-file] and [cmd] tags are currently irrelevant to your question, and their addition makes your question too broad.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51574915
type: AnswerComment

http://stackoverflow.com/comment/90365819
type: Comment
has text: The probability for each event is 100%. They just occur at different times, with different frequencies.
type: QuestionComment
comment on: http://stackoverflow.com/q/51632019
score: 0

http://stackoverflow.com/comment/90067956
type: Comment
comment on: http://stackoverflow.com/a/51549423
has text: The code I'm looking over has many instances of the following: `a=np.array([[1,2,3,4,5],[1,2,3,4,5]])` and `b=a[:]*1`. In this context, where the multiplication is happening with the contents of the container, we have to equivalent of a deep copy, no?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90267587
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51628451
has text: @Programmer120 , that's why `json.loads(responsedata)` is added. You may try `responsedata.json()`, is just same as `json.loads(responsedata)`
type: AnswerComment

http://stackoverflow.com/comment/89983916
comment on: http://stackoverflow.com/q/51507341
type: Comment
type: QuestionComment
score: 0
has text: Your port is where uWSGI (actually, the socket server underneath, or a web server forwarding to it) waits for connections which are then funneled to Python/Flask - from Flask's perspective, in this case, there is no port to speak of.

http://stackoverflow.com/q/51498477
has answer: http://stackoverflow.com/a/51498599
accepted answer: http://stackoverflow.com/a/51498584
has comment: http://stackoverflow.com/comment/89964827
type: Question
answer count: 2
tagged with: python
has body: How can I use objects which belong to one class, in another different class? I tried different things, but I still do not get a solution. Let´s say I have the following example code: class ClassA(): def __init__(self): print "I am ClassA" def methodA(self): print "Method executed" class ClassB(): def __init__(self): print "I am ClassB" self.varB = 0 def methodB(self): if self.varB == 0: # Error here self.objectA.methodA() else: print "Method not executed" class ClassC(): def __init__(self): print "I am ClassC" self.objectA = ClassA() self.objectA.methodA() #Step 1: obj1 = ClassC() #Step 2: obj2 = ClassB() #Step 3: (Gives error) obj2 = methodB() In this example, I have three classes. In ClassC, I create an instance of ClassA, which is used to execute the respective method (methodA). If afterwards we procceed with "Step 1", the output is: I am ClassC I am ClassA Method executed Then, in "Step 2", I create a new object of ClassB. Following to the last output, we get now as well: I am ClassB The problems comes with "Step 3", when I execute the methodB for the last object. The error: AttributeError: ClassB instance has no attribute 'objectA' I have very clear the origin of the error. I can´t simply use the instance that I created in ClassC, inside the method of ClassB. Does anyone know, how could I access from ClassB, an instance (in this case objectA) that I created in other class (ClassC)?
has title: Python - Using objects in different classes
score: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51498584
possible better answer: http://stackoverflow.com/a/51498599

http://stackoverflow.com/comment/90047042
comment on: http://stackoverflow.com/q/51539435
score: 0
has text: Possible duplicate of [How do I trim whitespace?](https://stackoverflow.com/questions/1185524/how-do-i-trim-whitespace)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89945334
score: 0
type: Comment
type: QuestionComment
has text: `cygdrive`? You're in cygwin? Sounds like you might be using different Python installs in Cygwin and outside of it.
comment on: http://stackoverflow.com/q/51487798

http://stackoverflow.com/comment/89981203
has text: @mVChr: Even then there can still be an error if `lista2` does not contain any elements.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51506029
score: 0

http://stackoverflow.com/q/51543383
answer count: 1
score: 0
has title: Finishing steps to a subplot graph
has answer: http://stackoverflow.com/a/51544102
tagged with: python
type: AnsweredQuestion
tagged with: matplotlib
type: Question
accepted answer: http://stackoverflow.com/a/51544102
has body: I'm having some trouble finishing up this subplot. All I need to do at this point is get rid of the jumble of text at the bottom, then add individual X labels for each bar in each subplot. (all subplots share the same group of X values) Here's what I have so far... dictlist = [] for i in quarters: d = defaultdict(int) x = df['Activity'][df['QuarterYear']==i].tolist() for j in x: d[j] += 1 dictlist.append(d) This returns a list with 4 dictionaries in it. Each one with the keys and value counts for each quarter. Here's dictlist[0] defaultdict(int, {'CARE COORDINATION': 11052, 'COMPREHENSIVE CARE MANAGEMENT': 1403, 'HEALTH PROMOTION': 6575, 'PATIENT AND FAMILY SUPPORT': 9731, 'REFERRAL TO SOCIAL SUPPORTS': 1888, 'TRANSITIONAL CARE': 239}) And here's my graph code f, axes = plt.subplots(2, 2, figsize=(7, 7), sharex=True, sharey=True) axes[0,0].bar(dictlist[0].keys(), dictlist[0].values()) axes[0,0].set_xlabel(quarters[0]) #axes[0,0].set_xticks(range(0,7)) #axes[0,0].set_xticklabels([*dictlist[0]], fontdict=None, minor=False) for p in axes[0,0].patches: axes[0,0].annotate(str(p.get_height()), xy=(p.get_x(), p.get_height())) axes[0,1].bar(dictlist[1].keys(), dictlist[1].values()) axes[0,1].set_xlabel(quarters[1]) for p in axes[0,1].patches: axes[0,1].annotate(str(p.get_height()), xy=(p.get_x(), p.get_height())) axes[1,0].bar(dictlist[2].keys(), dictlist[2].values()) axes[1,0].set_xlabel(quarters[2]) for p in axes[1,0].patches: axes[1,0].annotate(str(p.get_height()), xy=(p.get_x(), p.get_height())) axes[1,1].bar(dictlist[3].keys(), dictlist[3].values()) axes[1,1].set_xlabel(quarters[3]) for p in axes[1,1].patches: axes[1,1].annotate(str(p.get_height()), xy=(p.get_x(), p.get_height())) fig = plt.gcf() fig.set_size_inches( 16, 16) fig.savefig('output5.png') I'm not exactly sure what's causing that jumbled text at the bottom, and I'd like to create a master legend somehow. Any help would be appreciated. This is python 3.6

http://stackoverflow.com/q/51622480
has answer: http://stackoverflow.com/a/51622512
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/437589
tagged with: flask
tagged with: flask-sqlalchemy
duplicate of: http://stackoverflow.com/q/437589
tagged with: sql
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am running Flask Shell as a way to interact with SQLAlchemy. However, I notice that whenever I run Flask Shell in my app directory, it only references the code that was present at the time it was run. This means that if I detect an error and update the code, I need to close my command terminal, re-navigate to my Flask app directory, and run Flask Shell again. Is there any way for me either access my Flask app directly from the Python Shell, or to have Flask Shell automatically update if there is a change in the code? It seems incredibly inefficient to do it the way I have been doing it. The way I am currently running Flask Shell is that I am navigating to my Flask app directory in the command terminal and then running the "flask shell" command, every time I update my code. To be clear, this is different from running a Flask app on localhost. That does update once the code is changed. Flask Shell, however, does not, and is specifically being used in this case to interact with SQLAlchemy.
score: 3
has title: Can Flask Shell Update Automatically?
upvote count: 3
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/a/51562782
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51562280
upvote count: 1
score: 1
has body: For a rather simple case, where you don't need to access self from the decorator itself, you can simply use the following (which is pretty much what you already did, minus the wrapper function invocation, and the passing of self). The method passed to the decorator is already bounded to self when you assign self.some_method = repeat(do_count)(self.some_method) The full code: def repeat(repeat_count): def decorator(func): def wrapped(): for X in range(repeat_count): func() return wrapped return decorator class SomeClass(object): def __init__(self, do_count): self.a = 3 self.some_method = repeat(do_count)(self.some_method) def some_method(self): print("Accesing my a from inside: %d" % self.a) sc = SomeClass(5) sc.some_method() output: Accesing my a from inside: 3 Accesing my a from inside: 3 Accesing my a from inside: 3 Accesing my a from inside: 3 Accesing my a from inside: 3

http://stackoverflow.com/comment/90149750
has text: Ah. Sorry Wrong indentation. Happy to help :)
comment on: http://stackoverflow.com/a/51588090
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51574183
has answer: http://stackoverflow.com/a/51574248
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/90114803
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51574248
has title: How do I count the frequency of words in a sorted list?
type: Question
has comment: http://stackoverflow.com/comment/90114256
has body: npl = [] for i in df2['Review']: npl.extend(tb(i).noun_phrases) This is the code I used to produce my list and it's very long. ['omg', 'populus scramble', 'coffee', 'hack', 'snagged', 'burpple', 'ice cream melts', 'sweet prize ', ...] Basically, how do I develop a code that will loop the list to count the frequency of words and show the words too? Something like Counter. I spent hours looking through this website, trying to find a code that works for me but to no avail. npl.count('coffee') Using the code above works but it's only applicable for one word Expected output is something like this: {'coffee', '45' 'snagged', '23' 'ice cream melts', '13'}
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/90114371
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/90114603
has comment: http://stackoverflow.com/comment/90114566
has comment: http://stackoverflow.com/comment/90114482

http://stackoverflow.com/q/51489205
tagged with: numpy
score: 0
duplicate of: http://stackoverflow.com/q/47885848
tagged with: arrays
has title: How to filter a numpy array based on a field of its elements
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/47885848
has comment: http://stackoverflow.com/comment/89947336
answer count: 0
type: Question
has body: I know that I can use index expressions to filter a numpy array as shown in this SO answer. &gt;&gt;&gt; b = a[a&gt;threshold] But, what if I need the logical condition to be based on a field of the array to be filtered? e.g. with: &gt;&gt;&gt; arr = np.arange(12).reshape((3, 4)) &gt;&gt;&gt; arr array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) When I try to do a similar filter based on the 3rd field/column: &gt;&gt;&gt; b = arr[arr[2]&gt;0] I get an error Traceback (most recent call last): File "", line 1, in IndexError: boolean index did not match indexed array along dimension 0; dimension is 3 but corresponding boolean dimension is 4 I can't get the filtered array. What I need is the same result of the following list comprehension: [r for r in aa if r[2] &gt; 0] with aa = [[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]] What is the right way to filter based on a field/column?
has comment: http://stackoverflow.com/comment/89947325
linked to: http://stackoverflow.com/q/7994394

http://stackoverflow.com/comment/90221043
has text: the files exist, i put your code on pycharm but it finish with error code: 0, what does it means?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51628208

http://stackoverflow.com/q/51603822
has body: XLSXWRITER works on my Mac computer when I run my kivy app and successfully creates an XLSX file. Unfortunately once I compile the apk using buildozer the "Export" button I made doesn't create the XLSX. No crash occurs, I just can't find the XLSX that should have been created. My theory is that the spreadsheet is created but 'lives' within the APK Package. Please help me to create XLSX using Kivy on android! * Python 2.7.15 * Kivy 1.9.1 * Android Phone
type: UnansweredQuestion
tagged with: apk
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/90252357
score: 0
tagged with: xlsxwriter
has comment: http://stackoverflow.com/comment/90195445
type: Question
has title: Why doesn't XLSXWRITER create a file once my Kivy app is compliled into an APK?
has comment: http://stackoverflow.com/comment/104669242
answer count: 1
has answer: http://stackoverflow.com/a/59485426

http://stackoverflow.com/a/51681618
has comment: http://stackoverflow.com/comment/90339657
has body: I ran an empirical test using big_O fitting library here Note: All tests have been conducted on independent variable sweeping 6 orders of magnitude (i.e. rows from 10 to 10^6 vs. constant column size of 3, columns from 10 to 10^6 vs. constant row size of 10 The result shows that the columns reverse operation .columns[::-1] complexity in the DataFrame is Cubical: O(n^3) where n is the number of rows Cubical: O(n^3) where n is the number of columns Prerequisites: You will need to install big_o() using terminal command pip install big_o Code import big_o import pandas as pd import numpy as np SWEAP_LOG10 = 6 COLUMNS = 3 ROWS = 10 def build_df(rows, columns): # To isolated the creation of the DataFrame from the inversion operation. narray = np.zeros(rows*columns).reshape(rows, columns) df = pd.DataFrame(narray) return df def flip_columns(df): return df[df.columns[::-1]] def get_row_df(n, m=COLUMNS): return build_df(1*10**n, m) def get_column_df(n, m=ROWS): return build_df(m, 1*10**n) # infer the big_o on columns[::-1] operation vs. rows best, others = big_o.big_o(flip_columns, get_row_df, min_n=1, max_n=SWEAP_LOG10,n_measures=SWEAP_LOG10, n_repeats=10) # print results print('Measuring .columns[::-1] complexity against rapid increase in # rows') print('-'*80 + '\nBig O() fits: {}\n'.format(best) + '-'*80) for class_, residual in others.items(): print('{:&lt;60s} (res: {:.2G})'.format(str(class_), residual)) print('-'*80) # infer the big_o on columns[::-1] operation vs. columns best, others = big_o.big_o(flip_columns, get_column_df, min_n=1, max_n=SWEAP_LOG10,n_measures=SWEAP_LOG10, n_repeats=10) # print results print() print('Measuring .columns[::-1] complexity against rapid increase in # columns') print('-'*80 + '\nBig O() fits: {}\n'.format(best) + '-'*80) for class_, residual in others.items(): print('{:&lt;60s} (res: {:.2G})'.format(str(class_), residual)) print('-'*80) Results Measuring .columns[::-1] complexity against rapid increase in # rows ---------------------…
has comment: http://stackoverflow.com/comment/90339398
answers question: http://stackoverflow.com/q/51486063
has comment: http://stackoverflow.com/comment/90339474
has comment: http://stackoverflow.com/comment/90339514
has comment: http://stackoverflow.com/comment/90339432
score: -1
has comment: http://stackoverflow.com/comment/90339386
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90339479
downvote count: 2

http://stackoverflow.com/a/51490867
upvote count: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/51490358
has comment: http://stackoverflow.com/comment/89950342
score: 0
has body: There is an easier way to produce your bar chart in Pandas: a3.set_index('OfficeName').plot.bar(width=0.35, legend=False) plt.xticks(rotation=0, ha='center') (You still need to set the x and y axis labels and the title.)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89950445
has comment: http://stackoverflow.com/comment/97351113
type: Answer
answers question: http://stackoverflow.com/q/51490358
has comment: http://stackoverflow.com/comment/89950484

http://stackoverflow.com/comment/92799325
score: 0
has text: What would this be like for GRU/LSTM?
type: AnswerComment
comment on: http://stackoverflow.com/a/51630378
type: Comment

http://stackoverflow.com/comment/90145447
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51578631
type: Comment
has text: If you have the rtsp link of the camera you can use opencv VideoCapture directly. If you can say at least the model of the cam, and how are you trying to connect. This way we can actually help you know if you are doing it correctly or if the link is not the correct one. The address is most probably `rtsp://admin:password@ipOfCam/live/ch00_0`. Not sure if you need to set the port for this camera, so it could be `rtsp://admin:password@ipOfCam:554/live/ch00_0`

http://stackoverflow.com/a/51598803
has comment: http://stackoverflow.com/comment/90276710
downvote count: 0
has comment: http://stackoverflow.com/comment/90266844
has comment: http://stackoverflow.com/comment/90190194
type: Answer
has comment: http://stackoverflow.com/comment/90240136
upvote count: 1
has body: The w2v_model.wv.vectors is what was formerly called "syn0", and serves as the "projection weights" which essentially map a one-hot word-encoding into N dimensions. In your diagram, that's WI. The w2v_model.trainables.syn1neg is the hidden-to-output weights for negative-sampling mode, what your diagram labels WO.
has comment: http://stackoverflow.com/comment/90236950
has comment: http://stackoverflow.com/comment/90198147
score: 1
has comment: http://stackoverflow.com/comment/90265556
has comment: http://stackoverflow.com/comment/90266945
accepted answer of: http://stackoverflow.com/q/51594165
answers question: http://stackoverflow.com/q/51594165
type: AcceptedAnswer

http://stackoverflow.com/comment/90051299
has text: I tried using both scrapy and selenium but the code just can't find the divs which posts are. I wanna know if there is a way that linkedin would allow me to scrape its pages
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51541469

http://stackoverflow.com/a/51549593
has body: you can use diff to check when the difference between two following values is negative, meaning of the start of a new range. Let's create a dataframe: import pandas as pd import numpy as np # to create a dataframe with two columns my range go up to 12 but 1400 is the same df = pd.DataFrame({'a':[1,4,np.nan,5,10,12,2,3,4,np.nan,8,12],'b':range(1,13)}) df.loc[[4,8],'b'] = np.nan Because you have 'NaN', you need to use ffill to fill NaN with previous value and you want the opposite of the row (using ~) where the diff is greater or equal than 0 (I know it sound like less than 0, but not exactely here as it miss the first row of the dataframe). For column 'a' for example print (df.loc[~(df.a.ffill().diff()&gt;=0),'a']) 0 1.0 6 2.0 Name: a, dtype: float64 you get the two rows where a "new" range start. To use this property to create 'a1', you can do: # put 1 in the rows with a new range start df.loc[~(df.a.ffill().diff()&gt;=0),'a1'] = 1 # create a mask to select notnull row in a: mask_a = df.a.notnull() # use cumsum and ffill on column a1 with the mask_a df.loc[mask_a,'a1'] = df.loc[mask_a,'a1'].cumsum().ffill() Finally, for several column, you can do: list_col = ['a','b'] for col in list_col: df.loc[~(df[col].ffill().diff()&gt;=0),col+'1'] = 1 mask = df[col].notnull() df.loc[mask,col+'1'] = df.loc[mask,col+'1'].cumsum().ffill() and with my input, you get: a b a1 b1 0 1.0 1.0 1.0 1.0 1 4.0 2.0 1.0 1.0 2 NaN 3.0 NaN 1.0 3 5.0 4.0 1.0 1.0 4 10.0 NaN 1.0 NaN 5 12.0 6.0 1.0 1.0 6 1.0 7.0 2.0 1.0 7 3.0 8.0 2.0 1.0 8 4.0 NaN 2.0 NaN 9 NaN 10.0 NaN 1.0 10 8.0 11.0 2.0 1.0 11 12.0 12.0 2.0 1.0 EDIT: you can even do it in one line for each column, same result: df['a1'] = df[df.a.notnull()].a.diff().fillna(-1).lt(0).cumsum() df['b1'] = df[df.b.notnull()].b.diff().fillna(-1).lt(0).cumsum()
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90093849
has comment: http://stackoverflow.com/comment/90094443
type: Answer
accepted answer of: http://stackoverflow.com/q/51548631
answers question: http://stackoverflow.com/q/51548631
score: 0

http://stackoverflow.com/a/71978185
downvote count: 0
has body: Answer in April 2022 Since version 2.2, Tensorflow has supported find unique 1-D tensor in a 2D tensor using tf.raw_ops.UniqueV2. &gt;&gt;&gt; import tensorflow as tf &gt;&gt;&gt; a = tf.constant([[1, 2, 1], [3, 4, 1], [5, 6, 1], [1, 2, 1]]) &gt;&gt;&gt; y, idx = tf.raw_ops.UniqueV2(x=a, axis=[0]) &gt;&gt;&gt; y &lt;tf.Tensor: shape=(3, 3), dtype=int32, numpy= array([[1, 2, 1], [3, 4, 1], [5, 6, 1]], dtype=int32)&gt; &gt;&gt;&gt; idx &lt;tf.Tensor: shape=(4,), dtype=int32, numpy=array([0, 1, 2, 0], dtype=int32)&gt; Check the docs for more details.
type: Answer
answers question: http://stackoverflow.com/q/51487990
has comment: http://stackoverflow.com/comment/128725155
upvote count: 5
score: 5

http://stackoverflow.com/q/51564639
has comment: http://stackoverflow.com/comment/90096910
has comment: http://stackoverflow.com/comment/90096867
has comment: http://stackoverflow.com/comment/90097199
tagged with: word2vec
tagged with: python
type: UnansweredQuestion
score: 0
has body: While using TFIDF Word2Vec giving NaN values on the review of Amazon fine foods dataset after sampling it to 100k data points I am getting NaN values in the sentence vector... I tried almost everything with the code but am not getting real values.. After printing the sentence array this is the output I am getting - [nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan] [nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan] [nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan] [nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan] [nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan]..... The code is as follows - from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import TfidfTransformer tfidf = TfidfVectorizer(ngram_range=(1,2), analyzer='word') final_tfidf = tfidf.fit_transform(final_data['CleanedText'].values) tfidf_feat = tfidf.get_feature_names() tf_sent_vectors = [] row = 0 for sent in list_of_sent: sent_vec = np.zeros(50) #initializiing the sent_vec weighted_sum = 0 #initializing the weightedsum for word in sent: try: vec = w2v_modelk.wv[word] tf_idf = final_tfidf[row, tfidf_feat.index(word)] sent_vec += (vec * tf_idf) weighted_sum += tf_idf except: pass sent_vec /= weighted_sum print(sent_vec…
has comment: http://stackoverflow.com/comment/90097179
type: Question
has comment: http://stackoverflow.com/comment/90143937
has answer: http://stackoverflow.com/a/61308452
has comment: http://stackoverflow.com/comment/90096698
answer count: 1
has title: tfidf w2v giving NaN values
tagged with: tf-idf

http://stackoverflow.com/comment/90311311
score: 0
has text: https://hastebin.com/vucetirane.py check it
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51607860

http://stackoverflow.com/q/51487259
type: AnsweredQuestion
score: 1
tagged with: matplotlib
has title: Extract color data from Matplotlib.pcolormesh() plot for conversion to .kml or other format
upvote count: 1
type: Question
has body: I have a program that plots data on various map software, such as Google Earth and Leaflet. I need to represent a certain data set, which is stored as a numpy array, on Google Earth, using square polygons as the data format within the corresponding kml file. Pcolormesh produces a grid of color squares. Further, it allows you to extract the coordinates of the vertices of each square. If I then feed these into the simplekml library's polygon maker, it works great, only I cannot figure out how to extract the color data from matplotlib and pass it to the object I am creating. I have been trying to figure it out from the documentation. Here is what I have so far. The example uses Cartopy, but I believe it is only matplotlib that is causing my problem. import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import cartopy.crs as ccrs from cartopy.examples.waves import sample_data import pdb import simplekml ax = plt.axes(projection=ccrs.Robinson()) ax.set_global() lons, lats, data = sample_data(shape=(20, 40)) default_cmap = 'RdBu_r' def make_path_polygons(mesh): kml = simplekml.Kml() paths = mesh.get_paths() for path in paths: kml.newpolygon(name="newpoly", outerboundaryis=path.vertices) #NEED TO SET COLOR HERE kml.save("gridpaths.kml") mesh = plt.pcolormesh(lons, lats, data, transform=ccrs.PlateCarree(), cmap=default_cmap) print(mesh.get_facecolors()) #Result: array([[0.1215, 0.4667, 0.7058]]), I would have hoped this returned a sequence corresponding to the coordinate data, but seems it does not make_path_polygons(mesh) ax.coastlines() ax.gridlines() plt.savefig("pcm.png") Here is my matplotlib plot: And here is the .kml in Google Earth: I understand why the GE result is colorless, because right now I am only passing coordinate data to simplekml and nothing else. But how do I get that data out of the mpl.QuadMesh object? Any help would be greatly appreciated, thank you.
tagged with: kml
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51487314
accepted answer: http://stackoverflow.com/a/51487314
tagged with: python
tagged with: gis
tagged with: google-earth

http://stackoverflow.com/comment/89962051
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51497071
has text: Fix indentation
score: 0

http://stackoverflow.com/comment/90155588
comment on: http://stackoverflow.com/q/51594877
has text: Please copy-paste the full and complete exception output into the question, as text. And add e.g. a comment on the line of code it happens.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/89967460
type: QuestionComment
comment on: http://stackoverflow.com/q/51498881
has text: Since this is a `ForeignKey`, you can (at most) select *one* vehicle*, so it should be a `ModelChiceField`.
score: 0
type: Comment

http://stackoverflow.com/q/51567670
accepted answer: http://stackoverflow.com/a/51567686
tagged with: python
tagged with: pygame
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/63676678
upvote count: 2
duplicate of: http://stackoverflow.com/q/58177145
possible better answer: http://stackoverflow.com/a/63676678
type: Question
linked to: http://stackoverflow.com/q/26392336
has title: How to load image using pygame.image.load()?
has answer: http://stackoverflow.com/a/51567686
duplicate of: http://stackoverflow.com/q/8873219
has body: I just want to know the syntax. How do I load an image using pygame.image.load() ? Let's take an example, I want to load an image called cat.png - and type this pygame.image.load('cat.png') Then, where should the image cat.png be saved?
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/79016795
linked to: http://stackoverflow.com/q/58177145
favorite count: 0

http://stackoverflow.com/comment/89939220
has text: MySQL is not running in a container though. Does MySQL also have to dockerized to be used with a dockerized Django app?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51484521

http://stackoverflow.com/a/68753771
type: Answer
score: 0
has body: you need to change the column name, statsmodels can't fit regression line with "inf" in column name for example INF --> Infraction or anything else.
answers question: http://stackoverflow.com/q/51548666

http://stackoverflow.com/comment/89946104
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51488541
has text: Thanks! I also upgraded my flask from `0.10.1` to `1.0.2` and I am getting debug info again

http://stackoverflow.com/comment/90055247
score: 0
type: Comment
type: QuestionComment
has text: I guess it would. If you need further help, consider providing a [mcve].
comment on: http://stackoverflow.com/q/51540384

http://stackoverflow.com/comment/90219108
type: AnswerComment
type: Comment
has text: While this code may answer the question, it's often better to add some explanation to your code. What have you done/changed that solved the problem? See [How to write a good answer](https://stackoverflow.com/help/how-to-answer)
comment on: http://stackoverflow.com/a/51626655
score: 0

http://stackoverflow.com/comment/89951165
type: Comment
type: QuestionComment
has text: Thank you, I found the error by checking the server logs as you suggested. The problem was that python wasn't able to open the file as it was not located under the localhost root.
score: 0
comment on: http://stackoverflow.com/q/51490454

http://stackoverflow.com/q/51591897
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51623453
tagged with: ram
has body: I am trying to extract values from multiple tiff files in a folder using python. I have used glob-glob to iterate through the files and extract the values for each location based on latitude and longitude vales. I have written the code and its runs fine in the beginning but eventually keeps consuming my ram and my system hangs. I have almost 5000 such files and more than 200 locations. The code is given below. import math,os,sys,glob import gdal from openpyxl import load_workbook f1=('C:\Users\APPLIED\Desktop\SPIE Analysis\Data\Data1.xlsx') wt = load_workbook(f1, read_only=False)#, keep_vba=True) sheet1 = wt['Sheet1'] #--------------------------------------------------------------------------- lat = [] file_in = open("C:\Users\APPLIED\Desktop\SPIE Analysis\Data\lat.txt", "r") for y in file_in.read().split("\n"): lat.append(y) file_in.close lon = [] file_in = open("C:\Users\APPLIED\Desktop\SPIE Analysis\Data\lon.txt", "r") for y in file_in.read().split("\n"): lon.append(y) file_in.close #--------------------------------------------------------------------------- lp=0 y1=2002 print y1 os.chdir("F:\\wget\\Renamed") for file in glob.glob("*.tif"): b=[] b=list(file) c = file a = [b[0],b[1],b[2],b[3]] d = [b[4],b[5],b[6]] year = int(''.join(a)) day = int(''.join(d)) dif=year-2002 if year!=y1: print "" print year if (year-1)%4==0: lp=lp+1 y1=year else: sys.stdout.write("&gt;") r=day+dif*365+lp+3 for i in range(0,274): u0 = float(os.popen('gdallocationinfo -valonly -wgs84 %s %s %s' % (c, (lon[i]), lat[i])).read()) if u0&lt;0: if u0==-9999: sheet1.cell(row=r,column=i+2).value = u0 else: sheet1.cell(row=r,column=i+2).value = 0 else: sheet1.cell(row=r,column=i+2).value = u0/1000 wt.save(f1)
type: Question
has comment: http://stackoverflow.com/comment/90205653
answer count: 1
has comment: http://stackoverflow.com/comment/90149864
has title: Python consuming all my RAM and system hangs
accepted answer: http://stackoverflow.com/a/51623453
tagged with: gdal
score: 0
has comment: http://stackoverflow.com/comment/90175956
has comment: http://stackoverflow.com/comment/90177184
has comment: http://stackoverflow.com/comment/90196682

http://stackoverflow.com/comment/90126505
score: 0
type: Comment
type: QuestionComment
has text: Indenting is very important, at the moment the code that writes is outside the `with` statement, and so the file is automatically closed. Try indenting the five lines to the same amount as your `print()` statement.
comment on: http://stackoverflow.com/q/51555643

sml
tags question: http://stackoverflow.com/q/51604346
type: Tag
tag name: sml

http://stackoverflow.com/q/51551814
accepted answer: http://stackoverflow.com/a/51552024
has comment: http://stackoverflow.com/comment/90070825
tagged with: python
has answer: http://stackoverflow.com/a/51552024
type: AnsweredQuestion
has title: Better method to check all objects' parameters with a single call
has comment: http://stackoverflow.com/comment/90070838
has comment: http://stackoverflow.com/comment/90070713
has comment: http://stackoverflow.com/comment/90072372
possible better answer: http://stackoverflow.com/a/51552082
type: Question
has comment: http://stackoverflow.com/comment/90070792
has answer: http://stackoverflow.com/a/51552082
has comment: http://stackoverflow.com/comment/90070854
linked to: http://stackoverflow.com/q/51494587
has comment: http://stackoverflow.com/comment/90070659
score: 0
answer count: 2
has body: I want to get all objects which age is less than 18. How can easily do that? Should I had to pass all objects to get_nonage to get it? class People: def __init__(self, uid, age): self.uid = uid self.age = age def get_nonage(self): # print nonage here which age&lt;18 # expected output: {1: 11, 3: 15} pass p1 = People(1, 11) p2 = People(2, 20) p3 = People(3, 15) ... People.get_nonage()

http://stackoverflow.com/q/51580179
type: Question
type: AnsweredQuestion
has body: I am facing the below issue while installing thonny ide for python. Traceback (most recent call last): File "/home/shrivatsa/.local/lib/python3.5/site-packages/thonny/workbench.py", line 287, in _init_runner runner.start() File "/home/shrivatsa/.local/lib/python3.5/site-packages/thonny/running.py", line 67, instart self.reset_backend() File "/home/shrivatsa/.local/lib/python3.5/site-packages/thonny/running.py", line 427, in reset_backend self._proxy = backend_class(configuraration_option) File "/home/shrivatsa/.local/lib/python3.5/site-packages/thonny/running.py", line 596, in __init__ self._start_new_process() File "/home/shrivatsa/.local/lib/python3.5/site-packages/thonny/running.py", line 762, in _start_new_process my_env["JEDI_LOCATION"] = self_prepare_jedi() File "/home/shrivatsa/.local/lib/python3.5/site-packages/thonny/running.py", line 703, in _prepare_jedi import jedi ImportError: No module named 'jedi' The application launches but no run button and dedug button is active.
accepted answer: http://stackoverflow.com/a/51580244
answer count: 2
has title: Python ide thonny installation error in ubuntu
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/90125844
tagged with: python
possible better answer: http://stackoverflow.com/a/51580258
has answer: http://stackoverflow.com/a/51580244
has answer: http://stackoverflow.com/a/51580258
score: 0

php
tags question: http://stackoverflow.com/q/51566465
tags question: http://stackoverflow.com/q/51621752
tag name: php
tags question: http://stackoverflow.com/q/51639115
tags question: http://stackoverflow.com/q/51637031
tags question: http://stackoverflow.com/q/51575507
tags question: http://stackoverflow.com/q/51547926
tags question: http://stackoverflow.com/q/51600710
tags question: http://stackoverflow.com/q/51574834
tags question: http://stackoverflow.com/q/51578454
tags question: http://stackoverflow.com/q/51611362
tags question: http://stackoverflow.com/q/51606276
tags question: http://stackoverflow.com/q/51577997
tags question: http://stackoverflow.com/q/51619769
type: Tag

file
type: Tag
tags question: http://stackoverflow.com/q/51548722
tags question: http://stackoverflow.com/q/51625336
tags question: http://stackoverflow.com/q/51566670
tags question: http://stackoverflow.com/q/51544608
tags question: http://stackoverflow.com/q/51566759
tags question: http://stackoverflow.com/q/51504175
tag name: file
tags question: http://stackoverflow.com/q/51566436
tags question: http://stackoverflow.com/q/51509313
tags question: http://stackoverflow.com/q/51587905
tags question: http://stackoverflow.com/q/51520172
tags question: http://stackoverflow.com/q/51526992
tags question: http://stackoverflow.com/q/51616855
tags question: http://stackoverflow.com/q/51536179
tags question: http://stackoverflow.com/q/51520989
tags question: http://stackoverflow.com/q/51525961
tags question: http://stackoverflow.com/q/51501178
tags question: http://stackoverflow.com/q/51581671
tags question: http://stackoverflow.com/q/51578454
tags question: http://stackoverflow.com/q/51638861
tags question: http://stackoverflow.com/q/51598868
tags question: http://stackoverflow.com/q/51532790
tags question: http://stackoverflow.com/q/51508906
tags question: http://stackoverflow.com/q/51508274
tags question: http://stackoverflow.com/q/51623658
tags question: http://stackoverflow.com/q/51517759
tags question: http://stackoverflow.com/q/51584192
tags question: http://stackoverflow.com/q/51529822
tags question: http://stackoverflow.com/q/51586920
tags question: http://stackoverflow.com/q/51565562
tags question: http://stackoverflow.com/q/51501974
tags question: http://stackoverflow.com/q/51623506
tags question: http://stackoverflow.com/q/51579478
tags question: http://stackoverflow.com/q/51597416
tags question: http://stackoverflow.com/q/51555834
tags question: http://stackoverflow.com/q/51503845
tags question: http://stackoverflow.com/q/51514481

http://stackoverflow.com/comment/89971316
type: Comment
has text: This does not work because c is a longer list than d, and it only adds the 2015 salaries
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51501437

http://stackoverflow.com/a/51570914
score: 0
type: AcceptedAnswer
has body: You really don't want to change this. First: Would it be possible to install pipenv and run 3.7 from there, while keeping 2.7 at the default? Yes! Install pipenv, and set up an environment where 3.7 is the default, but leave the system default at 2.7. More generally: According to PEP 394, which isn't due to be reevaluated until 2020, if you don't have a virtual environment activated: python3 runs Python 3.x python2 runs Python 2.x python usually shouldn't be used—but if you do use it, it should run Python 2.x. Usually, you'll also have, e.g., python3.7 and python2.7 to run specific 3.x and 2.x versions, although this isn't covered by any standard. Scripts like pip, and those installed by pip, should be installed with similar suffixes—but ideally, if you have multiple versions, you shouldn't run those scripts. Most of them are designed to be run as modules, so you can run python3 -m pip to run the pip for your 3.x. For a few things, it may be handy to set up shortcuts. (For example, instead of running python3 -m ipython from the command line, I usually use an iTerm profile that uses that instead of bash as my start command. If you don't use either IPython or iTerm, you can make a Terminal.app profile that runs python3.) Scripts installed as part of your platform's package manager are a whole more complicated story, but macOS doesn't have an official package manager, and Homebrew generally expects you to install Python libraries with pip, not brew, so you don't have to worry about that. Programs should have an installer—whether they install via pip or something like py2app—that creates a proper shbang line, so they run with whichever Python version they were installed with, so you don't have to worry about them. But programs that come with your OS may use something like /usr/bin/env python, and they will expect that to run the version of Python that came with your OS. For development purposes, you usually want to use virtualenv or pipenv or conda so that python runs t…
answers question: http://stackoverflow.com/q/51570306
type: Answer
accepted answer of: http://stackoverflow.com/q/51570306

http://stackoverflow.com/q/51620908
tagged with: regex
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/3906137
score: 1
has title: Inconsistent return values when using regex functions
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51620958
has body: My code is behaving strangely, and I have a feeling it has to do with the regular expressions i'm using. I'm trying to determine the number of total words, number of unique words, and number of sentences in a text file. Here is my code: import sys import re file = open('sample.txt', 'r') def word_count(file): words = [] reg_ex = r"[A-Za-z0-9']+" p = re.compile(reg_ex) for l in file: for i in p.findall(l): words.append(i) return len(words), len(set(words)) def sentence_count(file): sentences = [] reg_ex = r'[a-zA-Z0-9][.!?]' p = re.compile(reg_ex) for l in file: for i in p.findall(l): sentences.append(i) return sentences, len(sentences) sentence, sentence_count = sentence_count(file) word_count, unique_word_count = word_count(file) print('Total word count: {}\n'.format(word_count) + 'Unique words: {}\n'.format(unique_word_count) + 'Sentences: {}'.format(sentence_count)) The output is the following: Total word count: 0 Unique words: 0 Sentences: 5 What is really strange is that if I comment out the sentence_count() function, the word_count() function starts working and outputs the correct numbers. Why is this inconsistency happening? If I comment out either function, one will output the correct value while the other will output 0's. Can someone help me such that both functions work?
has comment: http://stackoverflow.com/comment/90207272
favorite count: 0
linked to: http://stackoverflow.com/q/3906137
duplicate of: http://stackoverflow.com/q/36572993
has answer: http://stackoverflow.com/a/51621000
downvote count: 1

http://stackoverflow.com/q/51602088
answer count: 1
tagged with: keras
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/42532386
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/51608754
has body: I am trying to predict neutron widths from resonance energies, using a Neural Network (I'm quite new to Keras/NNs in general so apologies in advance). There is said to be a link between resonance energies and neutron widths, and the similiarities between energy increasing monotonically this can be modelled similiar to a time series problem. In essences I have 2 columns of data with the first column being resonance energy and the other column containing the respective neutron width on each row. I have decided to use an LSTM layer to help in the networks predict by utlising previous computations. From various tutorials and other answers, it seems common to use a "look_back" argument to allow the network to use previous timesteps to help predict the current timestep when creating the dataset e.g trainX, trainY = create_dataset(train, look_back) I would like to ask regarding forming the NN: 1) Given my particular application do I need to explicitly map each resonance energy to its corresponding neutron width on the same row? 2) Look_back indicates how many previous values the NN can use to help predict the current value, but how is it incorporated with the LSTM layer? I.e I dont quite understand how both can be used? 3) At which point do I inverse the MinMaxScaler? That is the main two queries, for 1) I have assumed its okay not to, for 2) I believe it is possible but I dont really understand how. I can't quite work out what I have done wrong in the code, ideally I would like to plot the relative deviation of predicted to reference values in the train and test data once the code works. Any advice would be much appreciated: import numpy import matplotlib.pyplot as plt import pandas import math from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error # convert an array of values into a dataset matrix def create_dataset(dataset, look_back=1): dataX, dataY …
type: Question
tagged with: neural-network
has title: Forming a Multi input LSTM in Keras
tagged with: lstm
tagged with: deep-learning

http://stackoverflow.com/comment/90080877
has text: Ok thanks for the solution.
score: 0
comment on: http://stackoverflow.com/q/51556737
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51494440
type: UnansweredQuestion
tagged with: google-analytics-firebase
type: Question
has comment: http://stackoverflow.com/comment/90002358
tagged with: google-api
score: 0
tagged with: python
has title: Google API: ConnectionResetError when refreshing token
has comment: http://stackoverflow.com/comment/93814302
tagged with: google-analytics-api
has body: The following code fails with the error "ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host" on the line http = credentials.refresh(http) from googleapiclient.discovery import build import httplib2 import pickle #credentials is a GoogleCredentials object generated during the auth flow credentials = pickle.load(open("credentials.pickle", "rb")) http = httplib2.Http() http = credentials.refresh(http) service = build('analytics', 'v4', http=http) Running the code with http = credentials.authorize(http), instead of .refresh, and it works completely fine. I'm at a complete loss at this stage as to how to resolve this, any hints in the right direction would be greatly appreciated.
answer count: 0

http://stackoverflow.com/comment/90135030
score: 0
has text: It looks like it gives you a way to switch the functions out based on the type of the first argument, is that right? Thanks for updating the code, however I'm handling duplicates that might turn up, there are two `'two'` keys. I'm prepending the parent key to the nested keys to avoid losing data. I'll see if I can suss it out.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51584443

http://stackoverflow.com/comment/90061172
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51546681
has text: Why after the FALSE line, execution returns to draw_interval(1) ?

http://stackoverflow.com/comment/90227073
has text: Why not make `a` a `3x3x3` array?
type: QuestionComment
comment on: http://stackoverflow.com/q/51631249
score: 0
type: Comment

http://stackoverflow.com/comment/90094846
has text: I figured out the issue. The project url tag is for a foreign key in the model that I will be querying. I modified the get_object code in the detailview as below. def get_object(self): project=Project.objects.all() x=project.filter(projectName=self.kwargs['project']) print(self.kwargs['project']) print(self.kwargs['useCasename']) obj = get_object_or_404(UseCaseProfile, project=x.first(), useCasename=self.kwargs['useCasename']) return obj
type: AnswerComment
comment on: http://stackoverflow.com/a/51563885
score: 0
type: Comment

http://stackoverflow.com/q/51489073
type: Question
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51489147
has answer: http://stackoverflow.com/a/51492947
has answer: http://stackoverflow.com/a/51489147
has comment: http://stackoverflow.com/comment/89947109
favorite count: 0
tagged with: tkinter
upvote count: 2
accepted answer: http://stackoverflow.com/a/51492947
tagged with: python
has title: Refer to tkinter widget by its instance
score: 2
type: AnsweredQuestion
tagged with: instance
has body: I am learning Python w/ Tkinter and I recently learned the difference between the reference and the name/instance of a widget. The reference is the string you assign to a widget (which can be changed later on), but the name seems to be the actual identity of the widget (which is immutable). Essentially it seems as though the reference is a nickname of a widget because it can change overtime and be different depending on who you are talking to, while the actual name of the widget on the widget's drivers license is always the same. Specifically, in this line of code... sample_frame = Frame(root, name = 'frame1', bg = 'blue', height = 50, width = '50') "sample frame" is the reference, while 'frame1' is the name. Unless I specifically assign the string 'frame1' as the name of this frame, python automatically generates a number sequence as its name. In order to view the name of any widget you just have to add... print(str(sample_frame)) (the output in this example is .frame1) So in Tkinter if I wanted to place this frame in my GUI i would have to pack/grid/place it in the following line like so... sample_frame.pack() But what I would like to do is call the pack method on this frame widget by its name rather than its reference. Something like this... frame1.pack() #or .frame1.pack() #because of that period The problem is that Python claims frame1 was never defined, and .frame1 is invalid syntax. Does anybody know how to do something like this? Thanks. For broader context I am doing this because I iterated the creation of 21 different frames and placed them in a 3x7 grid. Because of this all 21 frames have an identical reference. BUT, I made sure to make the name of each frame corresponds with its position.

http://stackoverflow.com/comment/90088092
score: 0
has text: See update above. In the Resource manager (sorry can't post picture yet on SO) I simply went to Overview -> Network -> and looked and java.exe vs. python.exe
comment on: http://stackoverflow.com/q/51545033
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90185405
comment on: http://stackoverflow.com/a/51610194
type: AnswerComment
score: 0
type: Comment
has text: Well , Are you handling the advertisement pop up?

http://stackoverflow.com/comment/90127351
comment on: http://stackoverflow.com/q/51580727
type: Comment
type: QuestionComment
has text: I have used filter from dplyr but it is static. We need to specify the criteria. I want to take criteria from user and filter on it. And supply this selection page to user, upon his selection it should return the count to him.
score: 0

http://stackoverflow.com/comment/90015397
has text: @beepretty Use this one and see if it works: `sess = K.get_session()`. Comment the line where you create the session using tensorflow.
type: Comment
comment on: http://stackoverflow.com/a/51513333
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89974284
comment on: http://stackoverflow.com/q/51502263
score: 0
type: QuestionComment
type: Comment
has text: problem lies in the line of code np.log, log_df = np.log(1+data"M24","M23","M22","M21","M20","M19","M18","M17","M16","M15","M14","M13","M12","M11","M10","M9","M8","M7","M6","M5","M4","M3","M2","M1")

http://stackoverflow.com/comment/127316931
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/70979400
has text: This worked as the pre-processor needs to be python3
score: 0

http://stackoverflow.com/a/51635753
upvote count: 15
downvote count: 0
has body: You can use pandas with the xlsxwriter engine (the default). You need to create a format object by calling the workbook.add_format() method as outlined in the xlsxwriter docs (link here). Once you've used pandas.DataFrame.to_excel(), you can add the format using worksheet.set_column(). An example of this can be found in the xlsxwriter docs (link here). I've provided a fully reproducible example below with the expected output. import pandas as pd df = pd.DataFrame({'Ticket': ['a','b','c','d'], 'Category': [2,1,4,3]}) writer = pd.ExcelWriter('Trial Version.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1', index=False) workbook=writer.book worksheet = writer.sheets['Sheet1'] format = workbook.add_format({'text_wrap': True}) # Setting the format but not setting the column width. worksheet.set_column('A:B', None, format) writer.save() Expected Output:
score: 15
has comment: http://stackoverflow.com/comment/119163615
type: Answer
answers question: http://stackoverflow.com/q/51631138

http://stackoverflow.com/comment/90151773
type: QuestionComment
has text: If this is not part of a large, existing program, I *strongly* recommend you install Python 3 today and start using it. Trying to figure out the Python 2 approach to character encodings in 2018 is an exercise in masochism.
comment on: http://stackoverflow.com/q/51593052
score: 4
type: Comment

http://stackoverflow.com/comment/90220061
comment on: http://stackoverflow.com/q/51626953
score: 0
type: QuestionComment
type: Comment
has text: Actually, you've set the right type (I didn't see it before now, sorry). What does your `row` look like?

http://stackoverflow.com/comment/90123413
comment on: http://stackoverflow.com/q/51549534
has text: thanks a lot @eyllanesc it works!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/127948480
comment on: http://stackoverflow.com/a/51695181
score: 0
type: AnswerComment
type: Comment
has text: @Thawn that isn't the only case that the example fails. You point out also the `out` parameter, but I think `np.at` and `np.bool_` also might fail. Numpy provides perhaps the [canonical example](https://numpy.org/doc/stable/user/basics.subclassing.html#array-ufunc-for-ufuncs) of an `__array_ufunc__` for subclasses.

http://stackoverflow.com/q/51490738
score: 0
has comment: http://stackoverflow.com/comment/89950112
has body: I have a set of logarithm which are L1, L2 and L3 which I have retrieved it from the paper "An Ultra-secure Router-to-router Spontaneous Key Exchange System", 2015: And this is the result for the equations: Given the value of alpha=5, x=15 and p=97. After I implement it in Python, I got the wrong result, which is not same in the result in the table. This is the code: a=5 x=15 p=97 i1=0.958478 i2=4.238835 L1=pow(a,x+i1)%p L2=pow(a,x+i1+i2)%p L3=pow(a,x+i2)%p print ("L1",L1) print ("L2",L2) print ("L3",L3) And this is the results that I've got: L1 55.596893310546875 L2 2.15625 L3 68.87890625 Please help me to identify the errors in my code. Thank you.
has comment: http://stackoverflow.com/comment/89950173
has comment: http://stackoverflow.com/comment/89950322
has comment: http://stackoverflow.com/comment/89950278
tagged with: python
has comment: http://stackoverflow.com/comment/89952238
has comment: http://stackoverflow.com/comment/89950410
has comment: http://stackoverflow.com/comment/89950516
answer count: 0
type: UnansweredQuestion
has title: Discrete logarithm using python
has comment: http://stackoverflow.com/comment/89950049
has comment: http://stackoverflow.com/comment/89950308
tagged with: logarithm
has comment: http://stackoverflow.com/comment/89950228
has comment: http://stackoverflow.com/comment/89950097
type: Question

http://stackoverflow.com/q/51630262
has comment: http://stackoverflow.com/comment/90224861
has body: I've got a question regarding the module "subprocess". I programmed a Python-Script which calls a C-Programm to execute. The Problem: The Python-Script always waits for the other programm to finish. Is there a way to avoid this? Good' day
tagged with: python
answer count: 0
tagged with: subprocess
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1196074
has comment: http://stackoverflow.com/comment/90224865
type: Question
has title: Python subprocess always waits for programm
score: 0
duplicate of: http://stackoverflow.com/q/1196074

http://stackoverflow.com/comment/90290082
comment on: http://stackoverflow.com/q/51565946
type: Comment
has text: Are you able to put up a runnable example, including some example data?
type: QuestionComment
score: 0

http://stackoverflow.com/q/51507219
has comment: http://stackoverflow.com/comment/89983536
type: Question
has comment: http://stackoverflow.com/comment/89983551
has answer: http://stackoverflow.com/a/51507290
score: 0
answer count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/89983721
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51507298
has comment: http://stackoverflow.com/comment/89983610
has comment: http://stackoverflow.com/comment/89983538
tagged with: python
has title: Recursion gcd python
has body: def gcd(a,b): if b==0: return a else: return gcd(b,a%b) When I try to print the output of gcd with any 2 numbers I get the error "TypeError: not all arguments converted during string formatting". Any idea ?
linked to: http://stackoverflow.com/q/33286034
upvote count: 1
has comment: http://stackoverflow.com/comment/89983581
downvote count: 1

http://stackoverflow.com/comment/90101188
type: QuestionComment
comment on: http://stackoverflow.com/q/51566762
has text: Thanks @slon. let me try your solution.
score: 0
type: Comment

http://stackoverflow.com/a/51491940
score: 1
answers question: http://stackoverflow.com/q/51491593
has comment: http://stackoverflow.com/comment/89953535
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89991586
type: Answer
has body: As far as I think, you can use multiprocessing.current_process() to conditionally register this handler: from multiprocessing import current_process if current_process().name == 'MainProcess': signal.signal(signal.SIGTERM, handle_sigterm)
accepted answer of: http://stackoverflow.com/q/51491593
downvote count: 0

kivy
tags question: http://stackoverflow.com/q/51528045
type: Tag
tags question: http://stackoverflow.com/q/51560637
tags question: http://stackoverflow.com/q/51616542
tags question: http://stackoverflow.com/q/51541494
tags question: http://stackoverflow.com/q/51509019
tags question: http://stackoverflow.com/q/51566492
tags question: http://stackoverflow.com/q/51579029
tags question: http://stackoverflow.com/q/51625840
tags question: http://stackoverflow.com/q/51551081
tags question: http://stackoverflow.com/q/51603822
tags question: http://stackoverflow.com/q/51558019
tags question: http://stackoverflow.com/q/51599993
tags question: http://stackoverflow.com/q/51494886
tags question: http://stackoverflow.com/q/51552017
tags question: http://stackoverflow.com/q/51496685
tags question: http://stackoverflow.com/q/51545587
tag name: kivy
tags question: http://stackoverflow.com/q/51546327
tags question: http://stackoverflow.com/q/51574976
tags question: http://stackoverflow.com/q/51620484
tags question: http://stackoverflow.com/q/51569131
tags question: http://stackoverflow.com/q/51499085
tags question: http://stackoverflow.com/q/51581248
tags question: http://stackoverflow.com/q/51503288
tags question: http://stackoverflow.com/q/51515471
tags question: http://stackoverflow.com/q/51615388
tags question: http://stackoverflow.com/q/51549972
tags question: http://stackoverflow.com/q/51510772
tags question: http://stackoverflow.com/q/51616095

http://stackoverflow.com/comment/90121681
comment on: http://stackoverflow.com/q/51578072
type: Comment
type: QuestionComment
has text: You will have to create two input fields for them
score: 0

http://stackoverflow.com/comment/90164289
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51597849
has text: My guess is that the best approach is to create the `zeros` target array, and copy columns one by one into the desired slot.

http://stackoverflow.com/comment/90099530
comment on: http://stackoverflow.com/a/51566375
has text: That makes sense for sure! I ran this code and still nothing is being produced on my GUI.
score: 0
type: AnswerComment
type: Comment

code-duplication
tag name: code-duplication
tags question: http://stackoverflow.com/q/51639411
type: Tag

http://stackoverflow.com/q/51637323
downvote count: 0
has body: Problem: I want to create a list of lambda functions using **kwargs which are iterated in the list. Similar questions (e.g., e.g.) exist, but they do not consider iterating over **kwargs. The problem, as before, is that the value of kwargs in the lambda function is evaluated "lazily" after creation in the list, meaning the last value assigned during the iteration is passed to all lambda functions. I've verified this is a 'problem' for classic loops as well as comprehensions. (2a) is not, having the value argset from the last iteration of the comprehension assigned to all **kwargs. (3a) is worse, having both the values of argset and i from the last iteration assigned to x and **kwargs. MWE Code def strfun(x,**kwargs): return 'x: {} | kwargs: {}'.format(x,kwargs) argsets = [ {'foo': 'bar'}, {'baz': 'qux'}, ] # (1) expected behaviour: print '(1) '+str([strfun(i,**argset) for i,argset in enumerate(argsets)]) # (2) unexpected behaviour: funs = [lambda x: strfun(x,**argset) for argset in argsets] print '(2) '+str([fun(i) for i,fun in enumerate(funs)]) # (3) unexpected behaviour: funs = [lambda : strfun(i,**argset) for i,argset in enumerate(argsets)] print '(3) '+str([fun() for fun in funs]) Output: (1) ["x: 0 | kwargs: {'foo': 'bar'}", "x: 1 | kwargs: {'baz': 'qux'}"] (2) ["x: 0 | kwargs: {'baz': 'qux'}", "x: 1 | kwargs: {'baz': 'qux'}"] (3) ["x: 1 | kwargs: {'baz': 'qux'}", "x: 1 | kwargs: {'baz': 'qux'}"] (1) is "correct". (2) is not, having the last value of argsets assigned to **kwargs for all functions ({'baz': 'qux'}). (3) is worse, having the last value of both i and argsets assigned to x and **kwargs for all functions (1 and {'baz': 'qux'}).
type: Question
accepted answer: http://stackoverflow.com/a/51637324
has comment: http://stackoverflow.com/comment/90241380
has comment: http://stackoverflow.com/comment/90239867
has title: **kwargs in list comprehension of lambda functions
has comment: http://stackoverflow.com/comment/90240861
tagged with: list-comprehension
linked to: http://stackoverflow.com/q/3431676
has answer: http://stackoverflow.com/a/51637324
upvote count: 2
linked to: http://stackoverflow.com/q/452610
duplicate of: http://stackoverflow.com/q/3431676
answer count: 1
tagged with: keyword-argument
favorite count: 0
tagged with: python
tagged with: lambda
linked to: http://stackoverflow.com/q/12423614
linked to: http://stackoverflow.com/q/6076270
has comment: http://stackoverflow.com/comment/129603801
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/77438945
answers question: http://stackoverflow.com/q/51605360
downvote count: 0
type: Answer
has body: I know this is an old thread, but Google didn't show it to me in the results so I think it's important to add it here. Font awsome now has a Python package, which makes it very easy to use. Install it with: pip install fontawesomefree more details are here: https://fontawesome.com/docs/web/use-with/python-django
score: 1
upvote count: 1

http://stackoverflow.com/q/51536757
has comment: http://stackoverflow.com/comment/90042497
has comment: http://stackoverflow.com/comment/90041313
has comment: http://stackoverflow.com/comment/90042964
tagged with: http://stackoverflow.com/tag/xml
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90041309
has comment: http://stackoverflow.com/comment/90042372
type: UnansweredQuestion
tagged with: python
has title: Update XML values using Python
has comment: http://stackoverflow.com/comment/90042974
answer count: 0
has body: I have a number of XML documents (c. 100,000 lines each) which I need to update the values of using an CSV document which has the correct values in. The data relates to buildings and each building has a reference number stored like this &lt;Property Version="1" ID="PY303466" IDType="Test" Reference="12345" Name="Test1; July 2018"&gt; And then the building data is stored within the children / sub-children of this tag. My thinking is that I can somehow extrapolate the reference number, then iterate through the various tags and then replace the values in the XML document with the values in the CSV. I'm relatively new to Python, and very new to XML - with the exception of a bit of web-scraping. I am wondering if my use case is viable, and if anyone has any experience doing something like this is there any guidance / tips you could give me? I have struggled to find resources for this type of task online.
score: 0
type: Question
has comment: http://stackoverflow.com/comment/90043175

http://stackoverflow.com/comment/90164377
has text: Accepted. Thanks cruisepandey!
comment on: http://stackoverflow.com/a/51596840
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90010590
score: 0
type: Comment
type: QuestionComment
has text: Django error page prints the value of ALLOWED_HOSTS setting. See what value you get there.
comment on: http://stackoverflow.com/q/51520721

http://stackoverflow.com/comment/90018684
type: Comment
type: QuestionComment
score: 1
has text: What do you want to to is sequence to sequence prediction. You can find some LSTM examples if you search for that term. Anyway stock prediction does not really work well.
comment on: http://stackoverflow.com/q/51506404

http://stackoverflow.com/comment/90058075
score: 0
comment on: http://stackoverflow.com/a/51544557
type: Comment
type: AnswerComment
has text: check my comment below, you can access the function although it has the same name as the instance variable

http://stackoverflow.com/a/51581377
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51581248
has comment: http://stackoverflow.com/comment/92294731
upvote count: 2
has body: Downgrade your Cython. Below is a list of Cython compatible with Kivy. sudo pip install --upgrade cython==x.yy.z Working versions Kivy 1.11.0.dev0 -&gt; Cython==0.28.3 Kivy 1.10.1 -&gt; Cython==0.28.2 Kivy 1.10.0 -&gt; Cython==0.25.2 Kivy 1.9.1 -&gt; Cython==0.23.1 Kivy 1.9.0 -&gt; Cython==0.21.2
has comment: http://stackoverflow.com/comment/90128194

http://stackoverflow.com/q/51541895
has comment: http://stackoverflow.com/comment/90051557
has body: how to split a string into words of 2 letters. Like given string is "HelloThere" now i want to make it ["He","ll","oT","he","re"]. Please help to code that in python.
type: Question
score: -1
has title: Split the string into words
linked to: http://stackoverflow.com/q/9475241
downvote count: 2
upvote count: 1
answer count: 1
tagged with: string
duplicate of: http://stackoverflow.com/q/9475241
favorite count: 0
has answer: http://stackoverflow.com/a/51542014
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90051701
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90192537
type: AnswerComment
score: 0
type: Comment
has text: And for the normalization I computed the area by summing the area of rectangles whose width is x[i+1]-x[i] and height is (y[i+1]+y[i])*0.5 (mean between the two y values). Then I normalized all y values by this so that the area under the curve is now 1.
comment on: http://stackoverflow.com/a/51612927

http://stackoverflow.com/q/51524123
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51524450
favorite count: 0
has comment: http://stackoverflow.com/comment/90017363
tagged with: python
type: AnsweredQuestion
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51524450
tagged with: row
score: 1
has title: How to get last five consecutive values in pandas data frame row?
has body: If I have Pandas Data Frame like this: 0 1 5 7 3 7 1 9 2 NaN 4 3 NaN 3 2 1 1 3 2 8 4 2 NaN 2 NaN 3 1 0 4 1 2 1 5 1 NaN 7 3 2 1 3 5 0 NaN 2 1 3 1 4 5 3 1 2 NaN 1 3 1 2 NaN 2 1 How can I find the last five consecutive values in each row? Like this below: 3 7 1 9 2 3 1 0 4 1 2 1 3 5 0 4 5 3 1 2
has comment: http://stackoverflow.com/comment/90017302
tagged with: pandas

http://stackoverflow.com/q/51593062
has body: I would like to have a function in an object that creates a member of a certain behavior. Similarly to using the @property decorator. But without having to declare the getter and the setter function. I would like to create many members of a custom behaviour with the same getter and setter functions. However this example does not work. When I run it, the new_prop member is a property object, not a member. How can I achieve my goal? class MyClass(): def __init__(self): self.new_prop("my_prop1") self.new_prop("my_prop2") self.new_prop("my_prop3") def new_prop(self, name): def getter(self): this_prop = getattr(self, "_" + name) if this_prop is None: return "This is None!" else: return this_prop def setter(self, value): setattr(self, "_" + name, value) setattr(self, name, property(getter, setter)) setattr(self, "_" + name, None) if __name__ == "__main__": my_class = MyClass() print(type(my_class.my_prop1))
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51593245
favorite count: 0
possible better answer: http://stackoverflow.com/a/51593145
has title: Property creator function
has answer: http://stackoverflow.com/a/51593145
tagged with: python
tagged with: properties
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51593245

http://stackoverflow.com/comment/89948379
type: Comment
type: AnswerComment
has text: Not sure which line you are referring to. But you can make if it is greater than 1: make the value plus one.
comment on: http://stackoverflow.com/a/51489698
score: 0

http://stackoverflow.com/comment/89992800
type: QuestionComment
comment on: http://stackoverflow.com/q/51511972
has text: The correct thing to do, if you are trying to sort by `id_student` is either `df.sort_values(by='id_student', inplace=True)` or `df = df.sort_values(by='id_student')`. This will ensure the corresponding rows will be sorted.
score: 1
type: Comment

http://stackoverflow.com/comment/90039929
has text: where should I change it? I placed the 2.40 in system PATH and removed 2.4 from my computer. Are you sure 2.4 and 2.40 are not the same thing?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51533985

http://stackoverflow.com/q/51560635
has body: I've created a Flask API connecting to an RDS Aurora database using the Postgres engine. The endpoints work fine, and I can connect to them using Postman and cURL. When I try to connect via a unittest script, however, I receive the following error: fe_sendauth: no password supplied I'm not sure why it would only occur when tests are being run, does anyone have any insight?
score: 0
answer count: 2
tagged with: postgresql
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52350852
tagged with: python
tagged with: rds
has title: Receiving 'fe_sendauth: no password supplied' error using AWS Aurora database with Postgres engine, but only when performing unit tests
tagged with: amazon-aurora
tagged with: python-unittest
has answer: http://stackoverflow.com/a/52364820
type: Question

http://stackoverflow.com/a/51491145
has body: Let's use timeit module to measure the performance: from collections import deque from timeit import timeit class Stack1: def __init__(self): self.s = deque() def push(self, data): self.s.append(data) def pop(self): try: self.s.pop() except Exception as e: print(e) def __str__(self): l = [] for i in self.s: l.append(str(i)) if l == []: return 'Stack is Empty' else: return ' '.join(l) class Stack2: def __init__(self): self.s = deque() def push(self, data): self.s.append(data) def pop(self): try: self.s.pop() except Exception as e: print(e) def __str__(self): return str(self.s) stack1 = Stack1() stack1.push(1) stack1.push(2) stack1.push(3) stack2 = Stack2() stack2.push(1) stack2.push(2) stack2.push(3) def test_func1(): s = str(stack1) def test_func2(): s = str(stack2) print(timeit('test_func1()', globals=globals(), number=1_000_000)) print(timeit('test_func2()', globals=globals(), number=1_000_000)) Output is (1 million calls each): 1.818193725997844 1.463878423001006 So Stack2 with simple str() call is ~20% faster.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51488861

http://stackoverflow.com/q/51571278
has comment: http://stackoverflow.com/comment/90117404
tagged with: rpm
score: 0
tagged with: version
type: UnansweredQuestion
tagged with: python
has body: I have a situation in which I have two list list1 and list2 : list1 is prerequisites rpm for application and list2 is the list of rpm's in the system list1 = ["binutils-2.23.52.0.1-12.el7.x86_64", "compat-libcap1-1.10-3.el7.x86_64", "compat-libstdc++-33-3.2.3-71.el7.i686", "compat-libstdc++-33-3.2.3-71.el7.x86_64"] list2 =['acl-2.2.51-12.el7.x86_64', 'adcli-0.8.1-3.el7.x86_64', 'audit-2.7.6-3.el7.x86_64', 'audit-libs-2.7.6-3.el7.i686', 'binutils-2.25.1-32.base.el7_4.2.x86_64','compat-libstdc++-33-3.2.3-72.el7.i686'] Created two dictionaries using regex : new_dict[match.group(1)] = {"name": s, "version": match.group ( 2 ), "build": match.group ( 3 ),"os": match.group ( 4 ), "arch": match.group ( 5 )} old_dict[match1.group ( 1 )] = {"name": i, "version": match1.group ( 2 ), "build": match1.group ( 3 ),"os": match1.group ( 4 ), "arch": match1.group ( 5 )} t_old = old_dict['libaio']['name'] print "t_old",t_old t_new = new_dict['libaio']['name'] print "t_new",t_new result =rpm.compare_packages(t_new, t_old) print result The output it get : t_old libaio-0.3.109-9.el7.x86_64 t_new libaio-0.3.109-13.el7.x86_64 1 t_new is newer I am stuck at here for single value it works but how do I do it for all keys for old_dict ?
answer count: 0
has comment: http://stackoverflow.com/comment/90111158
has comment: http://stackoverflow.com/comment/90111480
type: Question
has title: How do I compare list of Rpm versions in python

http://stackoverflow.com/q/51597073
tagged with: pandas
has answer: http://stackoverflow.com/a/51722161
downvote count: 0
accepted answer: http://stackoverflow.com/a/51722161
has title: python - No module named dill while using pickle.load()
favorite count: 0
has comment: http://stackoverflow.com/comment/90184247
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/90180573
type: AnsweredQuestion
tagged with: dill
has comment: http://stackoverflow.com/comment/90180305
upvote count: 10
has body: I have dill installed in my python 2.7 but when I try to unpickle my model it says "No module named dill". The pickled file contains pandas series. EDIT : Here's the snapshot of the traceback on ElasticBeanstalk environment File "/opt/python/current/app/app/models/classification.py", line 663, in __init__ self.lookupdict = pickle.load(open(&lt;filepath&gt;)) 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 1096, in load_global klass = self.find_class(module, name) File "/usr/lib64/python2.7/pickle.py", line 1130, in find_class __import__(module) File "/opt/python/run/venv/local/lib64/python2.7/site-packages/gevent/builtins.py", line 93, in __import__ result = _import(*args, **kwargs) ImportError: No module named dill
has comment: http://stackoverflow.com/comment/90160301
type: Question
possible better answer: http://stackoverflow.com/a/51615430
score: 10
has comment: http://stackoverflow.com/comment/90181029
has comment: http://stackoverflow.com/comment/90160184
has answer: http://stackoverflow.com/a/51615430
answer count: 2

http://stackoverflow.com/q/51554503
has comment: http://stackoverflow.com/comment/90075861
tagged with: python
has title: How to create common alias for all cells in a column in Excel automatically through scripting
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51556893
has answer: http://stackoverflow.com/a/51567400
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/90076839
score: 0
answer count: 2
has body: I have an Excel workbook with close to 90 columns. I would like to create column alias for each column in the workbook, so that it will be easier for me to use the respective columns in formulas. Normally, I would select each column in the workbook and type in my alias for the column into the Cell Reference Bar at the top Is there a way to do this automatically, because i have a lot of columns? Especially in Python ? I tried the pandas.Series.to_excel function which has the header attribute. However all it does is change the column names to the string specified and does not modify the alias for all the cells in the column. Thanks a lot for your help

http://stackoverflow.com/a/51946677
score: 1
type: AcceptedAnswer
has body: Okay I solved the Problem. It's not my favorite solution but it works: # Set mouse back to visible window when leaving 1920x1080 def mouse_pos(self, window, pos): try: #pos_width = int(pos[0]) #pos_height = int(pos[1]) if int(pos[0]) &lt;= 0: # Mouse outside, LEFT window.mouse_pos = (5, int(pos[1])) if int(pos[0]) &gt; self.win_width: # Mouse outside, RIGHT window.mouse_pos = (1900, int(pos[1])) if int(pos[1]) &lt; 0: # Mouse outside, BOTTOM window.mouse_pos = (int(pos[0]), 20) if int(pos[1]) &gt; self.win_height: # Mouse outside, TOP window.mouse_pos = (int(pos[0]), 1060) The cursor is moved back when he leaves the window.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51558019
type: Answer
answers question: http://stackoverflow.com/q/51558019
upvote count: 1

http://stackoverflow.com/q/51515176
type: Question
upvote count: 0
has title: can not find the error in my code
favorite count: 0
answer count: 1
score: -1
has comment: http://stackoverflow.com/comment/89998787
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89998915
type: UnansweredQuestion
has body: This code takes in an input of the form: a b c Where a is the number of rows of chairs, b is the number of chairs per row, and c is the number of people attending. I need to output in the form: d e Where d is the number of people who can sit, and e is the number of people who will be forced to stand. There may be more people than seats, or vice versa, and there may be the perfect amount, but I need to calculate it. Here is my code to do this, can you help me find my bug, it is failing some test cases. lines is a list containing the input lines[0] is the first line lines[1] is the second lines[0] = lines[0].rstrip().split() seats = int(lines[0][0]) * int(lines[0][1]) if seats &lt;= int(lines[1]): standing = int(lines[1]) - seats sitting = seats else: standing = 0 sitting = int(lines[1])
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/89998897
has answer: http://stackoverflow.com/a/51515486

http://stackoverflow.com/q/51600237
has comment: http://stackoverflow.com/comment/90173540
has comment: http://stackoverflow.com/comment/90173470
tagged with: regex
favorite count: 0
has comment: http://stackoverflow.com/comment/90179754
tagged with: python-3.x
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: I will start by describing my problem. I have a binary file (consider it a relatively large file , e.g. 1GiB) consisting of sequences of 8-bytes. I need to create two fast routines: to search this file for the index of the first 8-byte sequence equal to 0x0000000000000000. to search this file for the index of the first 8-byte sequence different from 0xFFFFFFFFFFFFFFFF. Note that both routines need to search aligned sequences, meaning that the match should start at the beginning of a sequence. I can change the file format (as I did below), but I need it to be able to represent a giant list of integers. Furthermore, this file will be accessed concurrently (read / update) from lots of scripts (lets say, about 100), but I'm using fcntl.flock to avoid a disaster. So far, I added a byte separator (\xAA) before every 8-byte sequence to make it easier to search without clashes. Hence, I consider the first problem solved, since I can use mmap.find to search for the first occurence of 0xAA0000000000000000, but I'm having problems to solve the second. Currently, to solve the second problem, I'm using the regex below applied to mmap, but I don't know if and how I can improve it further (I broke it into multiple lines to make it easier to read). b"\xaa(?:" \ b"[^\xff].......|" \ b".[^\xff]......|" \ b"..[^\xff].....|" \ b"...[^\xff]....|" \ b"....[^\xff]...|" \ b".....[^\xff]..|" \ b"......[^\xff].|" \ b".......[^\xff])" To test the performance of both methods, I made the stress test below. It creates a ~ 1GiB file containing the worst case for each problem, i.e., where the search needs to fully parse each sequence, and tries to execute the solutions I proposed above. import re import mmap import time zeros = b"\xaa" + (b"\x00" * 8) ones = b"\xaa" + (b"\xff" * 8) regex = b"\xaa(?:" \ b"[^\xff].......|" \ b".[^\xff]......|" \ b"..[^\xff].....|" \ b"...[^\xff]....|" \ b"....[^\xff]...|" \ b".....[^\xff]..|" \ b"......[^\xff].|" \ b".......[^\xff])" reg = re.compile(regex) file = o…
tagged with: mmap
tagged with: python
has comment: http://stackoverflow.com/comment/90167506
tagged with: performance
has comment: http://stackoverflow.com/comment/90167778
type: Question
has comment: http://stackoverflow.com/comment/90200752
has title: Python find first (non-)matching fixed-width word on a large file
downvote count: 0

http://stackoverflow.com/comment/89954474
type: Comment
score: 0
type: AnswerComment
has text: Don't use the get object. Just pass in an actual value for that field. Then you can understand how to put a variable in it.
comment on: http://stackoverflow.com/a/51489605

http://stackoverflow.com/a/51568893
type: Answer
has comment: http://stackoverflow.com/comment/90104083
has body: Python complaining about bytes-like objects is usually because whatever string you're trying to alter is encoded. Instead of if i.endswith(".jpg")], try if i.decode().endswith(".jpg")].
has comment: http://stackoverflow.com/comment/90103871
has comment: http://stackoverflow.com/comment/90110515
score: 0
answers question: http://stackoverflow.com/q/51568819

http://stackoverflow.com/comment/90111171
score: 0
type: Comment
has text: @B.Mr.W. true. Just do `df.sort_values(by='date')` before everything
comment on: http://stackoverflow.com/a/51572435
type: AnswerComment

http://stackoverflow.com/q/51566284
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51566375
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90099522
accepted answer: http://stackoverflow.com/a/51566375
has title: Printing variables in tkinter GUI
downvote count: 0
tagged with: variables
has comment: http://stackoverflow.com/comment/90099345
has comment: http://stackoverflow.com/comment/90099462
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90099287
tagged with: python
has comment: http://stackoverflow.com/comment/90099569
favorite count: 0
has body: This is my code: import pandas as pd from tkinter import * master = Tk() label1= Label(master, text='Department') label1.grid(row=0, column=0) textBox = Text(master, height=1, width=10) textBox.grid(row=0, column=1) def retrieve_input(): Department = textBox.get("1.0","end-1c") fileread = pd.read_csv('50.csv', encoding='latin-1') filevalue = fileread.loc[fileread['Customer'].str.contains(Department, na=False)] def printSomething(): label = Label(master, textvariable=filevalue) label.grid(row=3, column=1) button1 = Button(master,text="Show Values", command=lambda: retrieve_input()) button1.grid(row=2, column=1) mainloop( ) I have searched around Stack Overflow of how to do this, and was able to construct my code up until this point, However when I click the Show values button, nothing happens. I could find nowhere online that helped address this issue. Is there something fundamentally wrong with my code? Using Python 3.7
has comment: http://stackoverflow.com/comment/90099536
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90099346
possible better answer: http://stackoverflow.com/a/51566468
upvote count: 1
has answer: http://stackoverflow.com/a/51566468

http://stackoverflow.com/q/51540884
has comment: http://stackoverflow.com/comment/90392525
answer count: 0
downvote count: 0
type: UnansweredQuestion
has title: How to restrict Nexus OSS to specific PyPI package?
has comment: http://stackoverflow.com/comment/90436696
tagged with: proxy
has comment: http://stackoverflow.com/comment/111104258
score: 1
favorite count: 0
type: Question
tagged with: nexus
has comment: http://stackoverflow.com/comment/90510972
upvote count: 1
tagged with: python
has body: I have one group-repository (local + proxy to pypi . org). Also I have my own package with name N, which is also listed ony PyPI with name N (but it's completely different). How to make trick that Nexus blocks all browse and read access to PyPI server ONLY for this specific package (with name N)?
tagged with: pypi

http://stackoverflow.com/comment/90173744
score: 0
has text: @Sharkfan1781110 sir, please take a look at the output. Not once have you hinted they were strings. I've assumed they've been lists all this time because that's what you've lead us to believe. What do I do now?
comment on: http://stackoverflow.com/a/51586783
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51566579
tagged with: python
possible better answer: http://stackoverflow.com/a/51566598
has body: Given a dataframe df, I would like to generate a new variable/column for each row based on the values in the previous n rows (for example previous 3). For example, given the following: INPUT A B C 10 2 59.4 53 3 71.5 32 2 70.4 24 3 82.1 Calculation for D: if in the actual row in C or previous 3 rows in C there are 2 or more cells > 70 then 1, else 0 OUTPUT A B C D 10 2 59.4 0 53 3 71.5 0 32 2 70.4 1 24 3 82.1 1 How should I do it in pandas?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51567420
type: Question
has comment: http://stackoverflow.com/comment/90099851
has answer: http://stackoverflow.com/a/51567420
has answer: http://stackoverflow.com/a/51566598
has title: how to create a new boolean column that processes information from previous n rows
score: 0
answer count: 2
tagged with: pandas

http://stackoverflow.com/q/51612443
has body: I have the following dataframe: df = pd.DataFrame( data=[ ['X', '1'],[float('nan'),'2'],[float('nan'),'3'], ['Y', '4'],[float('nan'),'5'],[float('nan'),'6']]) 0 1 0 X 1 1 NaN 2 2 NaN 3 3 Y 4 4 NaN 5 5 NaN 6 How can I transform that dataframe to flatten the second column into a list/array for each new value in column 0? After the transform it should look like that: 0 1 0 X [1,2,3] 3 Y [4,5,6] Preserving of the index isn't important. Since I'm pandas beginner I have a hard time to solve it without iterating over it with a for loop.
favorite count: 0
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51612516
type: AnsweredQuestion
has title: How to flatten a column in a dataframe
type: Question
score: 2
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51612516
tagged with: pandas

http://stackoverflow.com/a/51610341
upvote count: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90271020
type: Answer
accepted answer of: http://stackoverflow.com/q/51610074
has comment: http://stackoverflow.com/comment/101585735
downvote count: 0
answers question: http://stackoverflow.com/q/51610074
has comment: http://stackoverflow.com/comment/90271834
has body: Create handler in main thread and manually create an event loop in child thread. import asyncio import threading from aiohttp import web def aiohttp_server(): def say_hello(request): return web.Response(text='Hello, world') app = web.Application(debug=True) app.add_routes([web.get('/', say_hello)]) handler = app.make_handler() return handler def run_server(handler): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) server = loop.create_server(handler, host='127.0.0.1', port=8089) loop.run_until_complete(server) loop.run_forever() t = threading.Thread(target=run_server, args=(aiohttp_server(),)) t.start() Update For new aiohttp, use the following, thank @Auyer for notification. import asyncio import threading from aiohttp import web def aiohttp_server(): def say_hello(request): return web.Response(text='Hello, world') app = web.Application() app.add_routes([web.get('/', say_hello)]) runner = web.AppRunner(app) return runner def run_server(runner): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(runner.setup()) site = web.TCPSite(runner, 'localhost', 8080) loop.run_until_complete(site.start()) loop.run_forever() t = threading.Thread(target=run_server, args=(aiohttp_server(),)) t.start()
has comment: http://stackoverflow.com/comment/105268328
has comment: http://stackoverflow.com/comment/94006940
score: 7
has comment: http://stackoverflow.com/comment/90225344

http://stackoverflow.com/comment/92736258
has text: Same issue - any update?
score: 0
comment on: http://stackoverflow.com/q/51492621
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51572354
tagged with: pandas
answer count: 1
downvote count: 0
has body: Say I have a DataFrame like this one: df = pd.DataFrame(['spam_eggs', 'tomato_spam'], columns=['Monty']) I would like to end up with a DataFrame that looks like this: Monty_eggs Monty_spam Monty_tomato 0 1.000000 1.000000 0.000000 1 0.000000 1.000000 1.000000 That is to say - for each row, count how many times the token appears. The tokens in the original DataFrame are separated by underscores.
favorite count: 0
accepted answer: http://stackoverflow.com/a/51572418
tagged with: python
tagged with: text
type: AnsweredQuestion
score: 1
has title: Count how many times each token appears in each rows of a DataFrame
upvote count: 1
type: Question
tagged with: counting
has answer: http://stackoverflow.com/a/51572418

http://stackoverflow.com/q/51574633
has comment: http://stackoverflow.com/comment/90115162
has comment: http://stackoverflow.com/comment/90115262
type: Question
has comment: http://stackoverflow.com/comment/90115081
has comment: http://stackoverflow.com/comment/90115234
has body: for this case, it ask me to do a indirect recursion. for "def count_less" function. which mean count the number of nodes which is less than the given value.For my code I will have attributeError. Can anyone help me to check my code? class BST: """A Binary Search Tree.""" def __init__(self, container=[]): """(BST, list) -&gt; NoneType Initialize this BST by inserting the items from container (default []) one by one, in the order given. """ # Initialize empty tree. self.root = None # Insert every item from container. for item in container: self.insert(item) def __str__(self): """(BST) -&gt; str Return a "sideways" representation of the values in this BST, with right subtrees above nodes above left subtrees and each value preceded by a number of TAB characters equal to its depth. """ if self.root: return self.root._str("") else: return "" def count_less(self, item): """(BST, object) -&gt; int Return the number of items in this BST that are strictly less than item. """ if self.root: return self.root.count_less(item) else: return 0 I need to write the function body in this "_BSTNode" class, and call the class method in above "BST" class. class _BSTNode: """A node in a BST.""" def __init__(self, item, left=None, right=None): """(_BSTNode, object, _BSTNode, _BSTNode) -&gt; NoneType Initialize this node to store item and have children left and right. """ self.item = item self.left = left self.right = right def _str(self, indent): """(_BSTNode, str) -&gt; str Return a "sideways" representation of the values in the BST rooted at this node, with right subtrees above nodes above left subtrees and each value preceded by a number of TAB characters equal to its depth, plus indent. """ if self.right: right_str = self.right._str(indent + "\t") else: right_str = "" if self.left: left_str = self.left._str(indent + "\t") else: left_str = "" return right_str + indent + str(self.item) + "\n" + left_str def count_less(self: '_BSTNode', item: object) -&gt; int: """ Return the number of ite…
score: 0
answer count: 1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51574881
has comment: http://stackoverflow.com/comment/90115305
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90115182
has title: Indirect recursion for number of nodes in BST is less than a given value

http://stackoverflow.com/comment/90044297
score: 0
type: AnswerComment
has text: Initially I received errors for certain elements in the last loop, but that was easily fixed with a try and except block. Otherwise it works great, thanks! Just one question. Regarding the last print line, I assume that the keywords refer to the table, but I didn't quite understand what "number" and "flights" refer to and how they give you the number of daily flights. For instance, let's say that I wanna scrape the aircraft types from the table instead, could that be done by simply changing the keywords in the last line?
comment on: http://stackoverflow.com/a/51501478
type: Comment

http://stackoverflow.com/a/51577268
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51577128
has comment: http://stackoverflow.com/comment/90119940
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51577128
has comment: http://stackoverflow.com/comment/90119918
has comment: http://stackoverflow.com/comment/90119957
score: 1
has body: I don't know how specific your regex needs to be, but your current one isn't working because of the } after the ;....this works: re.search(r'__WML_REDUX_INITIAL_STATE__ = (.*?);}\s*$', redux, re.M)

http://stackoverflow.com/q/51537241
tagged with: python
type: AnsweredQuestion
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/51537291
answer count: 1
has body: I am trying to groupby on salary column to get frequency of each salary category as below : def PROC_FREQ(dataset,arg1): x= dataset.groupby(arg1)[arg1[-1]].agg(({'Frequency':'count'})) print('\n') print(x) print('\n') PROC_FREQ(df,['SAL']) But it is giving below output where SAL and FREQUENCY headers are not propery aligned: Frequency SAL 100 2 200 1 300 1 I want output like below so that SAL and FREQUENCY headers should be properly to aligned to each other: SAL Frequency 100 2 200 1 300 1 Please help.
score: 0
has title: Python : Formatting issue with Groupby
has answer: http://stackoverflow.com/a/51537291

http://stackoverflow.com/a/51602260
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51602116
score: 1
has body: This might be slow, but it should solve the issue. df['var3'] = 0 for i in df.itertuples(): if i.var2 &gt; 3: amt = i.var0 - i.var1 df.loc[i.Index,'var3'] = amt else: amt = i.var0 - i.var2 df.loc[i.Index,'var3'] = amt

http://stackoverflow.com/q/51613764
tagged with: pandas
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/90193583
has answer: http://stackoverflow.com/a/51615149
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51617314
tagged with: python
has comment: http://stackoverflow.com/comment/90193545
linked to: http://stackoverflow.com/q/44635626
score: -1
has comment: http://stackoverflow.com/comment/90193482
has answer: http://stackoverflow.com/a/51614380
possible better answer: http://stackoverflow.com/a/51614920
has title: Create new columns from aggregated categories 2
downvote count: 1
has answer: http://stackoverflow.com/a/51614920
accepted answer: http://stackoverflow.com/a/51614380
has body: +-------+------------+---------------+-----------------+ | INDEX | SK_ID_CURR | CREDIT_ACTIVE | CREDIT_TYPE | +-------+------------+---------------+-----------------+ | 0 | 215354 | Closed | Consumer credit | +-------+------------+---------------+-----------------+ | 1 | 215354 | Active | Credit card | +-------+------------+---------------+----------------- | 2 | 215354 | Active | Consumer credit | +-------+------------+---------------+-----------------+ | 3 | 215354 | Active | Credit card | +-------+------------+---------------+-----------------+ | 4 | 215354 | Active | Consumer credit | +-------+------------+---------------+-----------------+ | 5 | 215354 | Active | Credit card | +-------+------------+---------------+-----------------+ | 6 | 215354 | Active | Consumer credit | +-------+------------+---------------+-----------------+ | 7 | 162297 | Closed | Consumer credit | +-------+------------+---------------+-----------------+ | 8 | 162297 | Closed | Consumer credit | +-------+------------+---------------+-----------------+ | 9 | 162297 | Active | Credit card | +-------+------------+---------------+-----------------+ | 10 | 162297 | Active | Credit card | +-------+------------+---------------+-----------------+ | 11 | 162297 | Closed | Consumer credit | +-------+------------+---------------+-----------------+ | 12 | 162297 | Active | Mortgage | +-------+------------+---------------+-----------------+ | 13 | 402440 | Active | Consumer credit | +-------+------------+---------------+-----------------+ | 14 | 238881 | Closed | Credit card | +-------+------------+---------------+-----------------+ I have the table above. I'd like to aggregate each column per id. For example I need to count the number of active and closed credits per SK_ID_CURR, and then make a column for active_credits and closed_credits, with the counted values. And the same for CREDIT_TYPE. like: SK_ID_CURR CREDIT_ACTIVE CREDIT_CLOSED CONSUMER_CREDIT CREDIT_CARD 215354 6 1 4 3
answer count: 4

http://stackoverflow.com/comment/90117549
comment on: http://stackoverflow.com/q/51561527
score: 0
type: Comment
type: QuestionComment
has text: Which version of ROS do you use? Hint: You get a serialization error, which is always caused by the publisher. Of course, serialization only happens when someone subscribes. I've tested your example with `OccupancyGrid` and explicit serialization [here](https://gist.github.com/tik0/6a1807799c34a0970cd0a6775af36177), and I couldn't reproduce your error. Please give a full working example of your publisher, otherwise we cannot help.

http://stackoverflow.com/comment/89976024
has text: Yes! In fact, it's most likely better to use `strip` with no arguments as it will remove all whitespace.
type: AnswerComment
comment on: http://stackoverflow.com/a/51503486
score: 0
type: Comment

http://stackoverflow.com/comment/90027169
comment on: http://stackoverflow.com/q/51529415
type: Comment
type: QuestionComment
has text: sorry, my mistake. i meant `print(subprocess.call(["xdg-open", file_name]))`
score: 0

http://stackoverflow.com/a/51533120
answers question: http://stackoverflow.com/q/51533021
has comment: http://stackoverflow.com/comment/90034153
has comment: http://stackoverflow.com/comment/90034039
downvote count: 0
has comment: http://stackoverflow.com/comment/90033917
has body: In your code here - for row in tablebodies: CompanyName = row.find_element_by_xpath(".//*[@class='rpOut']/span[2]").text rpslide = browser.find_element_by_class_name('rpSlide').find_elements_by_css_selector('.accountInfo') for list in rpslide: links = row.find_element_by_xpath(".//span[2]").text print(CompanyName , links) You define links in the scope offor list in rpslide loop. But if rpslide is empty, links won't be declared at all. Declare it above the for loop like links = '' and your error should go away. for row in tablebodies: ... links = '' for list in rpslide: links = row.find_element_by_xpath(".//span[2]").text print(CompanyName , links) Also, if links prints empty, you need to figure out why rpslide is empty, probably - browser.find_element_by_class_name('rpSlide').find_elements_by_css_selecto did not find anything
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/90034056
has comment: http://stackoverflow.com/comment/90034085
score: 2

http://stackoverflow.com/a/51631005
has body: There was a network issue. I just had to add IPs of mail and smtp server. Temporary fix: Run following commands in command prompt in admin mode: route add 'IP of mail server' mask 255.255.255.255 'default gateway of your machine' route add 'IP of smtp server' mask 255.255.255.255 'default gateway of your machine' Permanant fix: Ask network team to add mail server's IP to split tunnel.
type: Answer
accepted answer of: http://stackoverflow.com/q/51613385
answers question: http://stackoverflow.com/q/51613385
score: 0
type: AcceptedAnswer

scribus
tags question: http://stackoverflow.com/q/51614774
type: Tag
tag name: scribus

http://stackoverflow.com/q/51523034
accepted answer: http://stackoverflow.com/a/51528060
has comment: http://stackoverflow.com/comment/90015152
has comment: http://stackoverflow.com/comment/90016025
tagged with: optimization
possible better answer: http://stackoverflow.com/a/51524096
has answer: http://stackoverflow.com/a/51524096
tagged with: python
linked to: http://stackoverflow.com/q/12200580
has comment: http://stackoverflow.com/comment/90027271
type: AnsweredQuestion
score: 0
tagged with: numba
has comment: http://stackoverflow.com/comment/90022095
has answer: http://stackoverflow.com/a/51528060
type: Question
has title: Python optimization with numpy min, max (or numba)
has comment: http://stackoverflow.com/comment/90015034
has body: I need to get performance optimization extremely with python, numpy. My data is like this, a1 = np.array(np.random.random(500000) * 1000) a2 = np.array(np.random.random(500000) * 5000) With different ndarray a1, a2, I want to calculate min-max gap. numpy: np.max(a1) - np.min(a2) numba: @nb.jit(nb.float64(nb.float64, nb.float64), cache=True, fastmath=True) def nb_max_min(s1, s2): return np.max(s1) - np.min(s2) But, I got disappointed result min-max(numba): 1.574092000000249 ms max-max(numpy): 1.4246419999999205 ms I want to make more fast calc within ~0.xx ms if possible. How to conquer this optimization? update I only measured max - min part. My timing code is here. import time def timing(label, fn): t0 = time.perf_counter() fn() t1 = time.perf_counter() print('{}: {} ms'.format(label, (t1 - t0) * 1000)) All my code here, @nb.jit(nb.float64(nb.float64, nb.float64), cache=True, fastmath=True) def nb_max_min(s1, s2): return np.max(s1) - np.min(s2) a1 = np.random.random(periods) * 2000 a2 = np.random.random(periods) * 1000 timing('nb_min_max', lambda: nb_max_min(a1, a2)) timing('nb_min_max', lambda: nb_max_min(a1, a2)) timing('nb_min_max', lambda: nb_max_min(a1, a2)) timing('max-max', lambda: np.max(a1) - np.min(a2)) timing('max-max', lambda: np.max(a1) - np.min(a2)) timing('max-max', lambda: np.max(a1) - np.min(a2)) And, this is result nb_min_max: 0.728947999999896 ms nb_min_max: 1.0030130000000526 ms nb_min_max: 1.3124690000001493 ms max-max: 1.662436000000156 ms max-max: 0.9315169999997153 ms max-max: 1.9570019999992638 ms also I tried timeit %timeit np.max(a1) - np.min(a2) 475 µs ± 9.72 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) I think this is the most fastest way with python. Numpy or numba's result is not different significantly. As user2699 commented, fortran is the last chance to optimize..
tagged with: numpy
answer count: 2

http://stackoverflow.com/comment/89977982
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51504391
has text: @cezar Version 2.0.7

http://stackoverflow.com/q/51639745
has answer: http://stackoverflow.com/a/51640200
possible better answer: http://stackoverflow.com/a/51639793
has comment: http://stackoverflow.com/comment/90244046
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90243962
has comment: http://stackoverflow.com/comment/90244156
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
accepted answer: http://stackoverflow.com/a/51640200
tagged with: parsing
has title: How to parse html code saved as text?
has comment: http://stackoverflow.com/comment/90243899
score: 0
upvote count: 1
downvote count: 1
type: AnsweredQuestion
tagged with: text-parsing
has answer: http://stackoverflow.com/a/51639793
has body: I have multiple .txt files containing HTML code (HTML code from web pages were copied and saved as .txt). I want to parse these files as an HTML. Are there any libraries which have similar functionality as requests+bs4 bundle and can treat input from text files as a result of usual web parsing? Thank you for your help.

http://stackoverflow.com/a/51483333
has comment: http://stackoverflow.com/comment/90101642
has comment: http://stackoverflow.com/comment/90025136
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51482990
answers question: http://stackoverflow.com/q/51482990
has body: import foo.bar as bar That should work in bar_test.py if you run pytest from the parent directory (at least, it worked for me just now). You can't use import bar in python 3 (I'm assuming that's what you're using) because it's ambiguous - see PEP-404 and a more in depth stackoverflow answer for more details. EDIT: Looking at the expanded example, it looks like the problem is that bar_test.py isn't part of the foo package (because the test directory isn't a package). If you add a __init__.py file to the test directory, pytest will happily run the test:: $ pytest foo/test/bar_test.py ===================================================================== test session starts ====================================================================== platform linux -- Python 3.5.3, pytest-3.6.3, py-1.5.4, pluggy-0.6.0 rootdir: /home/xxxx/tmp/blank, inifile: collected 1 item foo/test/bar_test.py . [100%] =================================================================== 1 passed in 0.03 seconds =================================================================== $ ls -lh foo/test/ total 12K -rw-rw-r-- 1 xxxx xxxx 95 Jul 26 14:44 bar_test.py -rw-rw-r-- 1 xxxx xxxx 0 Jul 27 16:38 __init__.py -rw-rw-r-- 1 xxxx xxxx 132 Jul 27 16:38 __init__.pyc drwxrwsr-x 2 xxxx xxxx 4.0K Jul 27 16:38 __pycache__ Note that I had to delete the __pycache__ after adding __init__.py. See the pytest docs for more information.
has comment: http://stackoverflow.com/comment/89974183
score: 1
has comment: http://stackoverflow.com/comment/90081987
has comment: http://stackoverflow.com/comment/90014847
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90155480
has comment: http://stackoverflow.com/comment/90022599
has comment: http://stackoverflow.com/comment/89944728
has comment: http://stackoverflow.com/comment/89998776
type: Answer

http://stackoverflow.com/q/51578328
tagged with: pandas
tagged with: python
has title: How to square the individual matrix value using python?
has body: Cost function implemented with Python: **Thanks for help to achieve this. import pandas as pd import numpy as np import matplotlib.pyplot as plt load_data = pd.read_csv('C:\python_program\ex1data1.txt',sep = ",",header = None) feature_vale = load_data[0] y = np.matrix(load_data[1]) m = len(feature_vale) plt.scatter(load_data[0],load_data[1],marker='+',c = 'r') plt.title("Cost_Function") plt.xlabel("Population of City in 10,000s") plt.ylabel("Profit in $10,000s") df = pd.DataFrame(pd.Series(1,index= range(0,m))) df[1] = load_data[0] X = np.matrix(df) row_theta = np.zeros(2,dtype = int) theta = np.array([row_theta]) # Transpose the array prediction = np.dot(X,theta.T) error = (prediction-y.T) error_df = pd.DataFrame(error) #square the error squared_error = np.square(error_df) sum = np.sum(squared_error) print(sum) J = np.sum(squared_error) / (2 * m) print(J) Data reference link: searchcode.com/codesearch/view/5404318
has answer: http://stackoverflow.com/a/51578561
accepted answer: http://stackoverflow.com/a/51578561
tagged with: machine-learning
type: Question
type: AnsweredQuestion
tagged with: scipy
tagged with: numpy
answer count: 1
score: 0

http://stackoverflow.com/q/51519138
has comment: http://stackoverflow.com/comment/90007101
answer count: 1
has answer: http://stackoverflow.com/a/51541516
type: UnansweredQuestion
tagged with: django-models
type: Question
tagged with: django-orm
has title: Django use queryset method in annotation
has comment: http://stackoverflow.com/comment/90012901
tagged with: django
tagged with: python
score: 0
has body: I'm working on a Django project with models for courses and sections. I have made a custom aggregate method, 'stats' for sections which outputs a dictionary of values. I would like to group my sections by instructor and annotate the respective stats to each group. What I've tried so far: I first get a Course and store it as course. course.sections.values('instructor').annotate(section_count=Count('instructor')) I would like to do something like: course.sections.values('instructor').annotate(section_count=Count('instructor'), **stats) , although that clearly doesn't work This is my Section model: class Section(models.Model): course = models.ForeignKey(Course, related_name='sections') instructor = models.CharField() average_GPA = models.DecimalField() As = models.DecimalField() Bs = models.DecimalField() Cs = models.DecimalField() Ds = models.DecimalField() Fs = models.DecimalField() withdrawals = models.PositiveIntegerField() class_size = models.PositiveIntegerField() objects = SectionQueryset.as_manager() and this is the queryset code: class SectionQueryset(models.QuerySet): def stats(self): def safe_round(val): return round(val, 2) if (type(val) is float) else val data = self.aggregate( GPA=Avg('average_GPA'), A=Avg('As'), B=Avg('Bs'), C=Avg('Cs'), D=Avg('Ds'), F=Avg('Fs'), students=Sum('class_size'), withdrawals=Sum('withdrawals')) return {key: safe_round(value) for key, value in data.items()}

http://stackoverflow.com/a/52575638
accepted answer of: http://stackoverflow.com/q/51572603
score: 1
answers question: http://stackoverflow.com/q/51572603
has comment: http://stackoverflow.com/comment/103269195
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: The endpoint should be: https://graph.facebook.com/v2.6/me/messenger_profile You could see this in the reference: Get Started Reference
upvote count: 1

http://stackoverflow.com/a/51550148
upvote count: 1
has body: To call PL/SQL procedures and packages in cx_Oracle use callproc: cursor.callproc('myproc') If the PL/SQL procedure has parameters, you will have to bind data values. myvar = cur.var(int) cur.callproc('myproc', (123, myvar)) print(myvar.getvalue()) Take a look at the cx_Oracle tutorial. Update: A new blog post from Oracle talks more about using PL/SQL with cx_Oracle.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51539132
has comment: http://stackoverflow.com/comment/90085328
type: Answer

http://stackoverflow.com/comment/90088993
type: QuestionComment
comment on: http://stackoverflow.com/q/51560617
has text: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\libnvvp;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\extras\CUPTI\libx64;
score: 0
type: Comment

http://stackoverflow.com/q/51525826
has body: I started read book about Tkinter (Tkinter GUI Application Development Blueprints) and when I began to make my text editor with the help of this book I don't really understand one part. There is a feature than can help you find words in the text. def find_text(event=None): search_toplevel = Toplevel(root) search_toplevel.title('Find Text') search_toplevel.transient(root) search_toplevel.resizable(False, False) Label(search_toplevel, text="Find All:").grid(row=0, column=0, sticky='e') search_entry_widget = Entry( search_toplevel, width=25) search_entry_widget.grid(row=0, column=1, padx=2, pady=2, sticky='we') search_entry_widget.focus_set() ignore_case_value = IntVar() Checkbutton(search_toplevel, text='Ignore Case', variable=ignore_case_value).grid( row=1, column=1, sticky='e', padx=2, pady=2) Button(search_toplevel, text="Find All", underline=0, command=lambda: search_output( search_entry_widget.get(), ignore_case_value.get(), content_text, search_toplevel, search_entry_widget) ).grid(row=0, column=2, sticky='e' + 'w', padx=2, pady=2) Lines where we create a button really hard for me. I found out that lambda-function is just like normal function but created in other way, but other stufffff is really hard.Can you please explain me what this code is actually do? (button code) full code: https://github.com/PacktPublishing/Tkinter-GUI-Application-Development-Blueprints-Second-Edition/blob/master/Chapter%2002/2.05.py
score: 0
has answer: http://stackoverflow.com/a/51526686
accepted answer: http://stackoverflow.com/a/51526686
has comment: http://stackoverflow.com/comment/90020995
answer count: 1
has title: I can't understand some find_text function in Tkinter
tagged with: python
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90020524
has comment: http://stackoverflow.com/comment/90021162
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/51593640
has comment: http://stackoverflow.com/comment/90154031
has comment: http://stackoverflow.com/comment/90153531
type: Answer
has comment: http://stackoverflow.com/comment/90154055
has comment: http://stackoverflow.com/comment/90154288
answers question: http://stackoverflow.com/q/51593524
has comment: http://stackoverflow.com/comment/90154596
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51593524
score: 3
has comment: http://stackoverflow.com/comment/90154450
has comment: http://stackoverflow.com/comment/90153996
has comment: http://stackoverflow.com/comment/90154024
upvote count: 3
has comment: http://stackoverflow.com/comment/90153605
has comment: http://stackoverflow.com/comment/90153460
type: AcceptedAnswer
has body: Try matching everything from if or elif upto last-but one : into a match-group and similarly everything after that to the last : into another group. Now you can substitute the first match followed by == and then the next match re.sub('((?:if|elif)[^:]*):([^:]*:)', r'\1 == \2', s)
has comment: http://stackoverflow.com/comment/90153947

http://stackoverflow.com/q/51548202
favorite count: 0
tagged with: classname
has body: I am using Selenium and Python to create a script for automating end-user workflow in Internet Explorer (has to be IE). When using find_element_by_id, or find_element_by_class_name, I am receiving a NoSuchElementException error. Can you help me understand why my script is not able to find the id or name for the element "servProvCode"? I have attached screenshots to provide more detail. Thank you! An error is returned against line 23: selenium.common.exceptions.NoSuchElementException: Message: Unable to find element with css selector == [id="submit"] PYTHON SCRIPT: 1 import time 2 from selenium import webdriver 3 from selenium.webdriver.common.by import By 4 from selenium.webdriver.common.keys import Keys 5 from selenium.webdriver.common.desired_capabilities import DesiredCapabilities 6 7 #create capabilities 8 capabilities = DesiredCapabilities.INTERNETEXPLORER 9 10 #delete platform and version keys 11 capabilities.pop("platform", None) 12 capabilities.pop("version", None) 13 14 #start an instance of IE 15 driver = webdriver.Ie(executable_path="C:\\LocalDev\\IEDriverServer.exe", capabilities=capabilities) 16 17 #open Accela login page 18 driver.get("https://pwms-avdev.co.arapahoe.co.us/security/hostSignon.do?signOff=true") 19 time.sleep(2) 20 21 #enter Agency 22 agency = driver.find_element_by_id("servProvCode") 23 agency.send_keys('test', Keys.ENTER) 24 time.sleep(2) 25[enter image description here][1] 26 #enter Username
has comment: http://stackoverflow.com/comment/90159015
tagged with: python
has title: Python: Unable to find element with id or class name, webdriver cannot locate id's or class name's
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/51686446
upvote count: 2
has comment: http://stackoverflow.com/comment/90177258
linked to: http://stackoverflow.com/q/40758138
has comment: http://stackoverflow.com/comment/90160892
has comment: http://stackoverflow.com/comment/90206863
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90070137
has comment: http://stackoverflow.com/comment/90159722
tagged with: internet-explorer
has comment: http://stackoverflow.com/comment/90161417
accepted answer: http://stackoverflow.com/a/51686446
type: Question
score: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51492195
score: 0
tagged with: shell
tagged with: linux
has title: how to execute linux command via python loop
has answer: http://stackoverflow.com/a/63466339
tagged with: python
has body: I have a list of files which will be used to extract by another linux script like this: gzip -dc input/test_log.gz | bin/recreate state/object_mappings.sort &gt; output/recreate.out I need to change the name test_log.gz with my list of files with python loop, how can I execute this script dynamically. here is my code: import os from subprocess import call files = os.listdir("/my directory/") files.sort() for i in files: call('gzip -dc input/test_log.gz | bin/recreate state/object_mappings.sort &gt; output/recreate.out') I dont know how to change this script with dynamic variable i??
type: AnsweredQuestion
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51492274
accepted answer: http://stackoverflow.com/a/51492274
possible better answer: http://stackoverflow.com/a/63466339

http://stackoverflow.com/q/51615073
tagged with: class
duplicate of: http://stackoverflow.com/q/1301346
tagged with: python
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
upvote count: 1
has body: I have a Component class: class Component: def __init__(self, entity): self.__entity = entity And I have a TestComponent class which inherits from Component: class TestComponent(Component): def __init__(self, entity): Component.__init__(self, entity) print(self.__entity) Then I create an instance: comp = TestComponent(entity) When I run the code I get this error: AttributeError: 'TestComponent' object has no attribute '_TestComponent__entity' This makes no sense to me as it doesn't seem to be accessing the variable from the parent class... Does anyone know how to fix this? I also tried changing Component.__init__(self, entity) to super().__init__(self, entity) and super().__init__(entity), none of which are working either.
score: 1
has title: 'ChildClassName' object has no attribute '_ParentClassName'
type: Question
linked to: http://stackoverflow.com/q/1301346
downvote count: 0

http://stackoverflow.com/comment/89974852
comment on: http://stackoverflow.com/q/51502983
score: 0
type: QuestionComment
has text: no.. which value should I use? I tried 1 but no luck
type: Comment

http://stackoverflow.com/q/51536028
accepted answer: http://stackoverflow.com/a/51545459
answer count: 2
tagged with: svgutils
downvote count: 0
score: 1
favorite count: 0
has body: I'm trying to downscale some SVGs that have a default of about 420 by 500 pixels, they are not all the same sizes, but I would like to maintain a width of 50px on the output files. This is what I've managed so far (from this): import os import svgutils path = 'path/to/files' svg_files = [f for f in os.listdir(path) if f.endswith('.svg')] for i in svg_files: svg_file = os.path.join(path, i) svg = svgutils.transform.fromfile(svg_file) original = svgutils.compose.SVG(svg_file) original.scale(.1) svg_out = os.path.splitext(svg_file)[0] + '_scale.svg' new_svg = svgutils.compose.Figure(float(svg.height) * .1, float(svg.width) * .1, original) new_svg.save(svg_out) But it only adds the &lt;g&gt; with transform, and doesn't resize the original. Moreover, the end results won't open in inkscape. Any idea what I am doing wrong here? Edit: I've had a deeper look around, so far I've managed to resize the svgs using librsvg-2.40.1-2-w32-bin.zip from this sourceforge project and adding the /bin folder to windows path, this allows me to do the following: rsvg-convert -a ".\infile.svg" -w "30" -f svg -o ".\outfile.svg" however, no color information is retained. So I'm thus far. Edit 2: The color issue happens during the conversion using rsvg-convert, it seems that it also converts hex to rgb tuple in the process. Which some viewers do not support (such as MapboxGL studio)
has answer: http://stackoverflow.com/a/51538945
tagged with: python
has answer: http://stackoverflow.com/a/51545459
possible better answer: http://stackoverflow.com/a/51538945
type: AnsweredQuestion
upvote count: 1
type: Question
has title: how to resize svgs while constraining proportions using python 3.6.5 on Windows 10 (vscode)

http://stackoverflow.com/a/51634129
downvote count: 0
has body: countApprox works faster than count, has timeout and confidence definition. I suppose you will see the runtime difference on a big datasets.
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51633822
has comment: http://stackoverflow.com/comment/90232582

http://stackoverflow.com/comment/90092735
score: 0
has text: @user3483203 then how should I achieve the purpose of initializing with None and another initializer `ini_x` will give it a numpy array with zeros?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51562730

http://stackoverflow.com/a/51541516
answers question: http://stackoverflow.com/q/51519138
has body: I was playing around with the annotations and realized I could store them as a dictionary: stats_dict = {'average_GPA': Avg('average_GPA'), 'As': Avg('As'), 'Bs': Avg('Bs'), 'Cs': Avg('Cs'), 'Ds': Avg('Ds'), 'Fs': Avg('Fs'), 'students': Sum('class_size'), 'withdrawals': Sum('withdrawals')} then I could use the ** on it in the stats method in the Section Queryset: data = self.aggregate(**stats_dict). This was equivalent to what I had before, however I then realized that I could instead do: raw_stats = {'average_GPA': (Avg,'average_GPA'), 'As': (Avg,'As'), 'Bs': (Avg,'Bs'), 'Cs': (Avg,'Cs'), 'Ds': (Avg,'Ds'), 'Fs': (Avg,'Fs'), 'students': (Sum,'class_size'), 'withdrawals': (Sum,'withdrawals')} and stats_dict = {key: t[0](t[1]) for key, t in raw_stats.items()} which allowed me to do: to_annotate = {k: t[0]('sections__'+t[1]) for k, t in raw_stats.items()} self.get_queryset().annotate(**to_annotate) in my CourseModelManager.
score: 0
type: Answer

http://stackoverflow.com/a/51526127
has body: json.dumps(list(priceDict.items())) But why do you have an OrderedDict in first place? If you pass the same list you passed to OrderedDict to json.dumps it will generate your array: json.dumps([('2017-07-24', 149.7619), ('2017-07-25', 150.4019),....]) No need for OrderedDict in this case
answers question: http://stackoverflow.com/q/51526076
has comment: http://stackoverflow.com/comment/90023265
upvote count: 3
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90020969

http://stackoverflow.com/q/51601094
has comment: http://stackoverflow.com/comment/90168736
has comment: http://stackoverflow.com/comment/90174572
type: Question
answer count: 1
tagged with: ajax
has answer: http://stackoverflow.com/a/51608139
score: 0
has title: Send data to server using POST with AJAX
has comment: http://stackoverflow.com/comment/90170417
tagged with: python
has body: Im new to Django, I want to send data to a server using AJAX and POST, and retrieve the returned data. I know that AJAX works properly since I was successful doing a GET request, but when I do a POST request, I do not receive any response data from the server. Thank you in advance. views.py def validate_username(request): if request.method == "POST" and request.is_ajax(): description = request.POST.get('the_post') projects = Project.objects.filter(user__id__icontains = request.user.id).filter(pro_description__icontains = description).values_list('pro_description') response_data = {} try: response_data['result'] = 'Success' response_data['message'] = list(projects) except: response_data['result'] = 'Unsuccessful' response_data['message'] = 'The Subprocess module did not run the script correctly.' return HttpResponse(json.dumps(response_data), content_type="application/json") index.html {% extends 'base.html'%} this is index page!! {% block body %} <!-- {% csrf_token %} No Section Project Description search Project ID Employee Name Funding Year {% if projects %} {% for project in projects%} {{project.pro_no}} {{project.pro_section}} {{project.pro_description}} {{project.pro_ID}} {% for emp in project.employee.all %} {{emp.first_name}} {% endfor %} {% for emp in project.employee.all %} {{emp.funding_year}} {% endfor %} {% endfor %} {% endif %} {% if projects.has_previous %} Previous {% endif %} Page {{projects.number}} of {{projects.paginator.num_pages}}. {% if projects.has_next %} Next {% endif %} {% block javascript %} {% endblock %} {% endblock %} urls.py url(r'^ajax/validate_username/$', views.validate_username, name = 'validate_username'),
has comment: http://stackoverflow.com/comment/90169385
has comment: http://stackoverflow.com/comment/90200508
tagged with: django
accepted answer: http://stackoverflow.com/a/51608139
has comment: http://stackoverflow.com/comment/90200413
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90174977
has comment: http://stackoverflow.com/comment/90169796

http://stackoverflow.com/q/51613821
has answer: http://stackoverflow.com/a/51614158
score: -1
type: Question
accepted answer: http://stackoverflow.com/a/51614158
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: I've created a program that shuffles through a deck of cards, deals out five cards to two individual players, and then returns the value of each player's starting deck. How do I get an object that I have put inside a list and the print out the value of that object? For example: All my cards are in a list and the program shuffles the list and chooses five cards for player: diamond1, diamond5, spade2, club6, heart9 I then want diamond 1 to equal 1, diamond5 to equal 5, and etc. I have been able to do this by putting each card in its own list but I really want to know if there's a better way to do it. Here's my code: import random diamond1, heart1, club1, spade1 = 1, 1, 1, 1 diamond2, heart2, club2, spade2 = 2, 2, 2, 2 diamond3, heart3, club3, spade3 = 3, 3, 3, 3 diamond4, heart4, club4, spade4 = 4, 4, 4, 4 diamond5, heart5, club5, spade5 = 5, 5, 5, 5 diamond6, heart6, club6, spade6 = 6, 6, 6, 6 diamond7, heart7, club7, spade7 = 7, 7, 7, 7 diamond8, heart8, club8, spade8 = 8, 8, 8, 8 diamond9, heart9, club9, spade9 = 9, 9, 9, 9 diamond10, heart10, club10, spade10 = 10, 10, 10, 10 diamondJack, heartJack, clubJack, spadeJack = 11, 11, 11, 11 diamondQueen, heartQueen, clubQueen, spadeQueen = 12, 12, 12, 12 diamondKing, heartKing, clubKing, spadeKing = 13, 13, 13, 13 cards = ["diamond1", "heart1", "club1", "spade1", "diamond2", "heart2", "club2", "spade2", "diamond3", "heart3", "club3", "spade3", "diamond4", "heart4", "club4", "spade4", "diamond5", "heart5", "club5", "spade5", "diamond6", "heart6", "club6", "spade6", "diamond7", "heart7", "club7", "spade7", "diamond8", "heart8", "club8", "spade8", "diamond9", "heart9", "club9", "spade9", "diamond10", "heart10", "club10", "spade10", "diamondJack", "heartJack", "clubJack", "spadeJack", "diamondQueen", "heartQueen", "clubQueen", "spadeQueen", "diamondKing", "heartKing", "clubKing", "spadeKing"] def player1StartingDeck(): #Tells which cards are going to be in player 1 and 2's starting hand #Player1 card1, card2, card3, card4, …
downvote count: 1
has title: Python: How to get object in a list and then return the value of that object (which is a variable)?
type: AnsweredQuestion

http://stackoverflow.com/comment/90001339
has text: Find all quoted text and remove them then operate on this modified string.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51516361

http://stackoverflow.com/comment/89939349
score: 1
has text: If the `slice_length` was consistent, and the `start` varied, it is possible to reform the result into an array, but with some sort of concatenate before or after indexing. But with variable `slice_length` you are stuck with slicing each row separately.
comment on: http://stackoverflow.com/q/51484600
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89998897
type: QuestionComment
has text: But there's already something confusing. lines is a list of lists ? or a list of ints ? `seats = int(lines[0][0]) * int(lines[0][1])` so lines is a list of list `if seats <= int(lines[1]): ` lines is a list of ints ?
score: 0
comment on: http://stackoverflow.com/q/51515176
type: Comment

http://stackoverflow.com/comment/90028031
comment on: http://stackoverflow.com/q/51529840
type: Comment
type: QuestionComment
has text: `df.groupby(df.columns, axis=1).first()`
score: 2

http://stackoverflow.com/comment/90137724
type: QuestionComment
has text: Have you made any attempt to actually solve the problem at hand? Your code doesn't seem particularly related.
score: 0
comment on: http://stackoverflow.com/q/51586003
type: Comment

http://stackoverflow.com/a/51595377
has comment: http://stackoverflow.com/comment/90156635
has comment: http://stackoverflow.com/comment/90156693
has comment: http://stackoverflow.com/comment/90157704
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90156648
accepted answer of: http://stackoverflow.com/q/51595343
has comment: http://stackoverflow.com/comment/90157026
has body: Try splitting with a negative lookahead: re.split(r'[KR](?!P)', sequence) This would be the correct answer if you want to split and consume/remove the K or R letter in the process. If you instead want to split whenever KR precedes (and P does not proceed) while retaining all characters, then we can't just do a simple re.split, because it does not support lookbehinds. One workaround might be to first do a replace all and insert marker symbols at every place where a split should happen, e.g. $, which does not appear anywhere in your current input. Then, we can do a simple split on this marker character to get the result you want. sequence = 'MYNSIYGSPFPK...' seq_new = re.sub("([KR])([^P])", r'\1$\2', sequence) # insert '$' markers result = re.split(r'\$', seq_new) # split at '$' and consume the '$' print result ['MYNSIYGSPFPK', 'INPK', 'VR', 'YK', 'TALER', 'AGFDTKPR', 'NPFSSQR', ... Demo
answers question: http://stackoverflow.com/q/51595343
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/90157752
has comment: http://stackoverflow.com/comment/90157916

http://stackoverflow.com/q/51488410
type: UnansweredQuestion
type: Question
linked to: http://stackoverflow.com/q/36798798
has comment: http://stackoverflow.com/comment/89945819
has comment: http://stackoverflow.com/comment/89945818
has title: how to get every line of my input in sys.stdin.readline() Python?
has body: print "entry the news:" news = sys.stdin.readline() I copy paste news entry and the program just run my first line news, not the other. I've searched it for many times but there were no sites can answer my problem. I'm using Python 2.7
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/89945824
tagged with: input
tagged with: python
duplicate of: http://stackoverflow.com/q/36798798
tagged with: readlines
answer count: 0

http://stackoverflow.com/a/51574514
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51574431
has body: IIUC df.pivot_table(values='Service Type', columns='Service Type' , index='ID', aggfunc=lambda k: k.name[-1]) Service Type Parts warranty Service warranty ID 10 Parts warranty Service warranty 20 Parts warranty Service warranty 30 Parts warranty Service warranty Can always rename if needed .rename(columns={'Parts warranty': 'Parts', 'Service warranty': 'Service'}) Service Type Parts Service ID 10 Parts warranty Service warranty 20 Parts warranty Service warranty 30 Parts warranty Service warranty

http://stackoverflow.com/a/51519424
has comment: http://stackoverflow.com/comment/90008247
has comment: http://stackoverflow.com/comment/90007993
has comment: http://stackoverflow.com/comment/90007910
upvote count: 11
has body: You are trying to load json usign a file name, but not data that is in the file def load_tester(path): with open(path) as f: data = json.load(f) print(data) return np.asarray(data)
has comment: http://stackoverflow.com/comment/90008407
has comment: http://stackoverflow.com/comment/90007737
type: Answer
has comment: http://stackoverflow.com/comment/100169930
score: 11
answers question: http://stackoverflow.com/q/51519311
downvote count: 0

http://stackoverflow.com/comment/91500043
type: Comment
comment on: http://stackoverflow.com/a/52093118
has text: Thank you so much, I was using rpy2 till now!
score: 0
type: AnswerComment

http://stackoverflow.com/a/51615430
upvote count: 2
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51597073
has body: Two things: 1) This looks like a $PATH issue (or, similarly, a linking issue)... You seem to have at least two python installations (one at /opt/python, presumably from something like macports, and one at /usr/lib64, and possibly a third in a venv). I'm guessing that if you carefully confirm which python you are using, and which corresponds to the pip you used, you might find dill and the other modules you are using are not all in the same python installation. 2) Note that in the first line of the traceback you seem to be using pickle.load... if you want to use dill, shouldn't you be using dill.load to unpickle the serialized object?

http://stackoverflow.com/comment/90204291
type: Comment
comment on: http://stackoverflow.com/a/51619099
has text: @ScottBoston I only knew about boxcar from when I've used it with `SciPy`. The pandas documentation on the different window types is severely lacking. I might consider submitting a pull request to the documenation if I have time to put some examples together.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90304724
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51635266
score: 0
has text: Command line download is working fine for me... having issues with this one only...@SergeBallesta

http://stackoverflow.com/comment/90135800
comment on: http://stackoverflow.com/q/51584811
has text: Out of interest, how did using `db.session` fail?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90240768
comment on: http://stackoverflow.com/q/51636361
has text: The "selection" is for the entire row, but as you can see in the image, there's also an individual selection on the cell (it's hard to see with a row selection so I didn't select one for the screenshot). A quick test in Designer shows it's not shown by default, but in the case that Maya has only exposed it, I'm interested in actually getting the information. A bit like if you were to select an excel cell in a way where you can use the arrow keys to move to different ones.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90192672
type: Comment
has text: @JerinPeterGeorge: no, since then we have an invalid form, and that form will be `render(..)`ed (and if the template is properly defined, with the errors displayed). See for example here a template: https://docs.djangoproject.com/en/2.0/topics/forms/#the-view
type: AnswerComment
comment on: http://stackoverflow.com/a/51613410
score: 0

http://stackoverflow.com/q/51489385
has title: Designate a variable as a list without overwriting it in a function
answer count: 3
tagged with: python
favorite count: 0
has body: I created a function that will flatten a nested list into an ordinary list. outputarray = [] def flattenarray(x): for elmt in x: if isinstance(elmt, float) or isinstance(elmt, int): outputarray.append(elmt) elif isinstance(elmt, list): flattenarray(elmt) return outputarray The above works perfectly, but I am trying to have the "outputarray" variable inside the function, but when I do, the recursion step will overwrite the outputarray list back into an empty list. How can I make this work to designate a list inside the function and at the same time be able to append to it without overwriting it during recursion?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51489449
has answer: http://stackoverflow.com/a/51489674
upvote count: 4
has answer: http://stackoverflow.com/a/51489772
tagged with: recursion
tagged with: list
type: Question
downvote count: 0
score: 4

http://stackoverflow.com/q/51565669
linked to: http://stackoverflow.com/q/22275350
has body: I'm trying to run this Python script: import os with open('check_door', 'r') as file: text_1 = file.readline() with open('alert_check', 'r') as file2: text_2 = file2.readline() if text_1 == 'locked' and text_2 == 'disabled': os.system('python sensor.py') using this command: watch -n 60 /home/pi/check_sensor.py I'm getting these errors: /home/pi/check_sensor.py: 1: /home/pi/check_sensor.py: import: not found /home/pi/check_sensor.py: 2: /home/pi/check_sensor.py: Syntax error: "(" unexpected What am I doing wrong ?
tagged with: linux
tagged with: python
has comment: http://stackoverflow.com/comment/90098215
linked to: http://stackoverflow.com/q/6908143
has title: Run Python script repeatedly from bash
type: Question
duplicate of: http://stackoverflow.com/q/38811153
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/22275350
duplicate of: http://stackoverflow.com/q/27563854
has answer: http://stackoverflow.com/a/51565725
accepted answer: http://stackoverflow.com/a/51565725
score: 0
answer count: 1

http://stackoverflow.com/a/51517421
has comment: http://stackoverflow.com/comment/90003959
answers question: http://stackoverflow.com/q/51517335
type: AcceptedAnswer
downvote count: 0
has body: There is a difference if you check the lengths, you just can't see it when printing; a = "hello world " print(len(a)) print(len(a.strip())) Output: 15 11
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51517335

http://stackoverflow.com/a/51944162
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51551067
has body: Don't try to install google-cloud, that package is deprecated. As you have tagged this as Storage also, I assume you intend to use GCS from Python: rather install google-cloud-storage with pip install --upgrade google-cloud-storage. It is also recommended to use virtualenv.
downvote count: 0

http://stackoverflow.com/q/51483217
tagged with: database
accepted answer: http://stackoverflow.com/a/51483484
type: AnsweredQuestion
has title: struggle trying to convert a csv into a database [Python]
has comment: http://stackoverflow.com/comment/89935574
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/51483824
favorite count: 0
has answer: http://stackoverflow.com/a/51483824
type: Question
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/89935703
tagged with: python
has comment: http://stackoverflow.com/comment/89935556
has answer: http://stackoverflow.com/a/51483484
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/89935652
has body: I'm trying to convert a csv into a database. And I found this code on the internet: import csv, sqlite3 conn = sqlite3.connect('data.db') curs = conn.cursor() curs.execute('''DROP TABLE IF EXISTS data''') curs.execute('''CREATE TABLE data(col1 INT, col2 TEXT, col3 INT, mar, loc, inc, iscr, escr)''') with open('sample.csv', 'r') as fin: reader = csv.DictReader(fin) to_db = [(i['col1'], i['col2'], i['col3'], i['col4'], i['col5'], i['col6'], i['col7'], i['col8'], ) for i in reader] curs.executemany('''INSERT INTO data (col1, col2, col3, col4, col5, col6, col7, col8) VALUES (?, ?, ?, ?, ?, ?, ?, ?)''', to_db) conn.commit conn.close() But when I run it, I get the following error: Traceback (most recent call last): File "/Users/dirkkoomen/Desktop/Python cursus/inzendopgave 4/opgave 5/xxxxx.py", line 20, in &lt;module&gt; to_db = [(i['col1'], i['col2'], i['col3'], i['mar'], i['loc'], i['inc'], i['iscr'], i['escr'], ) for i in reader] File "/Users/dirkkoomen/Desktop/Python cursus/inzendopgave 4/opgave 5/xxxxx.py", line 20, in &lt;listcomp&gt; to_db = [(i['col1'], i['col2'], i['col3'], i['mar'], i['loc'], i['inc'], i['iscr'], i['escr'], ) for i in reader] KeyError: 'col1' Does anyone know what I'm doing wrong? EDIT: this is how my csv file looks like 51,F,46,M,0,15100,531,555 52,M,29,M,2,14200,673,633 53,M,25,S,0,22200,742,998 54,M,36,M,2,1000,677,646 55,F,99,S,0,10600,608,998 56,F,45,M,2,6100,710,743 57,M,99,M,2,16500,679,646 58,F,37,M,0,7400,637,683 59,M,45,S,0,22800,683,998 60,M,22,S,0,6400,699,998 61,M,32,S,0,3100,721,998

http://stackoverflow.com/q/51522734
has comment: http://stackoverflow.com/comment/90014547
has comment: http://stackoverflow.com/comment/90014421
tagged with: python
has comment: http://stackoverflow.com/comment/90015193
has title: Python script is not producing any output
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90014766
has body: I have a python script where I'm trying to read all .txt files in a directory and determine if they return True or False for any conditions that are in my script. I don't get an error message but the script doesn't produce any output. I want the script to read in .txt files that contain text formatted in .json format. Then I want the script to determine if the .txt file matches any of the statements in my code below. I then want to output the result to a csv file. Your help is very much appreciated! #!/usr/bin/env python # regarding whether any positive results were found for the domain on VT. import csv import json import pprint import sys import os CSVPATH = 'CsvResults.csv' VTOUTPUTPATH = './output/' VTOUTPUTEXT = '.txt' #files_to_search = [f for f in os.listdir('./output/') if f[-4:] == '.txt'] #vt_result_path = files_to_search #vt_result = vt_result_check(vt_result_path) pp = pprint.PrettyPrinter(indent=4) # Check files from VirusTotal queries for any positive results # Result is false unless any nonzero positive result is true def vt_result_check(vt_result_path): vt_result = None try: vt_result = False for filename in os.listdir(path): with open(filename, 'r', encoding='utf-16') as vt_result_file: vt_data = json.load(vt_result_file) #vt_result_path = [f for f in os.listdir('./output/') if f[-4:] == '.txt'] #vt_result = None #try: # vt_result = False # with open(infile) as vt_result_file: # vt_data = json.load(vt_result_file) # Look for any positive detected referrer samples try: for sample in (vt_data['detected_referrer_samples']): if (sample['positives'] &gt; 0): vt_result = True except: pass # Look for any positive detected communicating samples try: for sample in (vt_data['detected_communicating_samples']): if (sample['positives'] &gt; 0): vt_result = True except: pass # Look for any positive detected downloaded samples try: for sample in (vt_data['detected_downloaded_samples']): if (sample['positives'] &gt; 0): vt_result = True except: pass # Look for any …
has comment: http://stackoverflow.com/comment/90014455
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51522935
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51523491

http://stackoverflow.com/a/51598085
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51597997
has body: Your line: if os.path.isfile(file_path): is not indented so it is not within the function. 'return' is after that so it is not in the function either.
type: Answer

http://stackoverflow.com/q/51523984
upvote count: 2
score: 2
type: AnsweredQuestion
has title: tkinter, integrating an interactive grid into onto a page
has comment: http://stackoverflow.com/comment/90017255
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51524162
has body: I have an end goal of creating a battleship game (with a long way to go). To begin I am trying to master having multiple windows with various widgets on them and the ability to switch between windows. Currently I am trying to get a game board to be on one of the pages that can be clicked on to change colors(the beginnings of what would happen when a player clicked a tile to guess a ship position). However, the board opens detached from my main window and when clicked on it throws the following error: File "C:/Users/thani/Desktop/Code/Py_Projects/Boiler_Plate.py", line 109, in L.bind('', lambda e, i=i, j=j: on_click(i,j,e)) NameError: name 'on_click' is not defined The section of code I am using for the board will work on its own: #import tkinter as tk is at the beginning board =[ [None]*10 for _ in range(10) ] counter = 0 root = tk.Tk() def on_click(i,j,event): global counter color = "red" if counter % 2 else "black" event.widget.config(bg=color) board[i][j] = color counter += 1 for i, row in enumerate(board): for j, column in enumerate(row): L = tk.Label(root, text=' ', bg='grey') L.grid(row=i, column=j) L.bind('&lt;Button-1&gt;', lambda e, i=i, j=j: on_click(i,j,e)) #root.mainloop() is at the end but not when integrated into the page: import tkinter as tk class Grid_Test(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 (StartPage, PageOne, PageTwo): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nesw") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() #Start page and page one omitted as they are not relevant to the issue of pagetwo's grid class PageTwo(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, te…
downvote count: 0
has comment: http://stackoverflow.com/comment/90017365
accepted answer: http://stackoverflow.com/a/51524162
favorite count: 0
has comment: http://stackoverflow.com/comment/90018048
possible better answer: http://stackoverflow.com/a/51524476
tagged with: python
has answer: http://stackoverflow.com/a/51524476
has comment: http://stackoverflow.com/comment/90016830
tagged with: tkinter

http://stackoverflow.com/comment/90124357
type: AnswerComment
score: 0
type: Comment
has text: This really does not solve the problem that OP's `numpy` module is missing a method which [should be there](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.loadtxt.html).
comment on: http://stackoverflow.com/a/51579514

http://stackoverflow.com/comment/90291012
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51633489
has text: I need to experiment with your approach will keep you posted, thanks
score: 0

http://stackoverflow.com/q/51584171
has comment: http://stackoverflow.com/comment/90134239
has comment: http://stackoverflow.com/comment/90133733
has body: I can tell many people have had issues with this but having tried all possible solutions i have made my own post which hopefully can help solve this issue specifically for me. When i try running db.create_all() i get this error (attached in pic): Error observed I understand this is because mysqldb does not support python 3. But i have also tried importing the pymysql and this didnt work either (unless of course i did that step wrong? I basically added the lines: import pymysql and then pymysql.install_as_MySQLdb() into my app.py file. I am still really new to all of this. Anybody who's had this could they explain in simple steps please?
has comment: http://stackoverflow.com/comment/90167096
linked to: http://stackoverflow.com/q/33653076
type: Question
has answer: http://stackoverflow.com/a/51585286
answer count: 1
score: 0
has title: db.create_all() issues with python 3.7 for MAC
tagged with: mysql-python
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/51508583
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89986774
accepted answer: http://stackoverflow.com/a/51514363
tagged with: python
type: AnsweredQuestion
has body: I have two arrays, one with amounts and the other with risk. I want to basically minimize the sum of the amounts and at the same time keep the sum of the risks the same. To do this, I want to multiply the Amount and Risk with a array of weights (which needs to be solved for). from scipy.optimize import minimize import numpy as np #Array of Amounts Amount = np.array([10000000,-2000000,400000000,60000000]) #Array of Risk Risk = np.array([-10000,5000,-20000,500]) #Minimize the sum of Amounts def Objective(weights): x = weights * Amount return np.sum(x) #While keeping the sum of Risks constant i.e Sum of New Weighted Risk - Sum of Old weighted risk = 0 def Cons1(weights): x = weights*Risk return np.sum(x)-np.sum(Risk) #Create Constraint cons = ({'type': 'eq', 'fun':Cons1}) #Give Initial Guess guess = np.array([0.25,0.25,0.25,0.25]) #Minimize minimize(Objective,guess,constraints=cons) The result I get is: fun: -2.1834331315418437e+18 jac: array([0., 0., 0., 0.]) message: 'Singular matrix C in LSQ subproblem' nfev: 18 nit: 3 njev: 3 status: 6 success: False x: array([ 9.32859191e+09, -4.14243499e+09, -4.78072085e+09, -6.21192636e+09]) When I use the solver on Excel (Simplex LP), I get a viable result: Using guess weights : After Solving: Can anyone tell me what I'm doing wrong here?
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/51514363
tagged with: minimize
tagged with: optimization
has title: Unable to minimze in scipy when constraint equals zero

http://stackoverflow.com/q/51527725
answer count: 1
downvote count: 0
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/51533110
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/42476032
has title: GridSearchCV scoring on mean absolute error
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51533110
upvote count: 3
tagged with: grid-search
has body: I'm trying to setup an instance of GridSearchCV to determine which set of hyperparameters will produce the lowest mean absolute error. This scikit documentation indicates that score metrics can be passed into the grid upon creation of a GridSearchCV (below). param_grid = { 'hidden_layer_sizes' : [(20,),(21,),(22,),(23,),(24,),(25,),(26,),(27,),(28,),(29,),(30,),(31,),(32,),(33,),(34,),(35,),(36,),(37,),(38,),(39,),(40,)], 'activation' : ['relu'], 'random_state' : [0] } gs = GridSearchCV(model, param_grid, scoring='neg_mean_absolute_error') gs.fit(X_train, y_train) print(gs.scorer_) [1] make_scorer(mean_absolute_error, greater_is_better=False) However the grid search is not selecting the best performing model in terms of mean absolute error model = gs.best_estimator_.fit(X_train, y_train) print(metrics.mean_squared_error(y_test, model.predict(X_test))) print(gs.best_params_) [2] 125.0 [3] Best parameters found by grid search are: {'hidden_layer_sizes': (28,), 'learning_rate': 'constant', 'learning_rate_init': 0.01, 'random_state': 0, 'solver': 'lbfgs'} After running the above code and determining the so called 'best parameters', I delete one of the values found in gs.best_params_, and find that by running my program again the mean squared error will sometimes decrease. param_grid = { 'hidden_layer_sizes' : [(20,),(21,),(22,),(23,),(24,),(25,),(26,),(31,),(32,),(33,),(34,),(35,),(36,),(37,),(38,),(39,),(40,)], 'activation' : ['relu'], 'random_state' : [0] } [4] 122.0 [5] Best parameters found by grid search are: {'hidden_layer_sizes': (23,), 'learning_rate': 'constant', 'learning_rate_init': 0.01, 'random_state': 0, 'solver': 'lbfgs'} To clarify, I changed the set that was fed into my grid search so that it did not contain an option to select a hidden layer size of 28, when that change was made, I ran the code again and this time it picked a hidden layer size of 23 and the mean absolute error decreased (even though the size of 23 had been available from the start), wh…
type: Question
linked to: http://stackoverflow.com/q/42191717

http://stackoverflow.com/q/51573152
accepted answer: http://stackoverflow.com/a/51573270
has title: C running slower than PyPy
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/90112262
has comment: http://stackoverflow.com/comment/90112251
answer count: 2
has comment: http://stackoverflow.com/comment/90112389
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90112270
possible better answer: http://stackoverflow.com/a/51573221
has comment: http://stackoverflow.com/comment/90112355
has comment: http://stackoverflow.com/comment/90112157
has answer: http://stackoverflow.com/a/51573221
has comment: http://stackoverflow.com/comment/90112309
tagged with: python
has comment: http://stackoverflow.com/comment/90112441
has body: I'm running these two codes. They both perform the same mathematical procedure (calculate series value up to large terms), and also, as expected, produce the same output. But for some reason, the PyPy code is running significantly faster than the C code. I cannot figure out why this is happening, as I expected the C code to run faster. I'd be thankful if anyone could help me by clarifying that (maybe there is a better way to write the C code?) C code: #include &lt;stdio.h&gt; #include &lt;math.h&gt; int main() { double Sum = 0.0; long n; for(n = 2; n &lt; 1000000000; n = n + 1) { double Sign; Sign = pow(-1.0, n % 2); double N; N = (double) n; double Sqrt; Sqrt = sqrt(N); double InvSqrt; InvSqrt = 1.0 / Sqrt; double Ln; Ln = log(N); double LnSq; LnSq = pow(Ln, 2.0); double Term; Term = Sign * InvSqrt * LnSq; Sum = Sum + Term; } double Coeff; Coeff = Sum / 2.0; printf("%0.14f \n", Coeff); return 0; } PyPy code (faster implementation of Python): from math import log, sqrt Sum = 0 for n in range(2, 1000000000): Sum += ((-1)**(n % 2) * (log(n))**2) / sqrt(n) print(Sum / 2)
has comment: http://stackoverflow.com/comment/90112403
has answer: http://stackoverflow.com/a/51573270
upvote count: 1
has comment: http://stackoverflow.com/comment/90112210
has comment: http://stackoverflow.com/comment/90112202
type: Question
has comment: http://stackoverflow.com/comment/90112291
type: AnsweredQuestion

http://stackoverflow.com/comment/90062307
comment on: http://stackoverflow.com/q/51547183
has text: The right design depends on what the class does. If there's any possibility that you'll ever need to treat two separate API operations as a transaction under the same lock, the lock has to be external. And if the object is a dead simple thing like a `list` where it would make any sense to use it without a lock, the lock has to be either external or optional. But if it's something whose API should promise that each operation is thread-safe, like a `queue.Queue`, the lock should be internal. There's no one-size-fits-all answer; it's part of your object model design.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/51630268
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51573298
has body: Well, I use Quandl with Canopy and Anaconda (Windows and Mac) and never had any kind of problem at all. Sorry I did not see that you had already installed. But on the other hand, I had some troubles using pip when I did not run it as administrator - sometimes it said that the package was installed but it was not.

http://stackoverflow.com/a/51571794
accepted answer of: http://stackoverflow.com/q/51560515
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51560515
has body: I got the solution for this one, I forgot to add the grant_type parameter. Solution below: import requests import base64 import json token_url='https://ops.epo.org/3.2/auth/accesstoken' key = 'Basic %s' % base64.b64encode(b'myconsumerkeyhere:mysecretkeyhere').decode('ascii') data = {'grant_type': 'client_credentials'} headers = {'Authorization': key, 'Content-Type': 'application/x-www-form-urlencoded'} r = requests.post(token_url, data=data, headers=headers) rs= r.content.decode() response = json.loads(rs) token = response['access_token'] print(token)

http://stackoverflow.com/q/51491732
has body: say I have a data that tags the presence of water in terms of depth (meters): Depth Water 1.9 1.91 2 2.92 2.94 2.97 2.98 3 1 3.02 3.03 3.05 3.07 3.11 4.08 4.11 1 5.12 5.22 6.13 6.18 6.2 6.22 1 7.12 7.45 7.6 8.6 1 I want to perform a backfill on this using pandas such that every one meter above will will be tagged with 1, as below: Depth Water 1.9 1.91 2 1 2.92 1 2.94 1 2.97 1 2.98 1 3 1 3.02 3.03 3.05 3.07 3.11 1 4.08 1 4.11 1 5.12 5.22 1 6.13 1 6.18 1 6.2 1 6.22 1 7.12 7.45 7.6 1 8.6 1 My Scratch code is as follows: #create function that will tag 1: def label_water(row): if row['Water'] == '1' : return 1 else: return '' for i in np.where(df['Water']==1): for j in i: # j is the lower depth k = j-1 #k is now the upper depth data['Water']=df.apply(lambda row: label_water(row) if k&lt;df['Depth']&lt;j) However it gives back a syntax error, is there something I am missing?
score: 1
has title: Dynamic Backfilling a Pandas DataFrame based on a Specified Depth
tagged with: dataframe
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51491991
accepted answer: http://stackoverflow.com/a/51491991
tagged with: pandas
tagged with: python
type: AnsweredQuestion
downvote count: 0
type: Question

http://stackoverflow.com/comment/90106776
comment on: http://stackoverflow.com/a/51563770
score: 0
type: Comment
has text: Thank you for your advices. I am still trying to set and solve. I hope to find a way to handle.
type: AnswerComment

airflow
tags question: http://stackoverflow.com/q/51526132
tags question: http://stackoverflow.com/q/51637038
tag name: airflow
tags question: http://stackoverflow.com/q/51554263
tags question: http://stackoverflow.com/q/51638210
tags question: http://stackoverflow.com/q/51625265
tags question: http://stackoverflow.com/q/51608355
tags question: http://stackoverflow.com/q/51520767
tags question: http://stackoverflow.com/q/51617236
type: Tag
tags question: http://stackoverflow.com/q/51638467

http://stackoverflow.com/comment/90131934
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51572085
type: AnswerComment
has text: @AmolDeodhar I strongly suggest 3.6, type hints have great benefit and Prodict also uses type hints.

http://stackoverflow.com/comment/90205933
has text: Now add in `0j`, `1j`, `decimal.Decimal('0')`, `decimal.Decimal('1')`, `fractions.Fraction(0, 1)`, `fractions.Fraction(1, 1)`, `0.0` and `1.0` into the mix. Sets test for uses hashing and *equality tests* to determine if an object is in the set. `1 == True == 1.0 == 1j == decimal.Decimal('1') == fractions.Fraction(1, 1)`, and they all have the same hash value.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51505826

http://stackoverflow.com/a/51606449
answers question: http://stackoverflow.com/q/51605270
type: Answer
score: 0
has body: Here's a one-liner (ish) solution: userid = ['User 1 ID', 'User 2 ID', 'User 3 ID'] name = ['User 1 Name', 'User 2 Name', 'User 3 Name'] discriminator = ['User 1 Disc', 'User 2 Disc', 'User 3 Disc'] #convert [['a1', 'a2'], ['b1', 'b2']] to iter([('a1', 'b1'), ('a2', 'b2')]) total = zip(userid, name, discriminator) await client.send_message(message.channel, "**Ban List:**\n" + "\n".join("• {} ({}#{})".format(*i) for i in total)) The output should be: Ban List: • User 1 ID (User 1 Name#User 1 Disc) • User 2 ID (User 2 Name#User 2 Disc) • User 3 ID (User 3 Name#User 3 Disc)

http://stackoverflow.com/a/51605739
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51605581
answers question: http://stackoverflow.com/q/51605581
has comment: http://stackoverflow.com/comment/90176820
has body: You need to first apply dataframe.groupby() on Team column and then use shift() to get next RS value for the Team. df = pd.DataFrame({'Year':[1962,1962,1963,1963,1964,1964], 'RS':[599,774,747,725,702,800], 'Team':['WSA','STL','WSA','STL','WSA','STL']}) df['RS_Target'] = df.groupby('Team')['RS'].shift(-1) print(df) Output: Year RS Team RS_Target 0 1962 599 WSA 747.0 1 1962 774 STL 725.0 2 1963 747 WSA 702.0 3 1963 725 STL 800.0 4 1964 702 WSA NaN 5 1964 800 STL NaN EDIT: If your Year column contains random values b. Sort the column using below before applying groupby operation: df.sort_values(['Year'], inplace=True)

http://stackoverflow.com/comment/90053589
type: Comment
comment on: http://stackoverflow.com/a/51529275
score: 0
type: AnswerComment
has text: @JasonLeach `print name` statement should have the same indentation as the previous `name =` line, otherwise it won't work. indentation is quite important in python.

sockets
tags question: http://stackoverflow.com/q/51543938
tags question: http://stackoverflow.com/q/51595613
tags question: http://stackoverflow.com/q/51487104
tags question: http://stackoverflow.com/q/51580618
tags question: http://stackoverflow.com/q/51577844
tags question: http://stackoverflow.com/q/51527846
tags question: http://stackoverflow.com/q/51549719
tags question: http://stackoverflow.com/q/51543839
tags question: http://stackoverflow.com/q/51483363
tags question: http://stackoverflow.com/q/51566274
tags question: http://stackoverflow.com/q/51564270
tags question: http://stackoverflow.com/q/51530628
type: Tag
tags question: http://stackoverflow.com/q/51616394
tags question: http://stackoverflow.com/q/51613507
tags question: http://stackoverflow.com/q/51580668
tags question: http://stackoverflow.com/q/51497714
tags question: http://stackoverflow.com/q/51576949
tags question: http://stackoverflow.com/q/51618844
tag name: sockets
tags question: http://stackoverflow.com/q/51512621
tags question: http://stackoverflow.com/q/51537746
tags question: http://stackoverflow.com/q/51534340
tags question: http://stackoverflow.com/q/51592992

http://stackoverflow.com/q/51504497
answer count: 1
has title: Any way to get the app_id related to an item that has been deleted (API)
tagged with: podio
has answer: http://stackoverflow.com/a/51511194
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51511194
type: Question
has body: Any way to get the app_id related to an item that has been deleted (API). Because when I try to get details from the item_id I receive this information. https://api.podio.com/item/xxxxxxxx {u'error_parameters': {}, u'error_detail': None, u'error_propagate': False, u'request': {u'url': u'http://api.podio.com/item/xxxxxxxx', u'query_string': u'', u'method': u'GET'}, u'error_description': u'Item has been deleted', u'error': u'gone'} Regards.
score: 0

http://stackoverflow.com/comment/90070137
type: QuestionComment
has text: I don't see screenshots attached. could you try uploading again? HTML directly posting into the question would be a better choice.
score: 0
comment on: http://stackoverflow.com/q/51548202
type: Comment

http://stackoverflow.com/comment/90076864
comment on: http://stackoverflow.com/q/51554931
type: QuestionComment
type: Comment
has text: What exactly is your question ? How to achieve such expected output ? Or why it produces the output you gave ? Please specify.
score: 0

http://stackoverflow.com/a/58235778
type: Answer
answers question: http://stackoverflow.com/q/51562067
upvote count: 2
score: 2
has body: Windows has implemented Controlled folder access, which is to block un-authorized app to access your important files(means almost anything installed by windows). This is to prevent data encryption and ransom by malware. Windows will pop-out notification if it blocks any app. You can allow apps/programs access through Controlled folder access.
downvote count: 0

http://stackoverflow.com/comment/90240661
comment on: http://stackoverflow.com/a/51634193
type: AnswerComment
score: 0
type: Comment
has text: I updated my answer. Are your columns named `Opt1`, `Opt2`, `Opt3`?. If they're not then you have to change them in this code snippet...

http://stackoverflow.com/q/51585792
has comment: http://stackoverflow.com/comment/90142049
tagged with: python
linked to: http://stackoverflow.com/q/49090514
score: 1
tagged with: sublimelinter
upvote count: 1
type: Question
tagged with: pyflakes
has title: SublimeText linting Python3 with pyflakes in virtualenv
downvote count: 0
answer count: 1
tagged with: virtualenv
tagged with: sublimetext3
favorite count: 0
has answer: http://stackoverflow.com/a/51969865
has comment: http://stackoverflow.com/comment/90150001
has body: When I open my Python files in Sublime and delete simple things like : at the end of def myFunction():, then I expect the linter to add a red circle in the gutter. But I see nothing in the gutter. I notice at the bottom of the Sublime window it says "pyflakes(erred)" Installing the dependencies # Sublime v 3.1.1 # Sublime package install SublimeLinter # Sublime package install SublimeLinter-pyflakes pip3 install pyflakes which pyflakes # /Users/macbook/Desktop/my_virtual_env/bin/pyflakes Trying to tell my linter the path to use in "MyProj.sublime-project" settings { "folders":[ { "path": "." } ], "SublimeLinter.linters.pyflakes.python": "/Users/macbook/Desktop/my_virtual_env/bin/python3" } UPDATE: Sublime console output upon loading views.py SublimeLinter: #10 linter.py:907: 'pyflakes' is linting 'views.py' SublimeLinter: #10 python_linter.py:42: pyflakes: wanted python is 'None' SublimeLinter: #10 python_linter.py:93: pyflakes: trying to use globally installed pyflakes SublimeLinter: #10 python_linter.py:101: WARNING: cannot locate 'pyflakes'. Fill in the 'python' or 'executable' setting.
type: UnansweredQuestion

http://stackoverflow.com/a/51558815
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: The problem is that you use in your code the following line with 'w', which means (over)writing in the file: open('UserPassword.csv', 'w') Instead you should use 'a', which means appending to the file, as follows: open('UserPassword.csv', 'a')
answers question: http://stackoverflow.com/q/51558747
upvote count: 1
has comment: http://stackoverflow.com/comment/90109877
has comment: http://stackoverflow.com/comment/90142495
accepted answer of: http://stackoverflow.com/q/51558747
score: 1

http://stackoverflow.com/q/51616160
score: 3
answer count: 1
downvote count: 0
favorite count: 0
tagged with: image-stitching
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
has title: How to overlay/replace a part of an image with another using cv2?
upvote count: 3
tagged with: image-processing
type: Question
tagged with: opencv
has body: I have an image of a roof which covers a huge area! I am analyzing it for faults using segmentation. However the challenge is that sometimes the single shot of the roof doesn't have the details involved so its hard to analyse that. So we split it up into parts and take images of smaller parts and analyse that. Here is an example: Entire roof shot Part 1 Part 2 Part 3 So Now I want to analyse the parts for faults and replace it on the single shot. Here is how one of the analysed part looks: Post Analysis My thinking so far: If I can map the non analysed part to the roof in some way, I can use the same information and method to map the analysed part to the single shot too. I have been able to do feature detection and identify the parts on the single shot however I am not sure as to how I should transform them to fit and replace the exact part on the single shot. Here is the feature detection: Feature detection for image/template matching I have been thinking of trying to stitch the smaller images to the larger one sequentially one after the other but I am concerned that might not work PS: I am using Linux, Python3 and OpenCV 3.4.0 Also, the original single shot is not manually divided into the different parts. Since its a thermal cam, its not possible to have high res on the single shot so the cam takes different shots close up. Those parts are separate images and not cropped from the single shot. EDIT: I am now trying an alternative approach where I detect faults in the part images and then crop those faults out to use as templates and then try feature detection using SIFT to match the fault as a template on the single shot. However, small faults are being matched to every thing other than itself :( Most of the larger faults are detected fine and medium ones dont do too good either. I think the reason is that the image is low res and the single shot pic doesnt replicate the faults on the closer shots and the number of features is also less on the single shot for temp…
has answer: http://stackoverflow.com/a/51620948

http://stackoverflow.com/a/51526960
score: 3
has body: Simple solution using pivot, add_suffix (via @ScottBoston) and reset_index df.pivot(index = 'id',columns = 'group',values = 'value')\ .add_suffix('_value')\ .reset_index() group id A_value B_value 0 92.0 123.123 32019.0 1 105.0 9034.000 3281.0 2 999.0 421.000 NaN
downvote count: 0
has comment: http://stackoverflow.com/comment/90022481
answers question: http://stackoverflow.com/q/51526846
has comment: http://stackoverflow.com/comment/90022544
type: Answer
has comment: http://stackoverflow.com/comment/90022778
upvote count: 3
has comment: http://stackoverflow.com/comment/90022866

http://stackoverflow.com/comment/128154653
score: 0
type: Comment
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
comment on: http://stackoverflow.com/a/72545453
type: AnswerComment

http://stackoverflow.com/q/51567292
has comment: http://stackoverflow.com/comment/90101155
possible better answer: http://stackoverflow.com/a/51567318
has answer: http://stackoverflow.com/a/51567318
type: Question
tagged with: random
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/90101144
has answer: http://stackoverflow.com/a/51567358
favorite count: 0
tagged with: python
downvote count: 0
tagged with: shuffle
has title: Am I using random.shuffle wrong or is this a bug?
has comment: http://stackoverflow.com/comment/90101136
type: AnsweredQuestion
has body: So I'm shuffling a list before I split it. it's a list of numbers read from a file so the list is actually a list of strings, but they're numbers: streams = ['0','1','2','3','4','5','6','7','8','9'] now, the code I run, simply shuffles the list: print(streams, type(streams[0])) import random random.shuffle(streams) I'm using Python 3.6.4 by the way. Here's the error I get: C:\src&gt;python cli.py 0,1,2,3,4,5,6,7,8,9 &lt;class 'str'&gt; Traceback (most recent call last): ... File "....py", line 3, in split_randomized_list random.shuffle(streams) File "C:\ProgramData\Anaconda3\lib\random.py", line 275, in shuffle x[i], x[j] = x[j], x[i] TypeError: 'str' object does not support item assignment This says to me that it can't shuffle lists made up of numbers in string format? Is that right? Is that a bug or am I doing it wrong?
score: 1
accepted answer: http://stackoverflow.com/a/51567358

http://stackoverflow.com/q/51520381
tagged with: python
has comment: http://stackoverflow.com/comment/90009547
linked to: http://stackoverflow.com/q/2597104
has answer: http://stackoverflow.com/a/51520694
score: 1
has comment: http://stackoverflow.com/comment/90009709
upvote count: 1
has body: I have a loop in the form as below. I want to break and come out of the entire while loop if p&gt;len(number). Number is a list here containing some numbers. The below code is not breaking from the entire loop when p is more than the len(number). Can some one help with an implementation in python. while number[p]&lt;0 : if "some condition": #do something p=p+1 if p&gt;len(number): break; else: #do something p=p+1 if p&gt;len(number) break;
type: Question
has answer: http://stackoverflow.com/a/51520709
has comment: http://stackoverflow.com/comment/90009937
has answer: http://stackoverflow.com/a/51548145
has title: How to exit outer loop from an inner if statement
has comment: http://stackoverflow.com/comment/90009486
has comment: http://stackoverflow.com/comment/90009612
has comment: http://stackoverflow.com/comment/90009567
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90009847
favorite count: 0
linked to: http://stackoverflow.com/q/189645
type: UnansweredQuestion

http://stackoverflow.com/q/51575948
tagged with: pip
tagged with: pypi
type: Question
has answer: http://stackoverflow.com/a/51579226
has body: Trying to implement this for a small group that has a PyPI server to host 3rd party and internal packages. The challenge is that they want to access control the internal artifacts and lock newer version to the package's developers only. Is there a way to enforce LDAP based access control to the PyPI server? I am considering Artifactory too but that's a longer term solution.
answer count: 1
tagged with: ldap
score: 0
tagged with: devops
tagged with: python
has title: Is there a way control access to PyPI artifacts through LDAP Integration
type: UnansweredQuestion

http://stackoverflow.com/q/51601146
type: AnsweredQuestion
tagged with: floating-point
type: Question
accepted answer: http://stackoverflow.com/a/51601314
has comment: http://stackoverflow.com/comment/90168818
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/90168702
has title: Python cannot convert string to float sometimes
has comment: http://stackoverflow.com/comment/90168503
has comment: http://stackoverflow.com/comment/90168595
has comment: http://stackoverflow.com/comment/90168604
has comment: http://stackoverflow.com/comment/90168670
score: 0
has comment: http://stackoverflow.com/comment/90168847
has answer: http://stackoverflow.com/a/51601314
tagged with: python
has body: I have the following two codes: 1. f=open("file.csv","r") data=f.read() f.close() for line in data.split("\n"): for d in line.split(","): print(float(d)) 2. f=open("file.csv","r") data=f.read() f.close() for line in data.split("\n"): for d in line.split(","): float(d) The first code runs fine, but the second gives the error: ValueError: could not convert string to float: What is wrong with the second code? This is the first two lines of the file: 0,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,0 0,49.805,69.3666,78.4413,83.2828,86.1354,87.9128,89.0309,89.6942,90.0045,90.0045

http://stackoverflow.com/q/51631651
type: Question
upvote count: 9
has comment: http://stackoverflow.com/comment/90227943
has comment: http://stackoverflow.com/comment/90227784
answer count: 2
tagged with: django-queryset
has title: Why use get_context_data (self,**kwargs) and super ()
has answer: http://stackoverflow.com/a/51631969
favorite count: 0
has comment: http://stackoverflow.com/comment/90227746
tagged with: python-3.x
has body: In a class-based view, I simply use get_context_data as a function but why class CBV (TemplateView): def get_context_data(self,**kwargs): context = super ().get_context_data (**kwargs)
accepted answer: http://stackoverflow.com/a/51631969
has comment: http://stackoverflow.com/comment/90227876
has comment: http://stackoverflow.com/comment/90227847
tagged with: django
tagged with: python
score: 8
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/75613745
has comment: http://stackoverflow.com/comment/90227683
has answer: http://stackoverflow.com/a/75613745
downvote count: 1

http://stackoverflow.com/a/51552366
answers question: http://stackoverflow.com/q/51552292
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
has body: Short anwser is you can't. This is due to the fact that PyCharm does not not run your code while you type. Python is a dynamic language with multi inheritance, it would be difficult for IDE to check for all parameters in all base classes, especially due the fact that unlike in Java call to the base class __init__() function can be omitted. Also note that this fragment: class B(A): def __init__(self, bar=None, **kwargs): super().__init__(**kwargs) Enforces that foo can only be passed as keyword argument not a positional one, while class A allows it to be passed as positional argument. However, if typing is an issue i would suggest ctrl+O which is a shortcut to override. If you do it in an empty class it will create an __init__() method with arguments from the base class and a call to super. If the documentation is an issue just write a docstring for the method
accepted answer of: http://stackoverflow.com/q/51552292
score: 2

http://stackoverflow.com/comment/126525021
type: AnswerComment
type: Comment
has text: Sylvester, i dont know if you are still here, but i found the updated link: https://github.com/kaldi-asr/kaldi just so anyone comes here can go to updated link
comment on: http://stackoverflow.com/a/57641718
score: 0

http://stackoverflow.com/q/51617740
tagged with: linearmodels
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90226004
type: Question
tagged with: numpy
has title: Linearmodels FamaMacBeth 'list' argument must have no negative elements
downvote count: 0
has comment: http://stackoverflow.com/comment/90230539
favorite count: 0
has body: I'm trying to run some Fama MacBeth regressions using the FamaMacBeth functionality from linearmodels (version 4.8) and I'm running into the following error: ValueError Traceback (most recent call last) &lt;ipython-input-7-f393d4c071f0&gt; in do_panel(list_dfs, y_var, control_vars, method) 37 print(fmb_df[y_var].head()) 38 print(fmb_df[new_x_vars].head()) ---&gt; 39 model = FamaMacBeth(fmb_df[y_var], sm.add_constant(fmb_df[new_x_vars])).fit() 40 return model 41 ~\AppData\Local\Continuum\anaconda3\envs\py36\lib\site-packages\linearmodels\panel\model.py in fit(self, cov_type, debiased, **cov_config) 1940 cov = cov_est(wy, wx, params, all_params, debiased=debiased, **cov_config) 1941 df_resid = wy.shape[0] - params.shape[0] -&gt; 1942 res = self._postestimation(params, cov, debiased, df_resid, weps, wy, wx, root_w) 1943 index = self.dependent.index 1944 res.update(dict(df_resid=df_resid, df_model=x.shape[1], nobs=y.shape[0], ~\AppData\Local\Continuum\anaconda3\envs\py36\lib\site-packages\linearmodels\panel\model.py in _postestimation(self, params, cov, debiased, df_resid, weps, y, x, root_w) 441 f_pooled = InapplicableTestStatistic(reason='Model has no effects', 442 name='Pooled F-stat') --&gt; 443 entity_info, time_info, other_info = self._info() 444 nobs = weps.shape[0] 445 sigma2 = float(weps.T @ weps / nobs) ~\AppData\Local\Continuum\anaconda3\envs\py36\lib\site-packages\linearmodels\panel\model.py in _info(self) 223 224 entity_info = stats(self.dependent.entity_ids.squeeze(), --&gt; 225 'Observations per entity') 226 time_info = stats(self.dependent.time_ids.squeeze(), 227 'Observations per time period') ~\AppData\Local\Continuum\anaconda3\envs\py36\lib\site-packages\linearmodels\panel\model.py in stats(ids, name) 217 218 def stats(ids, name): --&gt; 219 bc = np.bincount(ids) 220 index = ['mean', 'median', 'max', 'min', 'total'] 221 out = [bc.mean(), np.median(bc), bc.max(), bc.min(), bc.shape[0]] ValueError: 'list' argument must have no negative elements I tried …
score: 1
has comment: http://stackoverflow.com/comment/90225823
has comment: http://stackoverflow.com/comment/90237421
has comment: http://stackoverflow.com/comment/90221439
has comment: http://stackoverflow.com/comment/90201321
answer count: 0
type: UnansweredQuestion
tagged with: regression

http://stackoverflow.com/comment/90064940
type: QuestionComment
score: 2
has text: I'm a bit confused why you want the empty rows
comment on: http://stackoverflow.com/q/51548583
type: Comment

http://stackoverflow.com/q/51627258
has body: So I have this in Python to detect intents when an input is entered. for text in texts: text_input = dialogflow.types.TextInput(text=text, language_code=language_code) query_input = dialogflow.types.QueryInput(text=text_input) response = session_client.detect_intent(session=session, query_input=query_input) print ('Chatbot: {}\n'.format(response.query_result.fulfillment_text)) detect_intent_texts("chat-8","abc",["Hey"],"en-us") And my current gui myText = StringVar() window.resizable(False, False) window.title("Chatbot") window.geometry('400x400') User_Input = Entry(window, textvariable=myText, width=50).place(x=20, y=350) subButton = Button(window, text="Send").place(x =350, y=350) window.mainloop() My aim is to create a GUI that takes a user input, and when submitted the code then detects what the user has input. As you can see from the above, on the final line ["Hey"], this is where I can type whatever I like and the chatbot responds in the console, although it works is not what I'd like to achive. How would I instead order [""] to detect what the user has wrote in the Entry widget?
has comment: http://stackoverflow.com/comment/90220316
score: -2
has comment: http://stackoverflow.com/comment/90219342
answer count: 1
has answer: http://stackoverflow.com/a/51632203
favorite count: 0
has comment: http://stackoverflow.com/comment/90228533
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90219218
has title: Detect intent from Entry instead of manual Dialogflow input
tagged with: tkinter
downvote count: 3
tagged with: dialogflow-es
upvote count: 1
type: Question

http://stackoverflow.com/comment/90165770
type: QuestionComment
comment on: http://stackoverflow.com/q/51599622
has text: Or maybe the file name specified is/isn't absolute!
score: 0
type: Comment

http://stackoverflow.com/q/51611298
has comment: http://stackoverflow.com/comment/90188880
type: Question
tagged with: python
tagged with: differential-equations
upvote count: 1
has title: iterate using multi dimensional np.array
has body: I've developed a class in order to solve backward euler using Newton-rapson method to solve the non linear equation. the class is suitable for the system of ODE as well (it takes an array of function ..) this is my class: class Backward(Euler): solved = False def __init__(self, dydt: Rhs, filename : str=' ', save :bool=True): self.save = save self.file = filename super().__init__(dydt) def solve(self): toll = 10e-12 self.time, self.u = self.dydt.createArray() print('Running Newton-Rapson Backward Euler ....') for i in range(len(self.time)-1): u0 = self.u[i].T u1 = u0 - np.linalg.inv(np.eye(len(self.dydt.u0)) - self.dt * self.dydt.Df(self.time[i+1],u0)) * (u0 - self.dt * self.dydt.f(self.time[i+1], u0).T - self.u[i].T ) error = np.array([1.0]) iters = 0 while True: try: u0 = u1.T u1 = u0 - np.linalg.inv(np.eye(len(self.dydt.u0)) - self.dt * self.dydt.Df(self.time[i+1],u0)) * (u0 - self.dt * self.dydt.f(self.time[i+1], u0).T - self.u[i].T ) iters += 1 error = np.abs(u1-u0) if error &lt;= toll: break if iters &gt;= 10000: raise ValueError('Too many iterations!') except ValueError as ex: print('Error occurred in Implicit-NR Euler Solvers: %s' %ex.args) return None , None self.u[i+1] = u1.T #------------------------------------------- print('...Done!') I got this error : Running Newton-Rapson Backward Euler .... Error occurred in Implicit-NR Euler Solvers: The truth value of an ars ambiguous. Use a.any() or a.all() If I try to use error.all() or error.any() the problem never converged ... the input parameters for this method is : eq1 = lambda t,u : u[1] eq2 = lambda t,u : u[2] eq3 = lambda t,u : u[3] eq4 = lambda t,u : -8*u[0]+ np.sin(t)*u[1]-3*u[3]+t**2 func1 = np.array([eq1,eq2,eq3,eq4]) y0 = np.array([1.,2.,3.,4]) system1 = rhs.Rhs(func1, 0,5,y0, 1000 ) where Rhs is a wrapper class containing the data like function to be solved etc.. EDIT I follow your advise thanks .. I put toll = 10e-3 but the problem doesn't solve... (Too many iteration) and also if i put error[0][…
type: UnansweredQuestion
answer count: 0
tagged with: arrays
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/51502595
downvote count: 1
has answer: http://stackoverflow.com/a/51504287
favorite count: 0
has comment: http://stackoverflow.com/comment/89973936
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89973924
has answer: http://stackoverflow.com/a/51503434
accepted answer: http://stackoverflow.com/a/51503434
possible better answer: http://stackoverflow.com/a/51504287
type: Question
has title: Adding non-existing combination
has body: I want to make a table with all available products for every customer. However, I only have a table with the combination of product and customer if it was bought. I want to make a new table that also included the product that were not bought by the customer. The current table looks as follows: The table I want to end up with is: Could anyone help me how to do this in pandas?
score: 0
answer count: 2
tagged with: pandas
upvote count: 1

http://stackoverflow.com/comment/90240703
has text: hmmm, it is time, check red alert http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#v0-23-0-may-15-2018
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51636569
type: Comment

http://stackoverflow.com/q/51535038
has answer: http://stackoverflow.com/a/54655854
tagged with: python
favorite count: 0
tagged with: pycharm
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51543997
upvote count: 1
tagged with: firebase
has answer: http://stackoverflow.com/a/56021897
score: 1
tagged with: firebase-admin
tagged with: dialogflow-es
type: Question
has body: After creating a chatbot in Dialogflow I want to connect this to my PyCharm environment, my end goal is to create a GUI within Python and allow it to connect through Dialogflow back-end, I also have a Firestore database and a few API's set up. I have read to connect PyCharm to the Dialogflow (and, the Google Cloud platform) I need to use the Firebase-Admin SDK, which has been installed through PIP. import dialogflow_v2beta1 from google.cloud import firestore import firebase_admin from firebase_admin import credentials #Initialize the Admin SDK cred = credentials.Certificate('C:Users\folder1\folder2\chatbot.json') default_app = firebase_admin.initialize_app(cred) #The below is a default test hoping to write a new document to the Firestore Database to check the connection works. doc_ref = db.collection(u'users').document(u'alovelace') doc_ref.set({ u'first': u'Ada', u'last': u'Lovelace', u'born': 1815 }) So, with the above I simply hope to connect my environment to my chatbot through the Google platform and when I run this code I hope for some data to be created in my Firestore database. The error I get when I run the above is: C:\Users\Me\PycharmProjects\Chatbot\venv\Scripts\python.exe C:/Users/Me/PycharmProjects/Chatbot/venv/Chatbot.py Traceback (most recent call last): File "C:/Users/Me/PycharmProjects/Chatbot/venv/Chatbot.py", line 12, in &lt;module&gt; cred = credentials.Certificate('C:Users\folder1\folder2\chatbot.json') File "C:\Users\Me\PycharmProjects\Chatbot\venv\lib\site-packages\firebase_admin\credentials.py", line 83, in __init__ with open(cert) as json_file: IOError: [Errno 2] No such file or directory: 'C:Users\\folder1\\folder2\\chatbot.json' Process finished with exit code 1 In short, I've checked the line 83 error in the credentials.py file where the default comment suggests means the file can't be found, but is correct as far as I can tell. The only thing I notice are the two \ in the error. Any help would be much appreciated. UPDATE This has erased…
has title: Firebase Admin SDK credentials certificate not validating
downvote count: 0
has answer: http://stackoverflow.com/a/74955995
has answer: http://stackoverflow.com/a/51579312

http://stackoverflow.com/a/51543350
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51541754
type: Answer
upvote count: 3
has body: Here a solution: import cv2 import matplotlib import numpy as np import matplotlib.pyplot as plt image = cv2.imread('mickey.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2YCR_CB)[...,0] def show_img(im, figsize=None, ax=None, alpha=None): if not ax: fig,ax = plt.subplots(figsize=figsize) ax.imshow(im, alpha=alpha) ax.set_axis_off() return ax def getBordered(image, width): bg = np.zeros(image.shape) _, contours, _ = cv2.findContours(image.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) biggest = 0 bigcontour = None for contour in contours: area = cv2.contourArea(contour) if area &gt; biggest: biggest = area bigcontour = contour return cv2.drawContours(bg, [bigcontour], 0, (255, 255, 255), width).astype(bool) im2 = getBordered(image, 10) show_img(im2, figsize=(10,10)) You can change thickness by changing param width in getBordered.
score: 3
accepted answer of: http://stackoverflow.com/q/51541754

http://stackoverflow.com/a/53205515
has body: In order to use a single aiohttp.ClientSession we need to instantiate the session only once and use that specific instance in the rest of the application. To achieve this we can use a before_server_start listener which will allow us to create the instance before the app serves the first byte. from sanic import Sanic from sanic.response import json import aiohttp app = Sanic(__name__) @app.listener('before_server_start') def init(app, loop): app.aiohttp_session = aiohttp.ClientSession(loop=loop) @app.listener('after_server_stop') def finish(app, loop): loop.run_until_complete(app.aiohttp_session.close()) loop.close() @app.route("/") async def test(request): """ Download and serve example JSON """ url = "https://api.github.com/repos/channelcat/sanic" async with app.aiohttp_session.get(url) as response: return await response.json() app.run(host="0.0.0.0", port=8000, workers=2) Breakdown of the code: We are creating an aiohttp.ClientSession, passing as argument the loop that Sanic apps create at the start, avoiding this pitfall in the process. We store that session in the Sanic app. Finally, we are using this session to make our requests.
has comment: http://stackoverflow.com/comment/97974471
has comment: http://stackoverflow.com/comment/97969965
has comment: http://stackoverflow.com/comment/97970380
has comment: http://stackoverflow.com/comment/104392490
type: Answer
score: 13
has comment: http://stackoverflow.com/comment/97970623
upvote count: 13
accepted answer of: http://stackoverflow.com/q/51638347
has comment: http://stackoverflow.com/comment/97522396
answers question: http://stackoverflow.com/q/51638347
has comment: http://stackoverflow.com/comment/97970241
has comment: http://stackoverflow.com/comment/97970344
has comment: http://stackoverflow.com/comment/97970889
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51494385
linked to: http://stackoverflow.com/q/25840177
has body: I thought that a = [] a.insert(42, "the answer") would raise an exception (perhaps IndexError), but it doesn't. Both Python 2.7 and 3.6 create a list with one element at index 0. The documentation says list.insert(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x). And apparently a.insert(i, x) with i&gt;len(a) is also equivalent to a.append(x). Is this intended or at least documented? I could not find anything yet.
type: Question
upvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/25840177
type: UnansweredQuestion
has title: Why does inserting way after the end of a list work in Python?
tagged with: python
tagged with: list
downvote count: 0
answer count: 0
score: 1

http://stackoverflow.com/comment/89940423
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51485188
has text: I feel that if the order in which the merge changes (in respect to when I train/test and when I try and predict) it would have a negative impact on my models performance? Just wanted to ensure.

http://stackoverflow.com/q/51546736
downvote count: 0
score: 1
has body: I have a np.array with 400 entries, each containing the values of a spectrum with 1000 points. I want to identify the n most interesting indices of the spectrum and return them. So I can visualize and use them as an input vector for my classificator. Is it best to calculate the variance, apply a PCA or are there better-suited algorithms? And how do I compute the accounted variance for that selection? Thanks
type: Question
has title: Dimension reduction by identifying important Variables
upvote count: 1
answer count: 1
tagged with: variance
favorite count: 0
has answer: http://stackoverflow.com/a/53248741
accepted answer: http://stackoverflow.com/a/53248741
tagged with: python
tagged with: dimensionality-reduction
type: AnsweredQuestion
tagged with: pca

http://stackoverflow.com/q/51534769
tagged with: python
has body: m = [{"text":"mamamia","speaker":"","id":0},{"text":"mamamia","speaker":"","id":1},{"text":"mamamia","speaker":"","id":2},{"text":"mamamia","speaker":"","id":3},{"text":"mamamia","speaker":"","id":4},{"text":"mamamia","speaker":"","id":5}] I would like to print all the values for "id". From 0 -5. Then make changes into it to become 6-11. And then the new value append it to the old one and save the file. Is it possible to do it?
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/51535918
tagged with: http://stackoverflow.com/tag/json
has title: How to loop and print all the values for each key in string for json?
type: Question
accepted answer: http://stackoverflow.com/a/51536660
score: -1
possible better answer: http://stackoverflow.com/a/51534885
has answer: http://stackoverflow.com/a/51534885
answer count: 3
has answer: http://stackoverflow.com/a/51536660
downvote count: 1
tagged with: string
favorite count: 0

http://stackoverflow.com/q/51638673
score: -2
answer count: 2
possible better answer: http://stackoverflow.com/a/51638716
has answer: http://stackoverflow.com/a/51638716
has title: re.sub doesn't replace the string when I execute the file
accepted answer: http://stackoverflow.com/a/51638711
favorite count: 0
has body: I am trying to write a python script to practice the re.sub method. But when I use python3 to run the script, I figure out that the string in the file doesn't change. Here is my location.txt file, 34.3416,108.9398 this is what regex.py contains, import re with open ('location.txt','r+') as second: content = second.read() content = re.sub('([-+]?\d{2}\.\d{4},[-+]?\d{2}\.\d{4})','44.9740,-93.2277',content) print (content) I set up a print statement to test the output, and it gives me 34.3416,108.9398 which is not what I want. Then I change the "r+" to "w+", it completely removes the location.txt content. Can anyone tell me the reason?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90241831
downvote count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/51638711
type: Question
has comment: http://stackoverflow.com/comment/90241874

http://stackoverflow.com/a/56034690
has comment: http://stackoverflow.com/comment/136010160
answers question: http://stackoverflow.com/q/51552706
type: Answer
downvote count: 0
score: 1
has body: I think it could be a solution as using a "container" to protect our code from the person we wouldn't let them access. the problem is docker is not a secure container. As the root of the host machine has the most powerful control of the Docker container, we don't have any method to protect the root from accessing inside of the container. I just have some ideas about a secure container: Build a container with init file like docker file, a password must be set when the container is created; once the container is built, we have to use a password to access inside, including reading\copy\modify files all the files stored on the host machine should be encypt。 no "retrieve password" or “--skip-grant-” mode is offered. that means nobody can access the data inside the container if u lost the password. If we have a trustable container where we can run tomcat or Django server, code obfuscation will not be necessary.
upvote count: 1

http://stackoverflow.com/comment/90159262
comment on: http://stackoverflow.com/q/51596270
score: 0
type: QuestionComment
has text: @KennyOstrom My final goal is to emulate a piece of hardware. That hardware has a microcontroller running up to a few MHz and no floating point module. A microsecond timer is implemented on it. I'm currently trying to emulate that timer on which the rest of the operation performed by the MCU will be based.
type: Comment

variables
tag name: variables
tags question: http://stackoverflow.com/q/51534256
tags question: http://stackoverflow.com/q/51593702
tags question: http://stackoverflow.com/q/51556958
tags question: http://stackoverflow.com/q/51566284
tags question: http://stackoverflow.com/q/51541431
tags question: http://stackoverflow.com/q/51502479
tags question: http://stackoverflow.com/q/51564669
tags question: http://stackoverflow.com/q/51598745
tags question: http://stackoverflow.com/q/51590633
tags question: http://stackoverflow.com/q/51586295
tags question: http://stackoverflow.com/q/51488941
type: Tag
tags question: http://stackoverflow.com/q/51619341
tags question: http://stackoverflow.com/q/51621405
tags question: http://stackoverflow.com/q/51586260
tags question: http://stackoverflow.com/q/51493313
tags question: http://stackoverflow.com/q/51585600
tags question: http://stackoverflow.com/q/51523999
tags question: http://stackoverflow.com/q/51505207
tags question: http://stackoverflow.com/q/51577957
tags question: http://stackoverflow.com/q/51598169
tags question: http://stackoverflow.com/q/51635303

http://stackoverflow.com/q/51585110
tagged with: io
tagged with: python
has body: Decoding a byte stream into a text stream is easy: import io f = io.TextIOWrapper(io.BytesIO(b'Test\nTest\n'), 'utf-8') f.readline() In this example, io.BytesIO(b'Test\nTest\n') is a byte stream and f is a text stream. I want to do exactly the opposite of that. Given a text stream or file-like object, I would like to encode it into a byte stream or file-like object without processing the entire stream. This is what I've tried so far: import io, codecs f = codecs.getreader('utf-8')(io.StringIO('Test\nTest\n')) f.readline() # TypeError: can't concat str to bytes f = codecs.EncodedFile(io.StringIO('Test\nTest\n'), 'utf-8') f.readline() # TypeError: can't concat str to bytes f = codecs.StreamRecoder(io.StringIO('Test\nTest\n'), None, None, codecs.getreader('utf-8'), codecs.getwriter('utf-8')) # TypeError: can't concat str to bytes f = codecs.encode(io.StringIO('Test\nTest\n'), 'utf-8') # TypeError: utf_8_encode() argument 1 must be str, not _io.StringIO f = io.TextIOWrapper(io.StringIO('Test\nTest\n'), 'utf-8') f.readline() # TypeError: underlying read() should have returned a bytes-like object, not 'str' f = codecs.iterencode(io.StringIO('Test\nTest\n'), 'utf-8') next(f) # This works, but it's an iterator instead of a file-like object or stream. f = io.BytesIO(io.StringIO('Test\nTest\n').getvalue().encode('utf-8')) f.readline() # This works, but I'm reading the whole stream before converting it. I'm using Python 3.7
tagged with: stream
has answer: http://stackoverflow.com/a/51585265
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51585265
has title: How to encode a text stream into a byte stream in Python 3?
tagged with: character-encoding
type: Question
score: 12
upvote count: 12
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/51514363
upvote count: 3
type: AcceptedAnswer
has body: As Erwin Kalvelagen correctly stated, it is a linear problem. In order to document the solution, I used linprog import numpy as np from scipy.optimize import linprog #Inputs into the Equation #We want to minimize Amount and keep Risk constant #Input Amount Amount=np.array([10000000,-2000000,400000000,60000000]) #Input Risk Risk = np.array([[-10000,5000,-20000,500]]) c= Amount A_eq = Risk b_eq = np.sum(A_eq) linprog(c,A_eq=A_eq,b_eq=b_eq) I get the correct result: fun: 24500000.0 message: 'Optimization terminated successfully.' nit: 2 slack: array([], dtype=float64) status: 0 success: True x: array([ 2.45, 0. , 0. , 0. ])
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51508583
score: 3
answers question: http://stackoverflow.com/q/51508583
has comment: http://stackoverflow.com/comment/90015971

http://stackoverflow.com/q/51531715
has comment: http://stackoverflow.com/comment/105302520
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/55501643
tagged with: excel
has body: I want to write multiple df of varying sizes to Excel as my code runs. Some tables will contain source data, and other tables will contain Excel formulas that operate on that source data. Rather than tracking the range of cells that I wrote the source data to, I want the formula df to contain an Excel reference to the source data df. This can be done with Excel's Names or with Excel's Table features. For example in my formula df I can have =INDEX(my_Defined_Name_source_data, 4,3) * 2 and the Excel Name my_Defined_Name_source_data is all I need to index my source data. Openpyxl details writing Tables here https://openpyxl.readthedocs.io/en/stable/worksheet_tables.html?highlight=tables Tables doesn't support the merged cells which a multiindex df.to_excel will create. So I'm looking at Defined Names instead. There's almost no documentation for writing Defined Names in openpyxl using wb.defined_names.append() This is what I've found https://openpyxl.readthedocs.io/en/stable/api/openpyxl.workbook.defined_name.html?highlight=definednames What I'm asking for help with: How to write a DataFrame to Excel and also give it an Excel Defined Name. Documentation and online examples are almost non existent. Also gratefully accepting suggestions for alternative ideas since I seem to be accessing something almost nobody else uses.
linked to: http://stackoverflow.com/q/14507794
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/52719346
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51545396
accepted answer: http://stackoverflow.com/a/51545396
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/55501643
upvote count: 1
has title: Pandas dataframe to Excel with Defined Name range
favorite count: 0

http://stackoverflow.com/comment/89938764
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51484809
has text: Wrap the two functions in another function: `"cat": lambda: function1(), function2()`.
score: 0

http://stackoverflow.com/comment/89941675
has text: thx!. The problem is that the items_to_process are several subelements from array_index, I need to process every n=4 idxs and not to every m=5 idxs. Starting from a n2=arbitrary index, until the end of the array.
comment on: http://stackoverflow.com/a/51486106
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90050423
score: 1
has text: Directly updating `self.__dict__` is not the recommanded way - if you have any binding descriptor (ie a read/write property) it won't be invoked. The proper solution is to use `setattr(self, name, val)`.
type: AnswerComment
comment on: http://stackoverflow.com/a/51541312
type: Comment

http://stackoverflow.com/a/51541091
type: Answer
has comment: http://stackoverflow.com/comment/90052675
accepted answer of: http://stackoverflow.com/q/51540597
has comment: http://stackoverflow.com/comment/90057537
answers question: http://stackoverflow.com/q/51540597
has body: how do I, without re-running the python script hook into it and run my commands? You would need to make the single Python script keep listening for the new input or requests (back and forth communication), but I think that would be a slight pain and also makes your python script less clear than the standard input -&gt; process -&gt; output flow. What is the reason for avoiding running multiple Python scripts? To write input to your scripts stdin, do something like this: public static void main(String[] args) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder("python", "path\\to\\script.py"); Process pr = pb.start(); try (BufferedWriter writerToProc = new BufferedWriter( new OutputStreamWriter(pr.getOutputStream())); BufferedReader readerOfProc = new BufferedReader( new InputStreamReader(pr.getInputStream())); BufferedReader errorsOfProc = new BufferedReader( new InputStreamReader(pr.getErrorStream()))) { writerToProc.write("WhoIs\n"); writerToProc.write("ReadHexFile\n"); // is this the syntax? writerToProc.write("SendFile 'path\to\file.txt'\n"); writerToProc.flush(); StringBuilder procOutput = new StringBuilder(); boolean gaveUp = false; long waitTime = 10 * 1_000; // 10 seconds long lastRead = System.currentTimeMillis(); for(;;) { final long currTime = System.currentTimeMillis(); final int available = readerOfProc.available(); if(available &gt; 0){ // TODO read the available bytes without blocking byte[] bytes = new byte[available]; readerOfProc.read(bytes); procOutput.append(new String(bytes)); // maybe check this input for an EOF code // your python task should write EOF when it has finished lastRead = currTime; } else if((currTime - lastRead) &gt; waitTime){ gaveUp = true; break; } } // readerOfProc.lines().forEach((l) -&gt; System.out.println(l)); // errorsOfProc.lines().forEach((l) -&gt; System.out.println(l)); } }
has comment: http://stackoverflow.com/comment/90062835
has comment: http://stackoverflow.com/comment/90059546
has comment: http://stackoverflow.com/comment/90065477
has comment: http://stackoverflow.com/comment/90082354
has comment: http://stackoverflow.com/comment/90052773
has comment: http://stackoverflow.com/comment/90049923
has comment: http://stackoverflow.com/comment/90051072
score: 0
has comment: http://stackoverflow.com/comment/90056787
has comment: http://stackoverflow.com/comment/90065618
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90052600

http://stackoverflow.com/comment/90017594
type: Comment
score: 1
type: AnswerComment
has text: @MapMan - I've updated my answer. Please let me know if you still have issues.
comment on: http://stackoverflow.com/a/51502808

http://stackoverflow.com/comment/89955585
score: 0
type: Comment
type: QuestionComment
has text: (1,2) is a tuple, better make it while userinput not in (1,2):
comment on: http://stackoverflow.com/q/51493313

http://stackoverflow.com/comment/90218338
comment on: http://stackoverflow.com/q/51626281
score: 0
type: QuestionComment
has text: @Hamidreza I mean if we split the wk by columns, IDs will be unique like Df2.
type: Comment

http://stackoverflow.com/comment/90065352
has text: and I also updated `dashboard`, forgot the `a` in dashboard. I guess my spelling is off here at the end of my day.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51548811

http://stackoverflow.com/a/51499790
type: Answer
has body: convert arrays to strings by if you want to maintain this shape.
answers question: http://stackoverflow.com/q/51498368
score: 0

http://stackoverflow.com/q/51566336
type: Question
has body: I'm working on a python file that extracts movies and their details from a JSON file and then saves the data to a custom movie object. Right now, I can select a single movie out of the huge list. However, I want to be able to loop through and get every single genre, director, actor and add them to a separate array. Right now when I try to do this I get this error: Traceback (most recent call last): File "/Users/leoconnelly/PycharmProjects/MLFinal/tester.py", line 27, in &lt;module&gt; tempGenre = (contents['results'][i]['genre']) TypeError: list indices must be integers or slices, not str I also want to create an array of my custom movie objects that has title, cast, director, and genre. Here's what my code looks like: from movie import Movie from user import User import json from pprint import pprint movieArray = [] nameArray = [] directorArray = [] genreArray = [] ##actorArray = [] movieToBeInputted = Movie("","","","") with open('movies.json') as f: contents = json.load(f) print(contents['results'][600]['title']) movieToBeInputted.name = (contents['results'][600]['title']) movieToBeInputted.director = (contents['results'][600]['director']) movieToBeInputted.genre = (contents['results'][600]['genre']) movieToBeInputted.actors = (contents['results'][600]['cast']) movieArray.append(movieToBeInputted) for i in contents: tempGenre = (contents['results'][i]['genre']) genreArray.append(tempGenre) #this is where the error happens print("xxxxxxx") print(movieToBeInputted.actors) ##d = json.load(json_data) ##json_movie_data = json.dumps(json_data) ##movieToBeInputted.actors = json_movie_data Here's my json data: { "results": [ { "title": "After Dark in Central Park", "year": 1900, "director": null, "cast": null, "genre": null, "notes": null }, { "title": "Boarding School Girls' Pajama Parade", "year": 1900, "director": null, "cast": null, "genre": null, "notes": null }, { "title": "Buffalo Bill's Wild West Parad", "year": 1900, "director": null, "cast": null, "genre": null…
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51566418
has comment: http://stackoverflow.com/comment/90099441
favorite count: 0
tagged with: python
type: UnansweredQuestion
upvote count: 1
score: 1
tagged with: http://stackoverflow.com/tag/json
has title: How do I loop through an entire JSON file and extract the data into variables

http://stackoverflow.com/a/51553094
answers question: http://stackoverflow.com/q/51547935
type: AcceptedAnswer
type: Answer
upvote count: 2
score: 1
downvote count: 1
has body: If you want to start at the seventh row, just create six empty ones. If you want to start at the seventh column just pad the row from the dataframe with a list of None that is wide enough.
accepted answer of: http://stackoverflow.com/q/51547935

http://stackoverflow.com/comment/90224903
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51559164
type: Comment
has text: Actually, I have just noticed this doesn't work as expected. The date indices don't seem to kept across operations, and given every single series has different start and end dates the data gets mixed up...

http://stackoverflow.com/q/51570206
favorite count: 0
tagged with: redis
tagged with: python-rq
tagged with: python
has comment: http://stackoverflow.com/comment/118025986
has body: I'm enqueueing several jobs to a rq.Queue and want to wait (not busy wait) until the queue is empty and all jobs were handled. Is there such an event to listen to?
has title: python-rq - how do I wait for the entire queue to be handled?
answer count: 0
type: UnansweredQuestion
type: Question
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/comment/89976791
type: Comment
type: QuestionComment
has text: Iterate through every line. If it has a date, append it to a new list. If it does not, append it to the last element in the list.
comment on: http://stackoverflow.com/q/51503935
score: 0

http://stackoverflow.com/comment/90192451
type: Comment
type: QuestionComment
has text: Yup, my bad! ;)
score: 0
comment on: http://stackoverflow.com/q/51613290

http://stackoverflow.com/comment/90201996
comment on: http://stackoverflow.com/a/51600796
score: 0
type: AnswerComment
has text: @raam indeed, it's because 'first' and 'last' are names for column I should not use like this. Try `mdf.loc[mdf['first'] <= mdf['last']]` should work
type: Comment

http://stackoverflow.com/comment/89983469
comment on: http://stackoverflow.com/a/51507148
score: 0
type: AnswerComment
has text: How do I edit a value inside my list? Say if my value for a test says it's 'Pending', I would like to modify it to 'Pass'
type: Comment

http://stackoverflow.com/comment/90042889
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51537027
has text: Thanks, it appeared it was a typo in the hash thanks.
type: AnswerComment

http://stackoverflow.com/comment/90112918
type: QuestionComment
has text: No. A lot of things are unclear. For example, we don't know how can we choose a pokemon at the beginning. You should tell us pokemon are chosen by the exact name displayed in the console, not by a list index. Without instructions, it's hard to answer.
comment on: http://stackoverflow.com/q/51572195
score: 0
type: Comment

http://stackoverflow.com/comment/90242897
type: QuestionComment
comment on: http://stackoverflow.com/q/51639170
type: Comment
has text: you need a csv-file-reader that accepts your "safe" string. Quoting the whole as `'"I have apples, pears and bannanas" , 22, 44'` should do it to get 3 colums
score: 0

http://stackoverflow.com/comment/90187663
type: QuestionComment
score: 5
comment on: http://stackoverflow.com/q/51611378
has text: `pd.read_csv('myfile', skiprows = 1)`
type: Comment

http://stackoverflow.com/a/51540354
has body: It could be that Imagenet Weights are not compatible with your new image dimension. I see that your only trainable layer is the very last layer, a dense layer, which doesn’t know anything about image dimension. My suggestion is to also let the first few convolutional layers to be trainable, so that those layers can adapt to the rescaling.
answers question: http://stackoverflow.com/q/51540068
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/98550895

http://stackoverflow.com/a/51615612
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/90196681
has comment: http://stackoverflow.com/comment/90196698
has comment: http://stackoverflow.com/comment/90196663
has comment: http://stackoverflow.com/comment/90196744
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51615580
answers question: http://stackoverflow.com/q/51615580
has comment: http://stackoverflow.com/comment/90197120
has body: for i in mylist: mylist.append(i.upper()) is basically appending to your list while iterating on it. So the iteration never ends. You want to do: mylist += [i.upper() for i in mylist] in that last case, the right-hand expression is computed from a non-modified mylist, then its elements are appended to the existing mylist. note that the above is equivalent to mylist.extend([i.upper() for i in mylist]) or mylist.extend(list(map(str.upper,mylist))) note that for both snippets above it is necessary to convert to list, or you get the same memory error if the inside is lazily evaluated. The last snippet is probably the fastest because it doesn't use any python loops at all, map, and no lambda For all 3 snippets the result is: ['phonon', 'communication', 'PHONON', 'COMMUNICATION']
has comment: http://stackoverflow.com/comment/90196569
has comment: http://stackoverflow.com/comment/90196622
has comment: http://stackoverflow.com/comment/90197137
upvote count: 3
has comment: http://stackoverflow.com/comment/90196633

http://stackoverflow.com/comment/90101225
has text: Whats your question?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51567356

http://stackoverflow.com/comment/90066352
score: 0
type: AnswerComment
has text: the issue i found is that the ids are not grouped by a function like groupby so what ends up happening is row 7 is being compared with 1 and not nan like row 1, 2 and 3, which is a false positive.
type: Comment
comment on: http://stackoverflow.com/a/51543906

http://stackoverflow.com/q/51622776
tagged with: javascript
has comment: http://stackoverflow.com/comment/90210970
favorite count: 0
has comment: http://stackoverflow.com/comment/90210908
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90211272
score: -1
type: Question
has comment: http://stackoverflow.com/comment/90211128
downvote count: 2
has answer: http://stackoverflow.com/a/51623010
has title: How to I turn a python script into a web app?
upvote count: 1
answer count: 1
has body: Sorry for the noob question, but I created a script that web scrapes data off our sccm server and compares it to programs that need to be pushed to hostnames. My script works perfectly when I run it in pycharm, but I would now like to make this program available to the other guys on my team via webpage, instead of them needing to borrow my computer everytime, LOL! Is there a way I can use a javascript front end to let them enter their username, password and serial number, and than based off that info run my script? I'm not a programmer to be honest so I apologize if this seems like a straightforward thing.

http://stackoverflow.com/q/51490597
type: AnsweredQuestion
has title: how to move file to specific folder(unicode) in python
has comment: http://stackoverflow.com/comment/89952014
answer count: 2
tagged with: file-move
accepted answer: http://stackoverflow.com/a/51491702
tagged with: unicode
score: 0
tagged with: python
has body: I want to move the files to a specific folder. However, due to a problem with Unicode, the file is not being moved. import os import shutil file=r"c:/test/test.rar" folder=r"c:/test/発射" shutil.move(file, folder) #os.rename(file, os.path.join(folder, os.path.split(file)[1])) "shutil.move" and "os.rename" return "[Errno 22] invalid mode ('wb') or filename" and "WindowsError: [Error 123] file name". They do not recognize Unicode filename. I searched for many solutions, but I could not solve them. Can this be solved? Thank you in advance for your help.
possible better answer: http://stackoverflow.com/a/51490840
has answer: http://stackoverflow.com/a/51490840
has answer: http://stackoverflow.com/a/51491702
type: Question

http://stackoverflow.com/q/51542722
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51552523
tagged with: multithreading
accepted answer: http://stackoverflow.com/a/51552523
type: Question
tagged with: pyqt4
score: 0
tagged with: pyqt
answer count: 1
has title: PyQt4 setText dynamic from other class with a link script
tagged with: rfid
has body: Everything works instead of this inconvenience. I tried to set text, but it doesn't work. Every new scan it should appear new text scanned from tag, but it is the same text from global variables from RFID script. from PyQt4 import QtCore, QtGui from ui_mainwindow import Ui_MainWindow import threading import RPi.GPIO as GPIO import MFRC522 import signal import time class MainWindow(QtGui.QMainWindow): state1, state2, state3, state4 = range(4) stateChanged = QtCore.pyqtSignal(int) def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.stateChanged.connect(self.onChangeState) threading.Thread(target=self.reading, daemon=True).start() def onChangeState(self, state): MIFAREReader = MFRC522.MFRC522() if state == MainWindow.state1: self.ui.label_4.setText(MIFAREReader.tagId) ###--&gt;text from RFID script self.ui.label_2.setText(MIFAREReader.tagName) ###--&gt;text from RFID script self.ui.label_3.setText(MIFAREReader.tagDetails) ###--&gt;text from RFID script self.ui.label_3.show() self.ui.label_2.show() self.ui.label_4.show() self.ui.groupBox.setStyleSheet("background: white;\n" "border-style: solid;\n" "border-width: 1px;\n" "border-radius: 20px;") elif state == MainWindow.state2: self.ui.label_3.hide() self.ui.label_2.hide() self.ui.label_4.hide() self.ui.groupBox.setStyleSheet("background: white url(scan.png) no-repeat center;\n" "border-style: solid;\n" "border-width: 1px;\n" "border-radius: 20px;") elif state == MainWindow.state3: self.ui.groupBox.setStyleSheet("background: white url(accsd.png) no-repeat center;\n" "border-style: solid;\n" "border-width: 1px;\n" "border-radius: 20px;") elif state == MainWindow.state4: self.ui.groupBox.setStyleSheet("background: white url(scan.png) no-repeat center;\n" "border-style: solid;\n" "border-width: 1px;\n" "border-radius: 20px;") def reading(self): ### Event Functions ### continue_reading = True # Hook the SIGINT #signal.signal(signal.SIGINT, end_read) #…
tagged with: python

http://stackoverflow.com/a/51493371
answers question: http://stackoverflow.com/q/51493185
score: 0
type: Answer
has body: a performant approach would be to build a "flat" dictionary with each word as key and the relevant group of words as value. L2=['marvel comics','bmw','mercedes benz','audi'] match_dict = {k:v for v in L2 for k in v.split()} which is: {'audi': 'audi', 'benz': 'mercedes benz', 'bmw': 'bmw', 'comics': 'marvel comics', 'marvel': 'marvel comics', 'mercedes': 'mercedes benz'} now scan the first list and issue element if in dictionary: L1=['marvel','audi','mercedes','honda'] result = [match_dict[x] for x in L1 if x in match_dict] result: ['marvel comics', 'audi', 'mercedes benz'] once the dictionary is built, you can scan large lists with high performance (O(1) lookup)

http://stackoverflow.com/q/51530094
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51546462
has title: Convert a mix of Pandas/List/Array to something Tensorflow will accept?
type: Question
tagged with: numpy
has body: I am using this to read some data into a character-level one-hot encoding. It's a bit inefficient but this is demonstration code so clarity is valued over performance: import tensorflow as tf sess = tf.Session() def onehot(str): chars = list(map(lambda c: max(0, ord(c) - 48), list(str))) twoDim = sess.run(tf.one_hot(chars, 122 - 48)) # flatten the 2D array: return [item for sublist in twoDim for item in sublist] import pandas df = pandas.read_csv(sys.argv[1]) train_inputs = df['input'].map(onehot).values train_labels = df['output'].map(onehot).values The resulting arrays print as [list([0.0, 0.0, 0.0, 0.0, ... Later in the code, I feed these arrays into a TF cost optimization function: _,cost = sess.run(train_step, feed_dict={x: train_inputs, y_: train_labels}) where I get this error: ValueError: setting an array element with a sequence. Frankly I am baffled by Python's representation of array-like data structures, the nuances between list, array, ndarray, numpy array, pandas dataframe, etc, and I don't understand what I'm missing. How can I convert the train_* variables to an array-like structure that Tensorflow will accept? Please feel free to answer with a checklist that could help others in the future, or a point-answer that just fixes my code. SAMPLE DATA Here's what my input csv file looks like: input,output abc,def ghi,jkl 123,456
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/90039012
has comment: http://stackoverflow.com/comment/90057183
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51592977
has body: You can use 'Counter' from Collections. https://docs.python.org/2/library/collections.html This will automatically group the identical names for you. You need not calculate the number of occurrences. For eg: &gt;&gt;&gt; from collections import Counter as c &gt;&gt;&gt; a = ('team a', 'team b', 'team a', 'team c', 'team b') &gt;&gt;&gt; c(a) Counter({'team a': 2, 'team b': 2, 'team c': 1})
answers question: http://stackoverflow.com/q/51592889
downvote count: 0
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/q/51563186
tagged with: request
tagged with: python-requests
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90093296
type: AnsweredQuestion
score: -1
has answer: http://stackoverflow.com/a/51563303
upvote count: 0
answer count: 1
has title: How to construct this form data to make a post request using python
has comment: http://stackoverflow.com/comment/90093462
tagged with: form-data
tagged with: python
has comment: http://stackoverflow.com/comment/90093481
favorite count: 0
accepted answer: http://stackoverflow.com/a/51563303
has body: I am trying to write a post request using python's request library. I am trying to fetch details of some startups from angel.co website. When I am inspecting the request using firefox's developer tools, the post request contains the form data like this - filter_data[locations][]=1647-India. I want to know how can I construct this exact form data in python so that I can make the request and get the same result, as I am getting in my browser.
has comment: http://stackoverflow.com/comment/90093326

http://stackoverflow.com/q/51600075
tagged with: postgresql
has body: Working in Jupyter with Python3 and psycopg2 to load csv into psql. First two columns are an ISO format I'm not too familiar with. Is there a simple data type that will accept: 2017-01-01T23:00:00-00:00 I've tried date, timestamp, timestamp w/o timezone, timestamp w/timezone. Do I need to pre-process in order to convert timestamp to friendlier format? I thought I could do something like - cur.execute(""" CREATE TABLE test( id integer PRIMARY KEY, intervalbegin_gmt timestamp, intervalend_gmt timestamp, ... Getting error - DataError: invalid input syntax for integer: "2017-01-01T23:00:00-00:00"
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51600197
upvote count: 2
tagged with: datetime
tagged with: python
tagged with: psycopg2
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51600197
type: Question
has title: Postgres timestamp not accepting 2017-01-01T23:00:00-00:00
downvote count: 0

http://stackoverflow.com/q/51616661
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90199379
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90201246
tagged with: histogram
has title: What is the best way to compare and visualize two word frequencies?
tagged with: word-frequency
has body: I have two dictionaries Counter({'physical_object': 37, 'psychological_feature': 35, 'attribute': 27, 'cause': 11, 'physical_process': 9, 'part': 9, 'measure': 9, 'relation': 5, 'group': 5, 'substance': 3, 'communication': 2, 'body_of_water': 1, 'fluid': 1}) Counter({'physical_object': 13, 'psychological_feature': 8, 'measure': 7, 'attribute': 4, 'relation': 3, 'physical_process': 2, 'cause': 2, 'group': 1, 'part': 1, 'fluid': 1}) Is there a way to plot the two distributions in percentage, to show if there is a certain pattern they follow or if they diverge in something? Right now I only have a double histogram, but I was looking for something that could show the pattern better! My code now: colors = ['b','g'] plt.hist([list(counter_fourth.values()), list(pr_counter_fourth.values())], alpha=0.5, color=colors) plt.legend(loc='upper right') plt.show()

http://stackoverflow.com/comment/90190925
type: Comment
comment on: http://stackoverflow.com/q/51609426
has text: @AgashThamo. I switched over to use Anaconda Spyder, just to try it in a different environment and got a different error as you can see in my edit above
score: 0
type: QuestionComment

http://stackoverflow.com/a/51537209
has body: It is possible to use only vectorised operations for this task. You can use pd.Series.bfill to create a mapping from your original index to a new one: counts = df['group'].value_counts().sort_index().reset_index() counts['original'] = counts['index'] counts.loc[counts['group'] == 1, 'index'] = np.nan counts['index'] = counts['index'].bfill().astype(int) print(counts) index group original 0 2 1 1 1 2 3 2 2 5 1 3 3 5 1 4 4 5 2 5 Then use pd.Series.map to perform your mapping: df['group'] = df['group'].map(counts.set_index('original')['index']) print(df) group num 0 2 0.43 1 2 5.20 2 2 1.30 3 2 0.33 4 5 0.74 5 5 0.50 6 5 0.20 7 5 0.12
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51536958
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/90048801

http://stackoverflow.com/q/51576635
has comment: http://stackoverflow.com/comment/90118785
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51576690
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90118759
score: 0
answer count: 1
tagged with: geometry
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90118792
tagged with: python
has body: I have some locations of features that are represented in pixel coordinate space (ie. (0,0) is in the top left corner of the image, and the y axis increases downwards and the x axis increases rightwards). When I plot these locations in Matplotlib (which by default uses the positive x and positive y quadrant of a cartesian plane) I always run the command plt.gca().invert_yaxis() so that the locations of the features look right in the plot. However, I would like to apply this transformation to the image points themselves, not just in the visualization.
has comment: http://stackoverflow.com/comment/90118920
has title: Invert y axis on actual data instead of just on the plot

http://stackoverflow.com/a/51629651
has comment: http://stackoverflow.com/comment/90224354
has comment: http://stackoverflow.com/comment/90224288
has body: I think problem is with mixed values - numeric with strings: data = pd.DataFrame({'Lat':['a',2,3]}) print (data) Lat 0 a 1 2 2 3 #data = data.sort_values(['Lat']) So possible solution is convert all non numeric to NaNs by to_numeric with errors='coerce' data['Lat'] = pd.to_numeric(data['Lat'], errors='coerce') data = data.sort_values(['Lat']) print (data) Lat 0 2.0 1 3.0 2 NaN EDIT: You can check all non numeric values: df = data[pd.to_numeric(data['Lat'], errors='coerce').isnull()] print (df) Lat 3 a
has comment: http://stackoverflow.com/comment/90224414
answers question: http://stackoverflow.com/q/51629567
has comment: http://stackoverflow.com/comment/90225057
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90224080
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51629567
has comment: http://stackoverflow.com/comment/90225193
has comment: http://stackoverflow.com/comment/90223828
has comment: http://stackoverflow.com/comment/90223795
type: Answer
has comment: http://stackoverflow.com/comment/90223663
has comment: http://stackoverflow.com/comment/91212222
has comment: http://stackoverflow.com/comment/90223689
has comment: http://stackoverflow.com/comment/90224870
has comment: http://stackoverflow.com/comment/90223581
has comment: http://stackoverflow.com/comment/90223976
upvote count: 3
has comment: http://stackoverflow.com/comment/90224225
has comment: http://stackoverflow.com/comment/90224719
has comment: http://stackoverflow.com/comment/90224478
has comment: http://stackoverflow.com/comment/90224022
has comment: http://stackoverflow.com/comment/90224591
score: 3
has comment: http://stackoverflow.com/comment/90224819
has comment: http://stackoverflow.com/comment/91208552

http://stackoverflow.com/comment/90129499
type: QuestionComment
score: 1
has text: The function `tts` will stop to exist once `load` is completed. So you can not simply call it from the outside.
comment on: http://stackoverflow.com/q/51582040
type: Comment

http://stackoverflow.com/q/51589210
upvote count: 7
has body: Hi I have a dataframe with some missing values ex: The black numbers 40 and 50 are the values already inputted and the red ones are to autofill from the previous values. Row 2 is blank as there is no previous number to fill. Any idea how I can do this efficiently? I was trying loops but maybe there is a better way
type: Question
score: 5
has comment: http://stackoverflow.com/comment/90143811
has comment: http://stackoverflow.com/comment/90144222
tagged with: dataframe
has answer: http://stackoverflow.com/a/51589382
has answer: http://stackoverflow.com/a/51589703
answer count: 2
accepted answer: http://stackoverflow.com/a/51589382
possible better answer: http://stackoverflow.com/a/51589703
favorite count: 0
linked to: http://stackoverflow.com/q/27905295
has comment: http://stackoverflow.com/comment/90143778
tagged with: python
has title: Fill NaN values in dataframe with previous values in column
type: AnsweredQuestion
downvote count: 2

http://stackoverflow.com/a/51608084
score: 1
has body: Use melt with groupby, aggregate size and last reshape by unstack: df = df.melt('ID').groupby(['ID', 'value']).size().unstack(fill_value=0) Another solution with pivot_table: df = df.melt('ID').pivot_table(index='ID', columns='value', aggfunc='size') Or with crosstab: df1 = df.melt('ID') df = pd.crosstab(df1['ID'], df1['value']) print (df) value Active Closed Dollars Euro Home ID 1 2 1 2 1 3 2 2 1 2 1 3
has comment: http://stackoverflow.com/comment/90188806
has comment: http://stackoverflow.com/comment/90188084
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51607727
type: Answer
has comment: http://stackoverflow.com/comment/90188207
accepted answer of: http://stackoverflow.com/q/51607727
downvote count: 0

http://stackoverflow.com/q/51493201
duplicate of: http://stackoverflow.com/q/36622480
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/98245021
has title: How do you find the PIP distribution name of a Python package from the package's name?
downvote count: 0
has body: I am trying to programatically find information (such as version number) about imported modules using: pip show *insert package name* In Python this looks like: subprocess.check_output([sys.executable, '-m', 'pip', 'show', *packagename*]).decode("utf-8") However, the name that is passed as argument to PIP to find information is not always the same as the name used to import the module. Is there a way to find the name that PIP uses, from the name you use to import the module?
answer count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/19086030
tagged with: pip
upvote count: 1
linked to: http://stackoverflow.com/q/36622480

http://stackoverflow.com/q/51639365
upvote count: 1
answer count: 1
has body: I've been following a tutorial from here to build a small python game. This would be the code behind it: import pygame pygame.init() display_width = 1280 display_height = 720 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption("Racing Game") clock = pygame.time.Clock() black = (0,0,0) white = (255,255,255) carImg = pygame.image.load("racecar.png") def car(x,y): gameDisplay.blit(carImg, (x,y)) x = display_width * 0.45 y = display_height * 0.8 x_change = 0 car_speed = 0 crashed = True while crashed: for event in pygame.event.get(): if event.type == pygame.QUIT: crashed = False ## &lt;code to remove&gt; if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 elif event.key == pygame.K_RIGHT: x_change = 5 if event.type = pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 ## &lt;/code to remove&gt; print(event) x += x_change gameDisplay.fill((255,255,255)) car(x,y) pygame.display.update() clock.tick(60) pygame.display.quit() pygame.quit() quit() When I try to run it the window opens and immediately closes. If I remove however the code between the two ## &lt;code to remove&gt; and ## &lt;/code to remove&gt; everything works fine. What is causing in that piece of code for this to happen?
downvote count: 0
has comment: http://stackoverflow.com/comment/90243291
favorite count: 0
has title: Python window opens and closes
tagged with: pygame
has comment: http://stackoverflow.com/comment/90243336
has answer: http://stackoverflow.com/a/51639533
has comment: http://stackoverflow.com/comment/90243318
type: UnansweredQuestion
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/90243414
type: Question

http://stackoverflow.com/q/51616715
has answer: http://stackoverflow.com/a/59647033
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90199276
has title: Subtraction from the number until it is not equal to zero
has answer: http://stackoverflow.com/a/51616783
type: Question
score: 0
answer count: 2
has body: I've got a list of numbers [5,10,15,20] and I've got some kind of "discount" value let's say it is 20. The thing I want to do is to substract this discount value from every number until discount is equal to 0 (20-5=15, 15-10=5 then 15-5 = 10). I've tried something like this: for i in list: while i[0] &gt; 0: i[0] - discount if discount != 0: continue else: break But it seems to have no effect at all
has comment: http://stackoverflow.com/comment/90199521
tagged with: python

http://stackoverflow.com/comment/90097856
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51565122
has text: I included a snippet of my code to provide a better understanding of what I'm trying to accomplish.

http://stackoverflow.com/q/51536577
has answer: http://stackoverflow.com/a/51537992
tagged with: redis
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: mysql
type: Question
has body: I am learning to use docker in one of my project which has the following tech stack django redis mysql - production sqlite - development mongod I could configure a simple docker which covers django related and mysql but have no idea how to glue redis and mongod as well. I see various ways in internet but based on the configuration i already made how should i fit them well. Here is what I have done docker-compose.yml version: '3' services: db: image: mysql web: build: context: . dockerfile: docker/python/Dockerfile command: bash -c "sleep 3; python /code/manage.py migrate --noinput &amp;&amp; python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db Dockerfile # python image (https://hub.docker.com/_/python/) FROM python:3.6 # Environment Variables ENV PYTHONBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 COPY ./requirements/requirements.txt /code/requirements.txt RUN pip install -r /code/requirements.txt RUN chmod ug+x /code/initialize.sh COPY . /code/ WORKDIR /code EXPOSE 8000 initialize.sh #!/bin/bash # This script initializes the Django project. It will be executed (from # supervisord) every time the Docker image is run. # If we're not in production, create a temporary dev database if [ "$DJANGO_PRODUCTION" != "true" ]; then echo "DJANGO_PRODUCTION=false; creating local database..." # Wait until the MySQL daemon is running while [ "$(pgrep mysql | wc -l)" -eq 0 ] ; do echo "MySQL daemon not running; waiting one second..." sleep 1 done # Wait until we can successfully connect to the MySQL daemon until mysql -uroot -pdevrootpass -e ";" ; do echo "Can't connect to MySQL; waiting one second..." sleep 1 done echo "MySQL daemon is running; creating database..." mysql -uroot -e "CREATE DATABASE appDB; CREATE USER milan@localhost; SET PASSWORD FOR milan@localhost=PASSWORD('milan'); GRANT ALL PRIVILEGES ON appDB.* TO milan@localhost IDENTIFIED BY 'milan'; FLUSH PRIVILEGES;" -pdevrootpass; else echo "DJANGO_PRODUCTION=true; no local databas…
tagged with: docker
score: 0
has title: use redis and mongo alongside postgres in docker
answer count: 1

http://stackoverflow.com/a/51600998
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51562284
answers question: http://stackoverflow.com/q/51562284
has body: Well. I have found the solution. I need to use the request in the post_save method. However, you can't use it in Django signals, so it's possible to use the Django save_model method which you can get access to the request. def save_model(self, request, obj, form, change): if obj: # Save the object super().save_model(request, obj, form, change) # Add the user instance to M2M field of the request.user (The admin User) who create the RegularUser request.user.adminuser.usuarios.add(obj)
type: AcceptedAnswer

http://stackoverflow.com/q/51589814
has comment: http://stackoverflow.com/comment/90145835
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: getting an error on a list of lists :TypeError: 'int' object is not iterable
has body: I am trying to call the function tfidf on a list of lists total_all. I am getting an error message on running the line below: TypeError: 'int' object is not iterable tfidf(total_all) def tfidf(documents): global dftfidf dftfidf = pd.DataFrame() tokenized_documents = [tokenize(d) for d in documents] idf = inverse_document_frequencies(tokenized_documents) for term in idf.keys(): tf = sublinear_term_frequency(term, document) doc_tfidf.append(tf * idf[term]) tfidf_documents.append(doc_tfidf) dftfidf=pd.DataFrame(data ={'term frequency':tf,'tfidf':doc_tfidf}) return dftfidf tfidf(total_all)
answer count: 0
has comment: http://stackoverflow.com/comment/90144979
type: Question
score: 0

http://stackoverflow.com/comment/90173067
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51603442
has text: It will return rows with `null` values, so after dropna, may be you can chech, you can look into documentation https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isnull.html
score: 0

http://stackoverflow.com/q/51546348
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51596694
has comment: http://stackoverflow.com/comment/90060652
has comment: http://stackoverflow.com/comment/90060468
tagged with: list
has answer: http://stackoverflow.com/a/51546725
has comment: http://stackoverflow.com/comment/90060528
has comment: http://stackoverflow.com/comment/90060717
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90061322
score: 3
has body: I understand that in-place list methods return None instead of the mutated list. As far as I can see, this makes it impossible to use these methods as part of the internal logic of a list comprehension. What is the most pythonic way to create a list comprehension whose members result from mutating other lists? In other words: what is the best alternative to this (non-functioning) line: new_list = [old_list.insert(0, "X") for old_list in list_of_old_lists] Which results in a list of Nones because list.insert() returns None. Is it simply not possible to do this in an elegant single-line of code without a lot of slicing and concatenating? The example above is trivial for the sake of illustrating my question but in reality I'd like to do this in more complex situations in lieu of multiple nested 'for' loops. Here's a simplified sample of what I'm trying to do: word = 'abcdefg' variations_list = [] characters_to_insert = ['X', 'Y', 'Z'] for character in characters_to_insert: for position in range(len(word) + 1): w = list(word) w.insert(position, character) this_variation = ''.join(w) variations_list.append(this_variation) for v in variations_list: print(v) This works fine using nested 'for' loops, like this (my real application is much more complex/verbose than this sample). But I cannot do the same thing using list comprehension because the 'insert' method returns None: variations_list_comprehension = [list(word).insert(position, character) for position in range(len(word) +1) for character in ['X', 'Y', 'Z']] for v in variations_list_comprehension: print(v) Results in a list of None values because the in-place mutations return "None".
has comment: http://stackoverflow.com/comment/90094464
linked to: http://stackoverflow.com/q/5753597
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/90060937
upvote count: 4
answer count: 3
tagged with: string
has title: Alternatives to using in-place list methods within a list comprehension?
favorite count: 0
has answer: http://stackoverflow.com/a/51546536

awk
tag name: awk
tags question: http://stackoverflow.com/q/51544470
type: Tag
tags question: http://stackoverflow.com/q/51587643
tags question: http://stackoverflow.com/q/51569334

http://stackoverflow.com/comment/90109485
has text: have just tried that and no luck either
comment on: http://stackoverflow.com/q/51571392
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51532928
tagged with: cgi
tagged with: yocto
upvote count: 1
type: Question
has body: I have enabled apache2 on imx6ul board which is running on custom modified Linux kernel. On running the CGI-script the contents are displayed in a plain text format. The code is working fine on my personal pc. How do I enable CGI in embedded Linux distributions? The custom Linux is built using YOCTO project for imx6ul board and base BSP provided by the vendor. The configuration file in the filesystem is named httpd.conf instead of apache2.conf.
has title: While executing cgi,plain text is displayed
tagged with: apache
downvote count: 0
score: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/a/56807312
has body: I had a similar issue (although in .NET Framework). In my case the reason was that I was using the url without a forward slash in the end and the API apparently does not support that. So https://test.access.com/this/url Throws 401 error Unauthorized but https://test.access.com/this/url/ Returns 200 OK.
downvote count: 0
answers question: http://stackoverflow.com/q/51581667
type: Answer
score: 5
upvote count: 5

http://stackoverflow.com/q/51508682
has title: What is Numpy equivalence of dataframe.loc() in Pandas
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/51508733
accepted answer: http://stackoverflow.com/a/51508733
favorite count: 0
has comment: http://stackoverflow.com/comment/89987614
tagged with: pandas
tagged with: python
upvote count: 15
has answer: http://stackoverflow.com/a/51509221
downvote count: 1
score: 14
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51509221
has body: I have a 120,000*4 numpy array as shown below. Each row is a sample. The first column is time in second, or the index using Pandas terminology. 0.014 14.175 -29.97 -22.68 0.022 13.905 -29.835 -22.68 0.030 12.257 -29.32 -22.67 ... ... 1259.980 -0.405 2.205 3.825 1259.991 -0.495 2.115 3.735 I want to select the rows recorded between 100.000 to 200.000 sec and save it into a new array. If this were a Pandas dataframe, I would simply write df.loc[100:200]. What is the equivalent operation in numpy? This is NOT a question of feasibility. I simply wonder if there are any pythonic one-line solutions.

http://stackoverflow.com/comment/90028413
comment on: http://stackoverflow.com/a/51530050
type: AnswerComment
has text: I tried, failed, because `nan` will be returned when comparing `nan` with strings. so I tried `df.fillna('').groupby(df.columns,axis=1).max(axis=1)` as @RafrelC posted, that works fine.
type: Comment
score: 2

http://stackoverflow.com/comment/90127653
type: Comment
type: QuestionComment
has text: maybe use `!pip -y install keras==2.1.2`
comment on: http://stackoverflow.com/q/51581139
score: 0

http://stackoverflow.com/a/75825946
downvote count: 0
type: Answer
has body: Your example works as desired for recent Python versions. However, the documentation is still completely lacking for nesting dataclasses. If there are default parameters, the following methods also work: from dataclasses import dataclass @dataclass class One: f_one: int = 1 f_two: str = 'two' @dataclass class Two: f_three: str = 'three' f_four: One = One() # nested class instance with default parameters example = Two() example # nested class instance with different parameters example = Two(f_three='four', f_four=One(f_one=2, f_two='three')) example # same but using dict unpacking example = Two(**{'f_three': 'five', 'f_four': One(**{'f_one': 3, 'f_two': 'four'})}) example # or, by changing the class initialization method to ingest a vanilla dict: @dataclass class Two: f_three: str = '3' f_four: One = One() def __init__(self, d: dict): self.f_three = d.get('f_three') self.f_four = One(**d.get('f_four')) d = {'f_three': 'six', 'f_four': {'f_one': 4, 'f_two': 'five'}} example = Two(d) example The important thing here is that the class member pointing to the nested dataclass should have the type of the dataclass and be initialized with its values. You can nest together as many levels of dataclasses as you like this way. Another way is to simply use a dict, which is easily serialized/deserialized to/from JSON: # dict is all you need example = { 'three': '3', 'four': { 'one': 1, 'two': '2', } } An old hack borrowed from Kaggle is to unpack a nested list or dict into a Struct, which is not a dataclass, for dot access: class Struct(dict): """Dataclass structure that inherits from dict.""" def __init__(self, **entries): entries = {k: v for k, v in entries.items() if k != 'items'} dict.__init__(self, entries) self.__dict__.update(entries) def __setattr__(self, attr, value): self.__dict__[attr] = value self[attr] = value def structify(obj: Union[list,dict]) -> Struct: """Unpack list or dict into Struct for dot access of members.""" if isinstance(obj, list): return [structify(ob…
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51564841

http://stackoverflow.com/comment/90154596
comment on: http://stackoverflow.com/a/51593640
type: Comment
has text: What the negation does for you is to at least just ignore those it can not solve, and you have to solve those in another way. But they may be edge cases, so might not even be worth solving with regex. At some point complexity is no longer worth the effort to automatize and you just have to find and correct those manually. Don't try to hammer a screw because it looks kind of like a nail.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90179754
type: QuestionComment
has text: @Marco I think the same,there are actually eight expressions in your regexp, resulting in eight program branching, too. But i'm not an expert, just feel that way:-)
score: 1
comment on: http://stackoverflow.com/q/51600237
type: Comment

http://stackoverflow.com/q/51590696
has comment: http://stackoverflow.com/comment/90146613
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51608534
type: Question
accepted answer: http://stackoverflow.com/a/51608534
has title: Speeding up read_csv in python pandas
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/71031209
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/71031209
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/36587211
has comment: http://stackoverflow.com/comment/90152448
tagged with: python
has comment: http://stackoverflow.com/comment/90147051
has body: I am trying to parse a huge csv file (around 50 million rows) using Pandas 'read_csv' method. Below is the code snippet I am using: df_chunk = pd.read_csv(db_export_file, delimiter='~!#', engine='python', header=None, keep_default_na=False, na_values=[''], chunksize=10 ** 6, iterator=True) Therafter using the pd.concat method I am getting the whole set of dataframe which is used for further processing. Everything is working fine instead, the read operation from that csv file takes almost 6 mins to create the dataframe. My question is that, is there any other way to make this process faster using the same module and method? Below is the sample data presented as a csv file 155487~!#-64721487465~!#A1_NUM~!#1.000 155487~!#-45875722734~!#A32_ENG~!#This is a good facility 458448~!#-14588001153~!#T12_Timing~!#23-02-2015 14:50:30 458448~!#-10741214586~!#Q2_56!# Thanks in advance

http://stackoverflow.com/comment/90054874
has text: Whilst this may be possible, there is no simple way to do this with `raw_input2. In general, it is not great practise to use `raw_input` for anything other than learning. You say that you can't use command line options, but are you completely sure that is the case?
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51543478

http://stackoverflow.com/q/51510772
score: -1
type: Question
has comment: http://stackoverflow.com/comment/90000036
accepted answer: http://stackoverflow.com/a/51523414
answer count: 1
downvote count: 1
tagged with: filechooser
favorite count: 0
has answer: http://stackoverflow.com/a/51523414
tagged with: python
tagged with: kivy
upvote count: 0
tagged with: return
has body: I have two methods, get_image_one() opens a Tkinter filechoooser and returns an image which is displayed in a kv file. I want the selected image to be set as the source in method check_for_image() so that further processing can be done on the selected image by check_for_image() for example to check if the image selected by the user has any texts etc. The logic for this testing will be provided by check_for_image() Please let me know if this is the best way to go about this i.e having two separate methods, one for selecting the file, second for validating the file. Thank you for your time and attention. Below is my full example. main.py from kivy.app import App from kivy.uix.label import Label from kivy.uix.button import Button from kivy.core.window import Window from kivy.uix.popup import Popup from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty from tkinter.filedialog import askopenfilename from tkinter import Tk class SampBoxLayout(BoxLayout): def get_image_one(self): '''This method is called by button FileChooser, it opens a FileChooser selects the desired image''' Tk().withdraw() img1 = askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*"))) self.first_image.source = img1 def check_for_image(self): '''This method is called by button TextIdentifier 1. It needs to get the image selected by the above FileChooser 2. The selected Image can be analysed further Ex: to check the if the selected image contains any text etc. ''' pass class SampleApp(App): def build(self): # Set the background color for the window Window.clearcolor = (1, 1, 1, 1) return SampBoxLayout() sample_app = SampleApp() sample_app.run() sample.kv #:kivy 1.10.0 &lt;ColoredBackground@Image&gt;: font_size: '48sp' color: (.9, .5, .4, 1) canvas.before: Color: rgb: (.2, .9, .9) Rectangle: pos: self.x + sp(2), self.y + sp(2) size: self.width - sp(5), self.height - sp(4) &lt;SampBoxLayout&gt;: first_image: first_image #…
type: AnsweredQuestion
has title: How to display path of selected image as a variable in another method?
has comment: http://stackoverflow.com/comment/89990727

http://stackoverflow.com/comment/91218945
type: QuestionComment
has text: No. I want to pass another parameter of date and get the rate for a particular date
comment on: http://stackoverflow.com/q/51571091
score: 0
type: Comment

http://stackoverflow.com/comment/99057174
has text: This is a common scenario, isn't it? I was expecting this question to flood with answers. Amused to see only two.
comment on: http://stackoverflow.com/q/51505295
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91040970
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51557885
has text: The signals are periodical and may be slightly out of phase.

http://stackoverflow.com/a/51567097
has comment: http://stackoverflow.com/comment/90147226
has body: So, there's two solutions for your problem, though potentially only one feasible one: 1. Use ndimage.map_coordinates Since interpolate.SmoothBivariateSpline.ev is vectorised, in your final expression you are almost already done: from scipy import ndimage as ndi xx, yy = np.meshgrid(np.arange(8000), np.arange(6000)) coords_in_input = apply_spline((xx, yy)) img2_data_splined = ndi.map_coordinates(img2_data, coords_in_input) (Note: you may need to do some transposing depending on your coordinate conventions.) 2. Use a LowLevelCallable One reason that geometric_transform is taking a while is that calling functions in Python is slow. Pauli Virtanen created the LowLevelCallable interface in SciPy to ensure that C/Cython/Numba functions can be called without the Python overhead. If you can express your mapping function in C or Numba code, you can get big speedups. The geometric_transform docs tell you the required function signature. Here's a simple example (credit: Kira Evans) for a simple 2D shift: In Cython: #cython: boundscheck=False #cython: wraparound=False #cython: cdivision=True #cython: nonecheck=False #cython: initializedcheck=False #cython: binding=False #cython: infer_types=False import numpy as np cimport numpy as cnp from libc.stdint cimport intptr_t cdef api int shift(intptr_t* output_coords, double* input_coords, int output_rank, int input_rank, void* user_data): cdef: Py_ssize_t i for i in range(output_rank): input_coords[i] = &lt;double&gt; output_coords[i] - (&lt;double*&gt; user_data)[0] return 1 Then, assuming you've imported the Cython module as mapping, in Python: # Don't declare the user_data array inline because # .ctypes.get_as_parameter # does not keep reference to the array shift_amount = np.array([42], dtype=np.double) shift_cy = LowLevelCallable.from_cython(mapping, name='shift', user_data=shift_amount.ctypes.get_as_parameter()) Now you can do: shifted = ndi.geometric_transform(image, shift_cy) with decent performance. You can also use Numba f…
accepted answer of: http://stackoverflow.com/q/51563175
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/51563175

http://stackoverflow.com/a/51632324
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
has body: Calling np.concatenate() repeatedly is an anti-pattern. Instead, try this: np.concatenate(all_data) Simple, fast.
accepted answer of: http://stackoverflow.com/q/51632184
answers question: http://stackoverflow.com/q/51632184
type: Answer

http://stackoverflow.com/comment/90060081
type: QuestionComment
has text: If I remember correctly, the issue turned up after adding `dialogflow` to the package list.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51512519

http://stackoverflow.com/comment/90102006
comment on: http://stackoverflow.com/a/51567713
has text: why does it create an alias? i thought i was defining a variable with `a=var()`
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51567162
has body: It's not working because you try to sum string like this '10,20,,30' or this '10,20,5,20' My solution: import re regex = re.compile(r',,|,') with open(file, 'r') as f: for line in f: s = 0 for x in regex.split(line): s += int(x) print(s)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51567009

http://stackoverflow.com/a/51485453
has comment: http://stackoverflow.com/comment/89940023
has comment: http://stackoverflow.com/comment/89940147
has comment: http://stackoverflow.com/comment/89939987
has comment: http://stackoverflow.com/comment/89975582
answers question: http://stackoverflow.com/q/51485285
has comment: http://stackoverflow.com/comment/89939978
score: 0
has comment: http://stackoverflow.com/comment/89940194
has comment: http://stackoverflow.com/comment/89940216
has body: Unfortunately it's pretty difficult to listen for keypresses unless you expect one for every iteration of your loop, which for what you're doing is impractical. I think Joel has it right in the comments, you should be using Ctrl+C and catching the KeyboardInterrupt like this from PIL import ImageGrab import numpy as np import cv2 import ctypes user32 = ctypes.windll.user32 screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1) def record_screen(): fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('ResultFile.avi', fourcc, 25.0, screensize) while True: try: img = ImageGrab.grab() img_np = np.array(img) frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB) out.write(frame) print('recording....') except KeyboardInterrupt: break out.release() cv2.destroyAllWindows() record_screen() This way, the KeyboardInterrupt won't terminate the program, it'll just end the while loop, allowing you to release your writer and cleanup the rest of the cv2 resources. Because you're using PyCharm as your IDE, Ctrl+C might not work for you - try Ctrl+F2 instead.
type: Answer

http://stackoverflow.com/q/51560331
has title: How to run Keras models with AVX2 support
has comment: http://stackoverflow.com/comment/90109053
tagged with: python
has comment: http://stackoverflow.com/comment/90144248
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: tensorflow
has body: I need to measure execution time for prediction per image by running models such as mobilenet2 and densnet121. First, I just run my python code with stock tensorflow. start = time.time() out = m.predict(val) end = time.time() print("model: densenet") print ("time: ", (end - start)/batch_size) where batch_size used to avoid prediction overhead time. I've gotten followed output: Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 model: mobilenet2 time: 0.24023537635803222 model: densenet time: 1.045912742614746 Then I download tensorflow-build wheel and install wheel using python -m pip Current message: # AVX2 message does not appear anymore model: mobilenet2 time: 0.16217999935150146 model: densenet time: 0.6216100001335144 Is there a "right" way to do this, because it looks like avx2 doesn't accelerate prediction so much?
has comment: http://stackoverflow.com/comment/90105963
type: Question
tagged with: avx2
downvote count: 0
has comment: http://stackoverflow.com/comment/90100051
tagged with: keras
favorite count: 0

http://stackoverflow.com/comment/90499005
has text: You say updated and added so I don't know if your dataset grows or changes. But if you're adding new data then keep only the knots from the old spline and combine with the new data. Weight the old knots heavily so that it has a significant influence on the next set of knots. Weights would have to adjusted to see how much you want the new data to affect the old data.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51492451

tolist
type: Tag
tag name: tolist
tags question: http://stackoverflow.com/q/51529545

http://stackoverflow.com/comment/89965078
type: Comment
comment on: http://stackoverflow.com/a/51494970
type: AnswerComment
has text: @FilippoSebastio - i think it is data dependent issue, in `open` are values `1.07, 1.09, 1.14`. Why it is not idea, maybe `arnc` and `dan` are same company maybe?
score: 0

http://stackoverflow.com/q/51606818
has body: I have this source image below (after cropped) and I try to do some image processing before I read text. With python and opencv, I tried to remove the lines in the background with k-means with k =2, and the result is I tried to smooth the image using this code below def process_image_for_ocr(file_path): # TODO : Implement using opencv temp_filename = set_image_dpi(file_path) im_new = remove_noise_and_smooth(temp_filename) return im_new def set_image_dpi(file_path): im = Image.open(file_path) length_x, width_y = im.size factor = max(1, int(IMAGE_SIZE / length_x)) size = factor * length_x, factor * width_y # size = (1800, 1800) im_resized = im.resize(size, Image.ANTIALIAS) temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') temp_filename = temp_file.name im_resized.save(temp_filename, dpi=(300, 300)) return temp_filename def image_smoothening(img): ret1, th1 = cv2.threshold(img, BINARY_THREHOLD, 255, cv2.THRESH_BINARY) ret2, th2 = cv2.threshold(th1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) blur = cv2.GaussianBlur(th2, (1, 1), 0) ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) return th3 def remove_noise_and_smooth(file_name): img = cv2.imread(file_name, 0) filtered = cv2.adaptiveThreshold(img.astype(np.uint8), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 41, 3) kernel = np.ones((1, 1), np.uint8) opening = cv2.morphologyEx(filtered, cv2.MORPH_OPEN, kernel) closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel) img = image_smoothening(img) or_image = cv2.bitwise_or(img, closing) return or_image And the result is Can you help me (any idea) to remove the lines on the background of the source image?
upvote count: 5
score: 4
has answer: http://stackoverflow.com/a/51609436
answer count: 1
has comment: http://stackoverflow.com/comment/100290679
favorite count: 0
tagged with: python
tagged with: text-recognition
accepted answer: http://stackoverflow.com/a/51609436
tagged with: opencv
type: AnsweredQuestion
has title: Filtering Image For Improving Text Recognition
tagged with: image-processing
downvote count: 1
linked to: http://stackoverflow.com/q/41362489
type: Question

http://stackoverflow.com/comment/90289755
score: 0
comment on: http://stackoverflow.com/a/51580712
type: Comment
has text: One way is to construct an appropriate header. See: https://orange-visual-programming.readthedocs.io/loading-your-data/index.html#three-row-header-format
type: AnswerComment

http://stackoverflow.com/comment/90206060
score: 0
type: Comment
type: QuestionComment
has text: Perhaps the pattern should change the last question mark to an asterisk. Maybe OP wants to check numbers into the millions. `r'\b\d+(?:,\d+)*\b'`
comment on: http://stackoverflow.com/q/51620195

http://stackoverflow.com/q/51560689
upvote count: 1
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 1
has title: Create categorical column based on string values
type: Question
has answer: http://stackoverflow.com/a/51560835
has comment: http://stackoverflow.com/comment/90088250
has comment: http://stackoverflow.com/comment/90088443
tagged with: pandas
downvote count: 0
answer count: 1
has body: I have kind of a simple problem, but I'm having trouble achieving what I want. I have a district column, with 32 different values for all districts in a city. I want to create a column "sector" that says which sector that district belongs to. I thought the obvious approach was through a dictionary and map, but couldn't make it work: sectores={'sector oriente':['Vitacura, Las Condes, Lo Barnechea', 'La Reina','Ñuñoa','Providencia'], 'sector suroriente':['Peñalolén','La Florida', 'Macul'], 'sector sur': ['La Granja','La Pintana','Lo Espejo','San Ramón','La Cisterna','El Bosque','Pedro Aguirre Cerda','San Joaquín','San Miguel'], 'sector surponiente':['Maipú','Estación Central','Cerrillos'], 'sector norponiente':['Cerro Navia','Lo Prado','Pudahuel','Quinta Normal','Renca'], 'sector norte':['Conchalí','Huechuraba','Independencia','Recoleta','Quilicura'], 'sector centro':['Santiago']} Noticed I needed to switch keys and values: sectores = dict((y,x) for x,y in sectores.items()) Then tried to map it: df['sectores']=df['district'].map(sectores) But I'm getting: TypeError: unhashable type: 'list' Is this the right approach? Should I try something else? Thanks in advance! Edit: This is what df['district'] looks like: district Maipú Quilicura Independencia Conchalí ...
favorite count: 0
accepted answer: http://stackoverflow.com/a/51560835

http://stackoverflow.com/q/51596270
type: UnansweredQuestion
tagged with: time
tagged with: python
has comment: http://stackoverflow.com/comment/90158588
has comment: http://stackoverflow.com/comment/90159142
has comment: http://stackoverflow.com/comment/90159253
has comment: http://stackoverflow.com/comment/90159262
has comment: http://stackoverflow.com/comment/90159306
has title: A clock with a microsecond timer
type: Question
has body: I'm trying to create a microsecond timer on python. The goal is to have a "tick" every microsecond. My current approach was: us = list() while len(us) &lt;= 1000: t = time.time()*1000000 if t.is_integer(): us.append(t) It shows that there are clear limitations in term of timing that I am not aware of. The 656 first values were 1532960518213592.0. The while loop executes in the "same" microsecond. Then the value jumps to 1532960518217613.0. The maximum resolution seems to be 4021 us. How can I overcome those limitations? EDIT: About this measurements. Chrome with a youtube video was running in the background. + Outlooks, Teams, Adobe and some other stuff. The CPU is an i5-5200U CPU @ 2.20 GHz (2 cores).
has comment: http://stackoverflow.com/comment/90159690
has comment: http://stackoverflow.com/comment/90158785
has comment: http://stackoverflow.com/comment/90159361
score: 0
has comment: http://stackoverflow.com/comment/90158464
has comment: http://stackoverflow.com/comment/90158672
has answer: http://stackoverflow.com/a/51596533
answer count: 1
has comment: http://stackoverflow.com/comment/90159877

http://stackoverflow.com/comment/90169771
score: 0
comment on: http://stackoverflow.com/q/51601761
has text: Also, where do you expect UID to come from?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90182933
score: 0
type: QuestionComment
type: Comment
has text: The `None` is due to `list.insert` being an in-place function. There are many duplicates e.g. [Insert an element at specific index in a list and return updated list](https://stackoverflow.com/questions/14895599/insert-an-element-at-specific-index-in-a-list-and-return-updated-list)
comment on: http://stackoverflow.com/q/51608549

http://stackoverflow.com/comment/89976795
type: QuestionComment
has text: yes, i found problem but i need your input. can you please print print(data) after line data.columns=[headerName]. give me output result. the problem seems to be column mapping with Product.
comment on: http://stackoverflow.com/q/51502263
score: 0
type: Comment

http://stackoverflow.com/comment/123062111
type: AnswerComment
has text: Thanks for saving my life :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51634460

http://stackoverflow.com/comment/90015665
score: 0
type: Comment
type: QuestionComment
has text: Nope. Same error.
comment on: http://stackoverflow.com/q/51522826

http://stackoverflow.com/comment/90131679
type: QuestionComment
comment on: http://stackoverflow.com/q/51583086
score: 0
has text: @AChampion. Ok that works. I'm still new to python, so if you don't mind could you explain why 'in' can recurse down 1d lists but not 2d lists. why is 'any()' unnecessary for 1d lists?
type: Comment

http://stackoverflow.com/comment/140158650
type: QuestionComment
comment on: http://stackoverflow.com/q/51623208
has text: If you run Ubuntu in mode Wayland, pynput will not work! https://stackoverflow.com/a/75496187/29588525 Ubuntu 24.04: In the login, click your user and before set your password, click the gear icon at the right-below corner of the screen and select "Ubuntu XOrg".
score: 0
type: Comment

http://stackoverflow.com/q/51541392
has answer: http://stackoverflow.com/a/51541484
has comment: http://stackoverflow.com/comment/90050549
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51541698
favorite count: 0
has body: I want to match similar articles from a django database based on tags which are stored in a list of dictionary like follows: myarticle = {'pk': 17, 'tags': [0, 1, 0, 1, 0]} allarticles = [{'pk': 1, 'tags': [0, 0, 0, 1, 0]}, {'pk': 2, 'tags': [0, 1, 0, 1, 0]}, {'pk': 3, 'tags': [1, 1, 0, 0, 0]}, {'pk': 4, 'tags': [1, 0, 1, 0, 1]}, {'pk': 5, 'tags': [0, 0, 0, 0, 1]}] What is the most convenient way to get a list back that ranks the number of matching tags based on the input myarticle. Expected result: result = [2, 1, 3, 5, 4]
has title: Find similar items in list of dictionaries based on values
type: Question
answer count: 2
tagged with: similarity
score: 5
tagged with: python
tagged with: dictionary
downvote count: 1
upvote count: 6
tagged with: list
tagged with: filtering

http://stackoverflow.com/a/51608339
has comment: http://stackoverflow.com/comment/90182396
has comment: http://stackoverflow.com/comment/90181850
has body: Use \t for separator by tab: chipo = pd.read_csv(url, delimiter='\t') print(chipo.head(10)) 0 1 1 Chips and Fresh Tomato Salsa 1 1 1 Izze 2 1 1 Nantucket Nectar 3 1 1 Chips and Tomatillo-Green Chili Salsa 4 2 2 Chicken Bowl 5 3 1 Chicken Bowl 6 3 1 Side of Chips 7 4 1 Steak Burrito 8 4 1 Steak Soft Tacos 9 5 1 Steak Burrito choice_description item_price 0 NaN $2.39 1 [Clementine] $3.39 2 [Apple] $3.39 3 NaN $2.39 4 [Tomatillo-Red Chili Salsa (Hot), [Black Beans... $16.98 5 [Fresh Tomato Salsa (Mild), [Rice, Cheese, Sou... $10.98 6 NaN $1.69 7 [Tomatillo Red Chili Salsa, [Fajita Vegetables... $11.75 8 [Tomatillo Green Chili Salsa, [Pinto Beans, Ch... $9.25 9 [Fresh Tomato Salsa, [Rice, Black Beans, Pinto... $9.25
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51608312

http://stackoverflow.com/a/51487062
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51487012
score: 1
upvote count: 2
has body: Simple list comprehension will work. Key to this is forcing jd to lower since otherwise it won't match correctly. [i for i in tech if i in jd.lower()] ['hadoop developer', 'sap workflow', 'sap hana']

http://stackoverflow.com/q/51608549
answer count: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/90182313
has body: I have a list: list1=[[2,3],[4,5],[6,7]] I want to add a single value "one" to all sublist in the list at index 2 final output should be: list2=[[2,3,"one"],[4,5,"one"],[6,7,"one"]] tried with: for list2 in list1: print list2.insert(2,"one") But its showing error as None.
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51608622
linked to: http://stackoverflow.com/q/14895599
has answer: http://stackoverflow.com/a/51608621
has answer: http://stackoverflow.com/a/51610019
has answer: http://stackoverflow.com/a/51608624
has answer: http://stackoverflow.com/a/51608647
has answer: http://stackoverflow.com/a/51608607
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51608611
accepted answer: http://stackoverflow.com/a/51608611
score: 1
linked to: http://stackoverflow.com/q/1516889
possible better answer: http://stackoverflow.com/a/51608622
has comment: http://stackoverflow.com/comment/90182023
has comment: http://stackoverflow.com/comment/90182933
has title: adding 1 constant value to all sub_list in list in python
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/90182642

http://stackoverflow.com/q/51517023
has body: I have the following dataframe column &gt;&gt;&gt; df2['Age] 1 25 2 35 3 48 y 4 34 yea 5 29 ... I just want to keep the number en replace the value in df2['Age] like that 1 25 2 35 3 48 4 34 5 29 ... My code doesn't work : df2.Age.replace('^.*','^[0-9]*[0-9]',regex=True,inplace=True) here's the result 1 ^[0-9]*[0-9] 2 ^[0-9]*[0-9] 3 ^[0-9]*[0-9] 4 ^[0-9]*[0-9] 5 ^[0-9]*[0-9] ... Thanks for any help in advance
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51517060
has answer: http://stackoverflow.com/a/51517060
linked to: http://stackoverflow.com/q/17336943
tagged with: dataframe
has answer: http://stackoverflow.com/a/51517114
score: -1
type: Question
answer count: 2
duplicate of: http://stackoverflow.com/q/17336943
favorite count: 0
accepted answer: http://stackoverflow.com/a/51517114
tagged with: regex
tagged with: python-3.x
downvote count: 2
has title: Python replace non digit character in a dataframe
upvote count: 1
tagged with: python

http://stackoverflow.com/q/51486615
answer count: 1
score: 0
tagged with: python
has title: Can I run other programs with Python?
has body: Let me be more specific. I want to create a series of audiofiles, each containing a range of frequencies. That is done most easily with Audacity, but it would take forever to do it manually since there are a lot of frequencies to deal with. So the question is: Can I make a script that will open Audacity, press all the required buttons within the program and fill in the necessary values, and then save the files? If that's also confusing, can I use Python to make a script that will move the cursor to a specific location, order it "to click" something?
tagged with: external
linked to: http://stackoverflow.com/q/1181464
has comment: http://stackoverflow.com/comment/89942598
type: UnansweredQuestion
tagged with: audacity
type: Question
has comment: http://stackoverflow.com/comment/89949692
has answer: http://stackoverflow.com/a/51486829

http://stackoverflow.com/comment/90067007
comment on: http://stackoverflow.com/a/51548927
score: 1
type: AnswerComment
type: Comment
has text: @Ben.T Great! I will do the same :)

http://stackoverflow.com/a/51529144
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Thanks for adding data and example output. First off I am pretty sure you cannot vectorize this as each calculation is dependent on the output of the previous one. So this is the best I was able to do. Your method came in around 0.116999 seconds on my machine This one came in around 0.0039999 seconds Not vectorized but it gets a good speed increase since it is faster to use a list for this and adding it back to the data frame at the end. def myfunc(pos_pre, signal): if signal == 0: # if the signal is negative # if the new col value above -0.2 is &gt; -1 then subtract 0.2 from that value pos = pos_pre - 0.02 if pos &lt; -1: # if the row above - 0.2 &lt; -1 set the value of current row to -1 pos = -1 elif signal == 1: # if the row above + 0.2 &lt; 1 then add 0.2 to the value of the current row pos = pos_pre + 0.02 if pos &gt; 1: # if the value above + 0.1 &gt; 1 set the current row to 1 pos = 1 return pos ''' set first position value because you aren't technically calculating it correctly in your method since there is no position minus 1... IE: it will always be 0.02''' new_pos = [0.02] # skip index zero since there is no position 0 minus 1 for i in range(1, len(df)): new_pos.append(myfunc(pos_pre=new_pos[i-1], signal=df['signal'].iloc[i])) df['position'] = new_pos Output: df.position 0 0.02 1 0.04 2 0.06 3 0.08 4 0.10 5 0.12 6 0.14 7 0.16 8 0.18
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51522976
answers question: http://stackoverflow.com/q/51522976

http://stackoverflow.com/comment/90240865
type: Comment
comment on: http://stackoverflow.com/a/51622468
has text: That's definitely where my bad assumption was. I'm now going back through a few other proof-of-concepts where I've had the same problem and this is solving so many head-scratchers! Thank you soooo much! I first hit this about a month ago, spun for a day, then tabled it. Tried a couple times to figure out the problem since then with no luck. Wish I could buy you a beer or something. You have saved me a LOT of time! Thank you, random smart internet person!
type: AnswerComment
score: 0

http://stackoverflow.com/q/51608066
answer count: 1
has title: (Python) number of list's element
linked to: http://stackoverflow.com/q/509211
favorite count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/509211
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/90181231
downvote count: 3
has body: print(circles) output [[[282 132 121] [712 380 121] [280 628 121] [138 380 122] [570 132 121] [568 628 120]]] I want to reach number of list's element = 6 print(len(circles)) # gives me "1"
has comment: http://stackoverflow.com/comment/90181271
type: Question
has comment: http://stackoverflow.com/comment/90181237
has answer: http://stackoverflow.com/a/51608154
upvote count: 0

http://stackoverflow.com/comment/90247818
comment on: http://stackoverflow.com/a/51626968
score: 0
type: AnswerComment
has text: Cheers Ben, appreciate the help.
type: Comment

http://stackoverflow.com/comment/90197102
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51615591
has text: The second method produces lovely result on my actual dataset, which has over 100k obs. Could you also suggest a way to exclude a variable from the frequency analysis?

http://stackoverflow.com/comment/90072212
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51552622
has text: Yes I am using ajax

http://stackoverflow.com/q/51487877
has answer: http://stackoverflow.com/a/51488365
favorite count: 0
tagged with: gnuplot
upvote count: 2
has title: Installing gnuplot on jupyter
tagged with: python
possible better answer: http://stackoverflow.com/a/66756599
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66756599
tagged with: anaconda
accepted answer: http://stackoverflow.com/a/51488365
has body: I want to plot my bar chart by gnuplot. But I have problem with installing. I am using jupyter anaconda and the following codes don't work for installing. !conda install gnuplot-py !pip install gnuplot-py !pip install gnuplot Do you have any idea?
type: Question
has comment: http://stackoverflow.com/comment/89944918
has comment: http://stackoverflow.com/comment/89944843
answer count: 2
has comment: http://stackoverflow.com/comment/89945008
downvote count: 0
has comment: http://stackoverflow.com/comment/89945346
tagged with: jupyter

http://stackoverflow.com/comment/90115027
type: Comment
comment on: http://stackoverflow.com/q/51573324
type: QuestionComment
has text: I commented the above code to validate that it is causing the issues. The program doesn't crash when I omit it.
score: 0

http://stackoverflow.com/q/51554931
has comment: http://stackoverflow.com/comment/90076864
accepted answer: http://stackoverflow.com/a/51555704
has comment: http://stackoverflow.com/comment/90076915
upvote count: 1
tagged with: loops
downvote count: 1
type: Question
tagged with: controls
score: 0
has body: Consider the code for i in range(1,3): print(i) for j in range(4,7): print(j) for k in range(8,10): print(k) continue the expected output is [1 4 8 9] and [2 5 8 9] for each iteration and actual is [1 4 8 9 ],[5 8 9],[6 8 9],[2 4 8 9],[5 8 9],[6 8 9]
answer count: 1
has comment: http://stackoverflow.com/comment/90077759
favorite count: 0
has title: Transfer control to outermost loop python for each iteration
has answer: http://stackoverflow.com/a/51555704
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90064496
score: 0
type: Comment
type: QuestionComment
has text: @OllinBoerBohan I think you are correct. I have tried a couple times and it seems I'm not skilled enough to make it actually work... I see the example there, so I will muddle through that for a time.
comment on: http://stackoverflow.com/q/51548206

ros
tags question: http://stackoverflow.com/q/51599229
type: Tag
tags question: http://stackoverflow.com/q/51542285
tag name: ros
tags question: http://stackoverflow.com/q/51593993
tags question: http://stackoverflow.com/q/51561527

http://stackoverflow.com/comment/90099116
score: 1
has text: I don't really understand the question, so I will just reiterate: everything returned by `modify_doc` must be a brand-new Bokeh model, and must not contain anything ever returned by a previous call.
type: AnswerComment
comment on: http://stackoverflow.com/a/51564139
type: Comment

http://stackoverflow.com/q/51639332
type: AnsweredQuestion
score: 81
has body: I was asked recently what this means in Python: &gt;&gt;&gt; char : str I had no idea. I checked the docs and there isn't anything like that. One suggestion was that it is static type declaration, but there is absolutely nothing in the docs about that either. With the above, if I &gt;&gt;&gt; type(char) it fails If I &gt;&gt;&gt; char : str = 'abc' it works, and the results of type(char) is &lt;class: str&gt;. It can't be static declaration though, because I can &gt;&gt;&gt; char : str = 4 and type(char) becomes &lt;class: int&gt;. What does that mean?
has title: Use of colon in variable declaration
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51639358
upvote count: 81
tagged with: python
linked to: http://stackoverflow.com/q/32557920
duplicate of: http://stackoverflow.com/q/39971929
duplicate of: http://stackoverflow.com/q/32557920
accepted answer: http://stackoverflow.com/a/51639358
type: Question

http://stackoverflow.com/q/51536708
has answer: http://stackoverflow.com/a/75031170
upvote count: 6
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/75189275
favorite count: 0
tagged with: python-3.x
has body: I am facing problem with my malfunction csv input file whole reading and which i can deal with by adding "error_bad_lines=False" in my read_csv func to remove those. But i need to report these many files which is creating the problem, I assumed that i need to catch that exception. And i tried it via using except pd.parser.CParserError and except ExceptionSubclass as exceptionsubclass: After searching over Internet, in both the cases i am not able to catch this exception, if you have any idea how to report all the malfunction file please let me know. Error i am getting : Traceback (most recent call last): File "main.py", line 134, in reading_csv df = pd.read_csv(absolute_path_of_file, sep=',', dtype=str, keep_default_na=False) data = self._reader.read(nrows) File "pandas/_libs/parsers.pyx", line 890, in pandas._libs.parsers.TextReader.read (pandas/_libs/parsers.c:10862) File "pandas/_libs/parsers.pyx", line 912, in pandas._libs.parsers.TextReader._read_low_memory (pandas/_libs/parsers.c:11138) File "pandas/_libs/parsers.pyx", line 966, in pandas._libs.parsers.TextReader._read_rows (pandas/_libs/parsers.c:11884) File "pandas/_libs/parsers.pyx", line 953, in pandas._libs.parsers.TextReader._tokenize_rows (pandas/_libs/parsers.c:11755) File "pandas/_libs/parsers.pyx", line 2184, in pandas._libs.parsers.raise_parser_error (pandas/_libs/parsers.c:28765) pandas.errors.ParserError: Error tokenizing data. C error: Expected 7 fields in line 22, saw 8
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51538109
score: 6
tagged with: python
has title: Python catch exception "pandas.errors.ParserError: Error tokenizing data. C error"
downvote count: 0
type: Question

http://stackoverflow.com/comment/90160334
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51597072
has text: I'm sorry, but we can't really reason about your code without knowing what state it's in as it enters the code you've provided.

http://stackoverflow.com/a/55554462
type: Answer
has body: The file name under https://pypi.org/project/malmo/#files for macos is: malmo-0.36.0.0-cp37-cp37m-macosx_10_13_x86_64.whl The cp37 suggest you need python 3.7 The 10_13 suggest you need MacOSX 10.13.3 (High Sierra) or higher. From your post it looks like your on 10.12 Also see: https://github.com/Microsoft/malmo/blob/master/doc/install_macosx.md which states: Installing dependencies for MacOSX Install Homebrew: http://www.howtogeek.com/211541/homebrew-for-os-x-easily-installs-desktop-apps-and-terminal-utilities/ Install dependencies: brew install python3 brew install ffmpeg boost-python3 brew cask install java8 If you are installing from source (and not using "pip3 install malmo"), unzip the Malmo zip to some location (e.g. your home folder as assumed in the next step). Add export MALMO_XSD_PATH=~/MalmoPlatform/Schemas (or your Schemas location) to your ~/.bashrc and do source ~/.bashrc When you update Malmo you will need to update the MALMO_XSD_PATH too. Notes: These instructions were tested on MacOSX 10.13.3 (High Sierra). You may have better luck installing if you build from source.
score: 0
answers question: http://stackoverflow.com/q/51604181

http://stackoverflow.com/a/51546884
answers question: http://stackoverflow.com/q/51545930
has body: The issue doesn't have anything to do with the sqlalchemy module. When accesing attributes of object using variable references, use the getattr() base python function. qry = self.session.query(func.max(getattr(table,name)).label("max_date"), func.min(getattr(table,name)).label("min_date"),)
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51545930
score: 1
upvote count: 1

http://stackoverflow.com/a/51507918
downvote count: 0
answers question: http://stackoverflow.com/q/51507845
type: Answer
upvote count: 1
score: 1
has body: list_animals = ['dog', 'cat', 'cow', 'tiger', 'lion', 'snake', 'lion'] set_pets = set(['dog', 'cat']) list_animals = list(filter(lambda x: x not in set_pets, list_animals)) print(list_animals) Outputs ['cow', 'tiger', 'lion', 'snake', 'lion']

http://stackoverflow.com/q/51555643
tagged with: regex
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90078102
type: Question
has title: Append CSV with specific words (RegEx) from text files (path specific too) in python
score: 0
has body: # coding=utf-8 # Libreria RegEx de Python. import re # Libreria para rutas. import os import csv # function scan folder DiarioOficial def scan_folder(): # directory 'path' path = '/Users/.../DiarioOficial' # contador de ficheros del path count = 0 # variables declaration company_name = '' company_capital = '' # creation csv as csvFile with open('aaa.csv', 'a') as csvFile: # iterate all paths in the folder DiarioOficial without name for (path, dirnames, file_names) in os.walk(path): # iterate over all the files in the path (+ file_name) for file_name in file_names: # Add extension that is required if file_name.endswith(".txt"): # summatory count files in DiarioOficial folder count = count + 1 # concatenation path + file name file_path=os.path.join(path, file_name) #print(file_path) # open and read the file path mensaje = open(file_path).read() # Replace a newline for a space mensaje = mensaje.replace("\n","") # Company Name keywords_cap = ['SpA', 'SPA', 'LIMITADA', 'LTDA', 'S.A.', 'E.I.R.L.'] keywords_cap = map(re.escape, keywords_cap) keywords_cap.sort(key=len, reverse=True) obj = re.compile(r'[:,;.]\s*"?([^:,;.]*?(?&lt;!\w)(?:{}))'.format('|'.join(keywords_cap))) if obj: company_name = obj.search(mensaje) else: company_name = "None" # Social Capital ($) cap = r"\s*(CAPITAL:\s+([^-]*)|Capital social:\s+([^-]*)|Capital:\s+([^-]*))" caps = re.search(cap, mensaje) if caps: company_capital = caps.group() else: company_capital = 'None' print (count) csvData = [company_name, company_capital] writer = csv.writer(csvFile, delimiter='-') headers = ['COMPANY NAME', 'COMPANY CAPITAL'] writer.writerow(headers) # print the header row writer.writerow(csvData) # print the Data in csv scan_folder() I want to create a one csv with row for company that the information is in path /Users/.../DiarioOficial. This row includes a Company Name and Company capital. But Python: ERROR: Traceback (most recent call last): File "/Users/anna/PycharmProjects/extractData/post.py", line 61, in scan_f…
has comment: http://stackoverflow.com/comment/90126505
tagged with: http://stackoverflow.com/tag/csv
tagged with: path
tagged with: python

http://stackoverflow.com/q/51634854
has comment: http://stackoverflow.com/comment/90234800
type: Question
accepted answer: http://stackoverflow.com/a/51635665
linked to: http://stackoverflow.com/q/209513
has comment: http://stackoverflow.com/comment/90235661
score: 0
answer count: 3
has title: Compare two hex numbers
tagged with: string-comparison
tagged with: hex
has body: I have a function that I use to compare two strings character by character and do some additional tasks on it. I want to modify it to compare hex numbers instead. For example: If A = "hello", B = "himan" were to be compared. I used to run a for loop and compare character by character. It worked fine. for x, y in zip(A, B): if x == y: do something How do I modify it to consider hex numbers. For example, if A = "30303867" and B = "3f160303", I want to match 30 with 3f first then so on. Normally, I can only match 3 by 3 and so on. Thanks
has comment: http://stackoverflow.com/comment/90235879
has answer: http://stackoverflow.com/a/51635665
has answer: http://stackoverflow.com/a/51635003
tagged with: python
linked to: http://stackoverflow.com/q/1888114
has answer: http://stackoverflow.com/a/51635525
has comment: http://stackoverflow.com/comment/90236029
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51635003
has comment: http://stackoverflow.com/comment/90234016

http://stackoverflow.com/comment/90125819
type: Comment
has text: thank you very much for your answer. If I use tf.py_func, do I lose much efficiency?
comment on: http://stackoverflow.com/a/51580225
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90125734
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51578953
has text: @honar.cs, I think you should ask a separate question, showing what you expect to see what you are seeing (without images).

http://stackoverflow.com/a/51558138
upvote count: 1
has comment: http://stackoverflow.com/comment/90084090
type: Answer
accepted answer of: http://stackoverflow.com/q/51557796
downvote count: 0
has comment: http://stackoverflow.com/comment/90084320
has comment: http://stackoverflow.com/comment/90084152
has comment: http://stackoverflow.com/comment/90084216
has comment: http://stackoverflow.com/comment/90085470
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51557796
has body: Nope. The column from priority or cluster won't be misinterpreted as the third column of severity. Here's answer to how reference is kept: in pandas.get_dummies there is a parameter i.e. drop_first allows you whether to keep or remove the reference (whether to keep k or k-1 dummies out of k categorical levels). Please note drop_first = False meaning that the reference is not dropped and k dummies created out of k categorical levels! You set drop_first = True, then it will drop the reference column after encoding. Here's link to one hot encoding. As in your case severity has 3 categories S1, S2 and S3. After creating dummies one of these categories will always be 1 and others 0. for s1 it will be [1,0,0], s2 will be [0,1,0] and s3 will be [0,0,1] Now if you drop the column for category s1. The values will be [0,0] if severity is S1 [1,0] if severity is S2 [0,1] if severity is S3. So there is no information loss here and your model has one less column to deal with. That's why it is always recommended to keep drop_first parameter as True. Edit : After applying the dummies you will get columns like: severity_S1 severity_S2 severity_S3 1 0 0 # when value is S1 0 1 0 # when value is S2 0 0 1 # when value is S3 pandas.get_dummies() drops the 1st column after creating the above references. So in your data will be like below: severity_S2 severity_S3 0 0 # when value is S1 1 0 # when value is S2 0 1 # when value is S3 For all there variables your final data will look like below: I'm using short column names due to space issue: s2 s3 p2 p3 B C D 0 0 1 0 1 0 0 # For row with S1, P2 and B 0 1 0 1 0 1 0 # For row with S3, P3 and C 1 0 0 0 0 0 1 # For row with S2, P1 and D 1 0 0 0 0 0 0 # For row with S2, P1 and A

http://stackoverflow.com/a/51495984
type: AcceptedAnswer
score: 1
has body: I think need rank with DataFrame.gt for &gt;: df = df.rank(ascending=True).gt(2) print(df) c1 c2 c3 0 False False False 1 False False True 2 True True False Detail: print(df.rank(ascending=True)) c1 c2 c3 0 1.0 1.0 2.0 1 2.0 2.0 3.0 2 3.0 3.0 1.0 EDIT: For rank per rows add axis=1: print(df.rank(ascending=True, axis=1)) c1 c2 c3 0 1.0 3.0 2.0 1 1.0 2.0 3.0 2 2.0 3.0 1.0 df1 = df.rank(ascending=True, axis=1).gt(2) print(df1) c1 c2 c3 0 False True False 1 False False True 2 False True False
has comment: http://stackoverflow.com/comment/89960908
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/89961345
has comment: http://stackoverflow.com/comment/89961249
has comment: http://stackoverflow.com/comment/89961935
downvote count: 0
answers question: http://stackoverflow.com/q/51495961
has comment: http://stackoverflow.com/comment/89960824
accepted answer of: http://stackoverflow.com/q/51495961
has comment: http://stackoverflow.com/comment/89961328

http://stackoverflow.com/q/51496924
has comment: http://stackoverflow.com/comment/89968132
has comment: http://stackoverflow.com/comment/89961668
has comment: http://stackoverflow.com/comment/89965773
score: 4
has comment: http://stackoverflow.com/comment/89972636
has comment: http://stackoverflow.com/comment/89970925
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51501842
has comment: http://stackoverflow.com/comment/89965190
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89965392
has body: I have two pandas.Series objects, say a and b, having the same index, and when performing the difference a - b I get the error ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() which I don't understand where is coming from. The Series a is obtained as a slice of a DataFrame whose index is a MultiIndex, and when I do a renaming a.name = 0 the operation works fine (but if I rename to a tuple I get the same error). Unfortunately, I am not able to reproduce a minimal example of the phenomenon (the difference of ad-hoc Series with name a tuple seems to work fine). Any ideas on why this is happening? If relevant, pandas version is 0.22.0 EDIT The full traceback of the error: ---------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-15-e4efbf202d3c&gt; in &lt;module&gt;() ----&gt; 1 one - two ~/venv/lib/python3.4/site-packages/pandas/core/ops.py in wrapper(left, right, name, na_op) 727 728 if isinstance(rvalues, ABCSeries): --&gt; 729 name = _maybe_match_name(left, rvalues) 730 lvalues = getattr(lvalues, 'values', lvalues) 731 rvalues = getattr(rvalues, 'values', rvalues) ~/venv/lib/python3.4/site-packages/pandas/core/common.py in _maybe_match_name(a, b) 137 b_has = hasattr(b, 'name') 138 if a_has and b_has: --&gt; 139 if a.name == b.name: 140 return a.name 141 else: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() EDIT 2 Some more details on how a and b are obtained: I have a DataFrame df whose index is a multyindex (year, id_) I have a Series factors whose index are the columns of df (something like the standard deviation of the columns) Then: tmp = df.loc[(year, id_)] a = tmp[factors != 0] b = factors[factors != 0] diff = a - b and executing the last line the error happens. EDIT 3 And it keeps happening also if I reduce the columns: the original df has around 1000 rows and columns, but re…
has title: Role of name of pandas.Series while doing difference
has comment: http://stackoverflow.com/comment/89965180
has answer: http://stackoverflow.com/a/51501842
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/89972795
has comment: http://stackoverflow.com/comment/89963111
has comment: http://stackoverflow.com/comment/89972703
has comment: http://stackoverflow.com/comment/89965968
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89965448
downvote count: 0
has comment: http://stackoverflow.com/comment/89964023
type: Question
has comment: http://stackoverflow.com/comment/89969073

http://stackoverflow.com/q/51574350
tagged with: aerospike
score: 3
has title: Clarifications related to getting the total number of records in an aerospike set? Is Lua scripting needed?
tagged with: python
tagged with: lua
favorite count: 0
accepted answer: http://stackoverflow.com/a/51582153
type: AnsweredQuestion
upvote count: 3
type: Question
has body: I would like to get the total number of records in an aerospike set via python. I guese, it is the value that is shown against n_objects against a set in the output of show sets - aql&gt; show sets +-----------+------------------+----------------+-------------------+----------------+---------------------+--------------------------------------------+------------+ | n_objects | disable-eviction | set-enable-xdr | stop-writes-count | n-bytes-memory | ns_name | set_name | set-delete | + | 179 | "true" | "use-default" | 0 | 0 | "namespace" | "setName" | "false" | From what I read from this, it seems it is only possible via lua scripting - https://discuss.aerospike.com/t/fastest-way-to-count-records-returned-by-a-query/2379/4 Can someone confirm the same? I am however able to find the count by using a counter variable by iterating over the result of select() and it is matching against the above count - client = aerospike.client(config).connect() scan = client.scan('namespace', 'set') scan.select('PK','expiresIn','clientId','scopes','roles') scan.foreach(process_result) print "Total aeroCount" print aeroCount def process_result((key, metadata, record)): global aeroCount aeroCount=aeroCount+1 Update I tried running command asinfo -v sets on command line first. It gave me the objects count as well, like this - ns=namespace:set=setName:objects=29949:. Not sure how exactly to get the objects count against a set from this. Does this command qualify as a command for the python function? I tried this - client = aerospike.client(config).connect() response = client.info_all("asinfo -v sets") Here is an error I am getting - File "Sandeepan-oauth_token_cache_complete_sanity_cp.py", line 89, in &lt;module&gt; response = client.info_all("asinfo -v sets") AttributeError: 'aerospike.Client' object has no attribute 'info_all'
has answer: http://stackoverflow.com/a/51582153
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90130465

eval
tags question: http://stackoverflow.com/q/51545986
tags question: http://stackoverflow.com/q/51518894
tags question: http://stackoverflow.com/q/51618235
type: Tag
tags question: http://stackoverflow.com/q/51550899
tag name: eval

http://stackoverflow.com/q/51586364
tagged with: tensor
tagged with: python
type: AnsweredQuestion
has title: tf.boolean_mask(2D, 2D) gives 1D result
downvote count: 0
score: 1
tagged with: mask
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51586462
has body: The Issue tf.boolean_mask() seems relatively simple: it removes values from a Tensor that don't match a condition. If the dimensions of the mask are the same as the target tensor, the condition works element-wise. With ret = tf.boolean_mask(src, mask), I find that the output dimensions do not match the input dimensions. src: Tensor("mul_3:0", shape=(?,?), dtype=int32) mask: Tensor("Cast_1:0", shape=(?,?), dtype=int32) ret: Tensor("boolean_mask/Gather:0", shape=(?,), dtype=int32) Note that (?,) acts differently than (?,?), although I'm not sure why or how. Code src = [1, 2, 3, 4, 5, 6, 7, 8, 9] src = tf.ones([tf.shape(src)[0], 1], tf.int32) * src matrix = tf.ones_like(src, tf.int32) matrix = tf.matrix_band_part(matrix, 3, 3) # number for mask is arbitrary mask = tf.cast(matrix, tf.bool) ret = tf.boolean_mask(tensor=src, mask=mask) What's the problem?
has answer: http://stackoverflow.com/a/51586462
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/51621632
has comment: http://stackoverflow.com/comment/90209571
has comment: http://stackoverflow.com/comment/90209346
score: 2
answers question: http://stackoverflow.com/q/51621578
has comment: http://stackoverflow.com/comment/90209456
has body: import pandas as pd df = pd.read_csv("&lt;path to file&gt;.csv").reset_index() # update headers df.columns = df.iloc[0] df = df.iloc[1:].set_index("ID_REF") df.loc["Final"] = ((df.notnull()) &amp; (df != 0)).sum()
downvote count: 0
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/90209213

http://stackoverflow.com/q/51511002
type: UnansweredQuestion
upvote count: 1
has title: Python Theano tensor @as_op - use a dictionary as itypes?
tagged with: theano
has body: I'm doing Bayesian analysis using PyMC3 package and use Theano. If I wanted to use two parameters, I was able to do, @as_op(itypes=[theano.tensor.dscalar, theano.tensor.dscalar], otypes=[theano.tensor.dvector]) Now my input is a dictionary containing the names and values. What should be my itypes. Please help.
score: 1
type: Question
downvote count: 0
favorite count: 0
tagged with: python
answer count: 0

http://stackoverflow.com/comment/90188433
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51610133
has text: oh ok :) It didn't show me the error. it was giving me null so I passed columns instead of strings and it workd
score: 0

http://stackoverflow.com/q/51500904
has answer: http://stackoverflow.com/a/51501167
has answer: http://stackoverflow.com/a/51500930
answer count: 3
upvote count: 1
linked to: http://stackoverflow.com/q/319426
possible better answer: http://stackoverflow.com/a/51501143
has answer: http://stackoverflow.com/a/51501143
downvote count: 0
has body: If you have a Pandas dataframe like this, filtering this way works: df = pd.DataFrame({'name1': ['apple','pear','applepie','APPLE'], 'name2': ['APPLE','PEAR','apple','APPLE'] }) df[df['name1'] != df['name2']] # works But how do you filter rows, when you want to compare the upper values of the columns? df[df['name1'].upper() != df['name2'].upper()] # does not work
has title: How to filter a Pandas dataframe in python based on column value comparison?
accepted answer: http://stackoverflow.com/a/51500930
tagged with: pandas
type: AnsweredQuestion
score: 1
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/q/51562600
tagged with: escaping
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90092050
has comment: http://stackoverflow.com/comment/131720378
downvote count: 3
duplicate of: http://stackoverflow.com/q/11283961
score: -1
has comment: http://stackoverflow.com/comment/90092098
has comment: http://stackoverflow.com/comment/90092142
type: Question
has answer: http://stackoverflow.com/a/51564593
possible better answer: http://stackoverflow.com/a/51563095
linked to: http://stackoverflow.com/q/5466451
favorite count: 0
has answer: http://stackoverflow.com/a/51563095
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90092229
linked to: http://stackoverflow.com/q/11283961
answer count: 3
has comment: http://stackoverflow.com/comment/90092156
has answer: http://stackoverflow.com/a/51623363
has comment: http://stackoverflow.com/comment/90092066
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/90093179
has comment: http://stackoverflow.com/comment/90092060
has body: Related: https://stackoverflow.com/a/18343661 https://stackoverflow.com/a/5466478 You use curly braces ( {•••} ) to denote parts of strings to be formatted. If you want to use literal curly brace characters so that they're ignored by .format(), you use double curly braces ( {{•••}} ). MCVE: string = "{format} {{This part won't be formatted. The final string will have literal curly braces here.}}" print string.format(format='string') If you have a chain of .format()s, you double the number of braces for each time you use .format(). The last one is surrounded by 4 braces and ends up with literal curly braces in the final output. MCVE: string = "{format1} {{format2}} {{{{3rd one won't be formatted. The final string will have literal curly braces here.}}}}" print string.format(format1='string1').format(format2='string2') It's also possible to format another format string into a format string. The last one is surrounded by 4 braces and ends up with literal curly braces in the final output. MCVE: string = "{format1} {{{{3rd one won't be formatted. The final string will have literal curly braces here.}}}}" print string.format(format1='{format2}').format(format2='string') The problem arises when you use a chain of .format()s depending on conditions determined at runtime. If you want a set of the curly braces to be escaped as literal characters, how many do you use? MCVE: string = "{} {{{{{{Here I don't know exactly how many curly braces to use because this string is formatted differently due to conditions that I have no control over.}}}}}}" if fooCondition: string = string.format('{} bar') if barCondition: string = string.format('{} baz') if bazCondition: string = string.format('{} buzz') string = string.format('foo') print string The 1st part of the string has 4 possible outputs: foo foo bar foo baz bar foo buzz baz bar The 2nd part of the string ends up with a different number of curly braces depending on how many conditions are True. I want the 2nd part's curly braces to…
has title: Escaping curly braces in string to be formatted an undefined number of times
accepted answer: http://stackoverflow.com/a/51564593
upvote count: 2
tagged with: string-formatting
has comment: http://stackoverflow.com/comment/90092153
tagged with: python
has comment: http://stackoverflow.com/comment/90093031

http://stackoverflow.com/comment/89972632
comment on: http://stackoverflow.com/a/51502111
type: AnswerComment
type: Comment
score: 3
has text: I agree that this is a problem, but I don't think it's causing the problem described. `report.upper() in "A T":` evaluates to True if `report` is "A".

http://stackoverflow.com/comment/90075498
has text: I edited the code once more now it only outputs one line
comment on: http://stackoverflow.com/a/51553555
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90196508
comment on: http://stackoverflow.com/a/51613593
has text: @rammohandubey: this is _definitely_ the problem.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51578561
type: Answer
score: 2
has body: repeat the following steps and let me know load_data = pd.read_csv('data.txt',sep = ",",header = None) feature_vale = load_data[0] y = np.matrix(load_data[1]) m = len(feature_vale) #print(m) #plt.scatter(load_data[0],load_data[1]) df = pd.DataFrame(pd.Series(1,index= range(0,m))) df[1] = load_data[0] X = np.matrix(df) row_theta = np.zeros(2,dtype = int) theta = np.array([row_theta]) # Transpose the array print(theta.T) prediction = np.matmul(X,theta.T) error = (prediction-y) error_df = pd.DataFrame(error) squared_error = np.square(error_df) print(squared_error)
accepted answer of: http://stackoverflow.com/q/51578328
has comment: http://stackoverflow.com/comment/90126287
has comment: http://stackoverflow.com/comment/90127046
has comment: http://stackoverflow.com/comment/90126827
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90122897
answers question: http://stackoverflow.com/q/51578328
has comment: http://stackoverflow.com/comment/90122603
upvote count: 2

http://stackoverflow.com/comment/90124311
has text: I am not dependant on JSON format. Can you provide a code example?
score: 0
comment on: http://stackoverflow.com/q/51579478
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51564755
type: Question
tagged with: python
has body: I really don't get why Python is so difficult to get up and running properly. Anyway, I've just fresh installed Python 3.7 and PyCharm. I want to get the Python Imaging Library working within my project, but when I try to install it using PyCharm I get the following error: pip install PIL Non-zero exit code (1) Try to run this command from the system terminal. Make sure that you use the correct version of 'pip' installed for your Python interpreter located at 'C:\Users\Jake\AppData\Local\Programs\Python\Python37-32\python.exe'. Command output: Collecting PIL Could not find a version that satisfies the requirement PIL (from versions: ) No matching distribution found for PIL You are using pip version 10.0.1, however version 18.0 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. I've attempted to run python -m pip install --upgrade pip from a CMD prompt, but I then get this error: Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' I just tried to install NumPy using the exact same method for PIL and Numpy installed without any issues whatsoever. This leads me to think that maybe PIL isn't supported for Python 3.7? Can someone explain to me what the issue is here and help me with importing modules into my PyCharm project?
tagged with: pycharm
score: 0
answer count: 1
has title: Attempting to install Python PIL module fails with "Non-zero exit code"
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51564866

http://stackoverflow.com/a/51635984
has comment: http://stackoverflow.com/comment/90238371
score: 3
answers question: http://stackoverflow.com/q/51635734
has body: Concatenate all of the files into a single DataFrame and then use the wave value to group and calculate the mean. import os import pandas as pd path_to_files = 'something' lst = [] for filen in [x for x in os.listdir(path_to_files) if '.ares' in x]: lst.append(pd.read_table(path_to_files+filen, skiprows=0, usecols=(0,1,2,3,4,8), names=['wave','num','stlines','fwhm','EWs','MeasredWave'], delimiter=r'\s+')) df = pd.concat(lst, ignore_index=True) # Calculate the average based on the first column df.groupby('wave').mean() As per your comment, you can first sort the DataFrame, so that the highest value occurs first, and then drop duplicates, leaving you with only the row for the highest stlines value for each unique value of wave. Just change the loop to: for filen in [x for x in os.listdir(path_to_files) if '.ares' in x]: df1 = pd.read_table(path_to_files+filen, skiprows=0, usecols=(0,1,2,3,4,8), names=['wave','num','stlines','fwhm','EWs','MeasredWave'], delimiter=r'\s+')) df1 = df1.sort_values('stlines', ascending=False).drop_duplicates('wave') lst.append(df1)
has comment: http://stackoverflow.com/comment/90238743
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90238228
upvote count: 3

http://stackoverflow.com/comment/90022831
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51485910
has text: I decide to separate my problem in two parts. First create a loop where I would change my file in the path and then use the create list of all the paths to use my function. Do you think it's a good idea ?

http://stackoverflow.com/a/51496629
type: Answer
has comment: http://stackoverflow.com/comment/89961106
answers question: http://stackoverflow.com/q/51489500
score: -1
has body: The function get_web_json() should be modified to : def get_web_json(url): with urlopen(url) as rsq: dataform = rsq.read().decode().replace('\n','') return json.loads(dataform)
downvote count: 2
upvote count: 1

rpc
tag name: rpc
tags question: http://stackoverflow.com/q/51527846
type: Tag

http://stackoverflow.com/a/51524545
accepted answer of: http://stackoverflow.com/q/51520775
answers question: http://stackoverflow.com/q/51520775
has comment: http://stackoverflow.com/comment/90019736
has comment: http://stackoverflow.com/comment/90026161
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
has body: Here's one way using a nested dictionary mapping: from collections import defaultdict d = defaultdict(dict) for row in games_df.itertuples(index=False): d[row.week].update({row.winner: row.loser, row.loser: row.winner}) def_df['opponent'] = def_df.apply(lambda x: d[x['week']][x['team']], axis=1) print(def_df) team week opponent 0 GB 1 CHI 1 MIA 1 DET 2 CHI 1 GB 3 DET 1 MIA 4 GB 2 MIA 5 MIA 2 GB 6 CHI 2 DET 7 DET 2 CHI An equally valid alternative using tuple keys, which avoids collections: d = {} for row in games_df.itertuples(index=False): d[(row.week, row.winner)] = row.loser d[(row.week, row.loser)] = row.winner def_df['opponent'] = def_df.set_index(['week', 'team']).index.map(d.get)
score: 2
has comment: http://stackoverflow.com/comment/90019425

http://stackoverflow.com/comment/90018208
comment on: http://stackoverflow.com/q/51524514
type: Comment
type: QuestionComment
has text: @NickT get pretty standard output I think, a bunch of import statements (edited post to include). Unfortunately I don't have a choice on terminal emulator install.
score: 0

http://stackoverflow.com/comment/90218964
type: AnswerComment
comment on: http://stackoverflow.com/a/51626552
score: 0
has text: @uli28 No problem, [here](https://stackoverflow.com/help/someone-answers) is a useful page about accepting answers. All you need to do is press the grey checkmark on the answer.
type: Comment

http://stackoverflow.com/comment/90285897
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51659570
has text: Again, way too complicated -- just create a reference-set with one-degree increments instead. Or in general, make enough so that you don't care what the rounding error would be. If you REALLY want, just take the K nearest neighborS, and average over them (over the rotations that each one represents). Yeah you could try to weight them by distance, etc. etc ... hopefully, and I would expect, that's just not remotely necessary.
score: 0

http://stackoverflow.com/comment/90207816
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51621107
has text: 1) Please do not post terminal output in an image. See here for why: https://unix.meta.stackexchange.com/q/4086/40481 2) What about `conda install anaconda python=3`?
type: Comment

http://stackoverflow.com/q/51620390
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90210303
downvote count: 0
score: 1
tagged with: cgi
type: Question
answer count: 2
has body: I am trying to get a html page to take a text input and have a python script get it and print it out. I had this working correctly while I was on a trial period for a webhost, and after I upgraded to a full account, I transferred the files over and it stopped working. I might have missed a step in the setup, but I can't figure out where. Here is what I did: I set up a python virtualenv and then I activated it by going into SSH and typing in source /home/username/virtualenv/test/3.5/bin/activate and confirmed that it was activated. Then I tried to run my index.html file that is in my public_html folder: Test Enter Message: Everything displayed correctly. When I enter anything into the input box and click submit, it should execute my hello.py script that is in my cgi-bin folder: #!/home/username/virtualenv/test/3.5/bin/python import cgi data = cgi.FieldStorage() print ("Content-Type: text/html\n") print (data["message"].value) All that displays is the actual python code, instead of the input from the html. I tried it also with #!/usr/bin/python in the python script and it still displays just the python code.
has comment: http://stackoverflow.com/comment/90207760
upvote count: 1
tagged with: http://stackoverflow.com/tag/html
has title: .py python file displaying code instead of executing on webhost
has answer: http://stackoverflow.com/a/51624098
favorite count: 0
accepted answer: http://stackoverflow.com/a/51624098
possible better answer: http://stackoverflow.com/a/51640583
has answer: http://stackoverflow.com/a/51640583
tagged with: python

http://stackoverflow.com/q/51487549
tagged with: cluster-analysis
has title: Unsupervised learning clustering 1D array
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/51580352
has answer: http://stackoverflow.com/a/51580352
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/89944569
linked to: http://stackoverflow.com/q/35094454
favorite count: 0
has answer: http://stackoverflow.com/a/51488130
has comment: http://stackoverflow.com/comment/89944372
tagged with: python
type: AnsweredQuestion
tagged with: unsupervised-learning
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/111095695
has answer: http://stackoverflow.com/a/51488332
has body: I am faced with the following array: y = [1,2,4,7,9,5,4,7,9,56,57,54,60,200,297,275,243] What I would like to do is extract the cluster with the highest scores. That would be best_cluster = [200,297,275,243] I have checked quite a few questions on stack on this topic and most of them recommend using kmeans. Although a few others mention that kmeans might be an overkill for 1D arrays clustering. However kmeans is a supervised learnig algorithm, hence this means that I would have to pass in the number of centroids. As I need to generalize this problem to other arrays, I cannot pass the number of centroids for each one of them. Therefore I am looking at implementing some sort of unsupervised learning algorithm that would be able to figure out the clusters by itself and select the highest one. In array y I would see 3 clusters as so [1,2,4,7,9,5,4,7,9],[56,57,54,60],[200,297,275,243]. What algorithm would best fit my needs, considering computation cost and accuracy and how could I implement it for my problem?
type: Question
accepted answer: http://stackoverflow.com/a/51488130
has comment: http://stackoverflow.com/comment/89944300

http://stackoverflow.com/q/51588935
has comment: http://stackoverflow.com/comment/90146112
has body: I know that Python-interpreter converts a python-code into a python-bytecode, and can run the python-bytecode on PythonVM. So, I'm interested in how to assemble python-bytecode to objectcode(for processors, ex. intel x64) on PythonVM. Does use assembly like nasm in PythonVM ? I want to look at the code, doc, or reference about processing to map and convert python-bytecode to processor's instruction(set) code(follows: https://www.felixcloutier.com/x86/). Please tell me.
tagged with: python
has comment: http://stackoverflow.com/comment/90143824
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
upvote count: 1
score: 1
type: Question
has title: How to assemble Python-bytecode to objectcode(for processors) on PythonVM?
downvote count: 0

http://stackoverflow.com/comment/90380724
has text: I went ahead and added some more examples which show more context into the path taken after calling `__getitem__` and the cython function called, which ultimately is where most of the time is spent for large values. The logic in `__getitem__` is not always intuitive, but I found this GH issue to be helpful for explaining what different inputs do under the hood https://github.com/pandas-dev/pandas/issues/9595.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51700776
type: AnswerComment

http://stackoverflow.com/comment/90051625
has text: SyntaxError: 'return' outside function. That's the error I got when I used that code
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51541616
type: Comment

http://stackoverflow.com/a/51494696
answers question: http://stackoverflow.com/q/51494558
has comment: http://stackoverflow.com/comment/89959313
has body: Why not use pandas: import io import pandas as pd csv = """2014.03.12 23:59:59,2014.03.20 23:59:59,BRENTSPOT,Brent 1,1.29,1.6,0.8568833439015613,91.09,3.5,2.053,-0.035\n 2014.04.01 23:59:59,2014.04.02 23:59:59,BRENTSPOT,Brent 1,1.39,1.4,0.8568833439015613,89.59999999999999,3.5,2.053,-0.036\n""" print(pd.read_csv(io.StringIO(csv), header=None).values.tolist()) which yields [['2014.03.12 23:59:59', '2014.03.20 23:59:59', 'BRENTSPOT', 'Brent 1', 1.29, 1.6, 0.8568833439015613, 91.09, 3.5, 2.053, -0.035], ['2014.04.01 23:59:59', '2014.04.02 23:59:59', 'BRENTSPOT', 'Brent 1', 1.39, 1.4, 0.8568833439015613, 89.59999999999998, 3.5, 2.053, -0.036000000000000004]] If you want to use your file Brent 3.csv replace the call to io.StringIO with the path of the file.
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/89967827
downvote count: 0
score: 1

http://stackoverflow.com/comment/90010188
has text: OK, a query is fine then. Looks like you are setting Limit=1. This does NOT limit your result set to the first result. Limit means it will only evaluate the first item in the partition set. You probably need to remove that limit.
comment on: http://stackoverflow.com/q/51506863
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51543545
accepted answer: http://stackoverflow.com/a/51543641
favorite count: 0
has title: Dictionary help in Python3
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/90054908
has answer: http://stackoverflow.com/a/51543644
upvote count: 2
tagged with: dictionary
has answer: http://stackoverflow.com/a/51543641
type: AnsweredQuestion
type: Question
has body: I'm trying to print a formatted layout of a list. I've got the main part down but I can't seem to get the numbering right. Here's the code: shopping_list = {"eggs": "$2", "milk": "$3.50", "cereal": "$3"} my_shopping_list = "".join(**n**+". "+item+" "+shopping_list[item]+"\n" for item in shopping_list) print(my_shopping_list) Basically I want to print the items and price in the format: {number}. {item} {price}\n So the results should be: 1. eggs $2 2. milk $3.50 3. cereal $3 It should work if I add more items into the dictionary But I do not know what to replace n with: **n**+". "+item+" "+shopping_list[item]+"\n" for item in shopping_list I've tried using lists to do this shopping_list = [["eggs", "$2"], ["milk", "$3.50"], ["cereal", "$3"]] my_shopping_list = "".join(str(n+1)+". "+shopping_list[n][0]+" "+shopping_list[n][1]+"\n" for n in range(len(shopping_list))) print(my_shopping_list) And it works just fine but I need it to work for dictionary so do I find a way to index a dictionary like a list or is there a better way to do it? Thanks in advance!
score: 2
possible better answer: http://stackoverflow.com/a/51543620
downvote count: 0
has answer: http://stackoverflow.com/a/51543620
has comment: http://stackoverflow.com/comment/90054993

http://stackoverflow.com/comment/90823733
type: AnswerComment
comment on: http://stackoverflow.com/a/51832037
type: Comment
has text: Not sure I understand your question. Don't you already have the paths stored in your database?
score: 0

http://stackoverflow.com/comment/90078219
comment on: http://stackoverflow.com/a/51551044
score: 0
type: AnswerComment
has text: Thanks jezreal and RafaelC instead of indexing till 4 i was trying to index it to a specific character e.g: ind=df['x'].str.find("_") finds location of the character "_" and then apply df['y'] = df['x'].str[1:ind] What is the right way to do it
type: Comment

http://stackoverflow.com/comment/90200640
type: QuestionComment
comment on: http://stackoverflow.com/q/51617026
has text: Well the problem is that module. So you will either have to find a version that works or use something that doesn't depend on it. The PyPI entry for `web` makes it look like it is not supposed to be used for anything.
score: 0
type: Comment

http://stackoverflow.com/a/51622567
has body: On the create method of the serializer you are trying to create an Entity with the data fields of an Article: entities_relations = validated_data.pop('entities', None) entity_instance = Entity.objects.create(**validated_data) You didn't specify the line where the error occurs, but it seems to be here. I don't know the fields of the Entity model, but title seems to not be one of them.
answers question: http://stackoverflow.com/q/51622311
has comment: http://stackoverflow.com/comment/90211488
score: 0
accepted answer of: http://stackoverflow.com/q/51622311
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/53375405
type: Answer
downvote count: 1
score: 3
upvote count: 4
has comment: http://stackoverflow.com/comment/109212098
has comment: http://stackoverflow.com/comment/109208047
has comment: http://stackoverflow.com/comment/129599051
answers question: http://stackoverflow.com/q/51486081
has body: Do not use the conda install to install the rpy2, just use the pip install rpy2. Here are some additional packages you may need to install before the rpy2: conda install -y PyHamcrest sudo apt-get install -y libreadline6-dev pip install rpy2 Some notes: which pip should refer to anaconda's path. The environment variable for R (R_HOME and PATH) should be properly set up before you install the rpy2. After the installation, you may encounter an error when calling import rpy2.robjects as robjects: RRuntimeWarning: Error: package or namespace load failed for ‘stats’ in dyn.load(file, DLLpath = DLLpath, ...): unable to load shared object '/usr/local/lib/R/library/stats/libs/stats.so': libRlapack.so: cannot open shared object file: No such file or directory To solve this, I found a solution in How I solved the error - libRlapack.so: cannot open shared object file: No such file or directory You need to locate your libRlapack.so file (in my case this file is in /usr/local/lib/R/lib/), or the following command should show the path to this file: R CMD ldd /usr/local/lib/R/library/stats/libs/stats.so and then write this path to the /etc/ld.so.conf.d/libR.conf and then run ldconfig: echo &quot;/usr/local/lib/R/lib/&quot; &gt;&gt; /etc/ld.so.conf.d/libR.conf &amp;&amp; ldconfig That should fix the problem.

http://stackoverflow.com/comment/90142593
type: Comment
type: QuestionComment
has text: See for example here: https://stackoverflow.com/a/33439544/67579. Can you share the current approach for the API?
comment on: http://stackoverflow.com/q/51588705
score: 0

http://stackoverflow.com/comment/90152197
comment on: http://stackoverflow.com/a/51591689
score: 0
type: AnswerComment
has text: Great! it works for me.Thank you very much @ImportanceOfBeingErnest
type: Comment

http://stackoverflow.com/comment/89950779
type: Comment
type: QuestionComment
has text: You could package it as a Docker container, assuming you deploy it to a system that runs Docker
score: 1
comment on: http://stackoverflow.com/q/51487516

http://stackoverflow.com/a/51557627
has comment: http://stackoverflow.com/comment/90083365
has body: Given that the ORM force loads the queryset when deleting, cf: File "/root/virtualenvs/myproj-prod/lib/python3.6/site-packages/django/db/models/deletion.py", line 89, in add if not objs: the only workaround I can think of (that does not require forking or monkeypatching anything) would be to first update the whole queryset so the jsonfield is set to something valid, ie: qs.update(name_of_the_field={}) qs.delete() But this won't preven other issues with your data being inconsistent, so the real solution is obviously to clean up your whole dataset.
accepted answer of: http://stackoverflow.com/q/51555750
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51555750
has comment: http://stackoverflow.com/comment/90083530
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/90072617
score: 0
type: Comment
type: QuestionComment
has text: Flush works perfectly, thank you !
comment on: http://stackoverflow.com/q/51552583

http://stackoverflow.com/q/51513894
tagged with: python
type: UnansweredQuestion
tagged with: web-scraping
has answer: http://stackoverflow.com/a/51514373
has title: Extracting Text from Javascript or Ajax based webpages?
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51514959
has body: Is there a way to scrap the text from Javascript based sites example: https://www.ajio.com/ajio-mid-rise-slim-fit-cargo-pants/p/460151939_brown I need the product specifications from this page How can I do this?
score: 0

http://stackoverflow.com/a/51528828
has body: Your question isn't very clear, but this should work, if my understanding is not wrong: def string_length(mystring): try: if type(int(mystring)) == int: return "Sorry, integers don't have length" elif type(mystring) == str: return len(mystring) except: return len(str(mystring)) mystring = input("what is the value ?") print(string_length(mystring))
accepted answer of: http://stackoverflow.com/q/51527516
answers question: http://stackoverflow.com/q/51527516
has comment: http://stackoverflow.com/comment/90026145
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/51521255
answers question: http://stackoverflow.com/q/51520775
upvote count: 1
downvote count: 0
score: 1
has body: Updated Create a column of opponents opponent_list = [] for team, week in zip(def_df['team'],def_df['week']): for gameweek, winner, loser in zip(games_df['week'],games_df['winner'],games_df['loser']): if gameweek == week and (winner ==team or loser ==team): if winner == team: opponent_list.append(loser) else: opponent_list.append(winner) def_df['opponent'] = opponent_list
has comment: http://stackoverflow.com/comment/90015200
type: Answer

http://stackoverflow.com/a/51499804
has comment: http://stackoverflow.com/comment/89971228
type: Answer
answers question: http://stackoverflow.com/q/51499765
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/89968126
has body: Using Regex Lookbehind &amp; Lookahead Ex: import re s = """-----BEGIN CERTIFICATE----- [binary] -----END CERTIFICATE-----""" m = re.search(r"(?&lt;=-----BEGIN CERTIFICATE-----).*?(?=-----END CERTIFICATE-----)", s, flags=re.DOTALL) if m: print( m.group() ) Output: [binary]
downvote count: 0

http://stackoverflow.com/q/51526846
possible better answer: http://stackoverflow.com/a/51526960
tagged with: dataframe
upvote count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51526960
accepted answer: http://stackoverflow.com/a/51526927
duplicate of: http://stackoverflow.com/q/47152691
favorite count: 0
linked to: http://stackoverflow.com/q/47152691
tagged with: python
has answer: http://stackoverflow.com/a/51526927
type: AnsweredQuestion
score: 2
tagged with: join
downvote count: 0
tagged with: pivot
has title: Unpivot dataframe and join pandas
type: Question
has body: I have this dataframe: +-------+-----+---------+ | group | id | value | +-------+-----+---------+ | A | 92 | 123.123 | | A | 105 | 9034 | | A | 999 | 421 | | B | 92 | 32019 | | B | 105 | 3281 | +-------+-----+---------+ I'd like to pivot the 'group' column so that its values become part of the 'value' column name and the observations are joined by 'id' like this: +-----+---------+---------+ | id | A_value | B_value | +-----+---------+---------+ | 92 | 123.123 | 32019 | | 105 | 9034 | 3281 | | 999 | 421 | nan | +-----+---------+---------+ What's the best way to go about doing this?
answer count: 2

http://stackoverflow.com/comment/90048863
has text: You should read [Python's super() considered super!](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/), to see how using `super` beats explicit references to the parent class.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51540486

http://stackoverflow.com/q/51520673
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51521121
score: 0
tagged with: binaryfiles
has body: I have a sensor unit which generates data in large binary files. File sizes can run into several tens of Gigabytes. I need to: Read the data. Process it to extract the necessary information that I want. Display / Visualize the data. Data in the binary file is formatted as: Single precision float i.e. numpy.float32 I have written the code which is working well. I am now looking to optimize it for time. I observe that it is taking a very large time to read the binary data. The following is what I have right now : def get_data(n): ''' Function to get relevant trace data from the data file. Usage : get_data(n) where n is integer containing relevant trace number to be read Return : data_array : Python array containing single wavelength data. ''' with open(data_file, 'rb') as fid: data_array = list(np.fromfile(fid, np.float32)[n*no_of_points_per_trace:(no_of_points_per_trace*(n+1))]) return data_array This allows me to iterate the value for n and obtain different traces i.e. chunks of data. The variable no_of_points_per_trace contains the number of points in every trace as the name suggests. I am obtaining this from a separate .info file. Is there an optimal way to do this?
answer count: 1
has title: What is the fastest way to read a specific chunk of data from a large Binary file in Python
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/90010879
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51521121

http://stackoverflow.com/a/51595760
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90211819
score: 1
has body: From the error message I can guess that you are using Python2.7 on a Windows system. Windows is unicode friendly, but not really utf-8 friendly. So it is unlikely for your source csv file to be utf-8 encoded. In addition the error message is still a hint: 'utf8' codec can't decode byte 0xfe in position 0 Byte 0xfe can never exist in a utf-8 encoded file, neither as a start byte (below 0xf8) nor as a continuation byte (below 0xc0). But it is the windows-1254 code page encoding for 'ş'. So I assume that your input csv file uses a windows-1254 character set ('cp1254' in Python) On the other end, reportlab only accept utf8 encoded strings or true unicode strings. What can be done: decode all the strings just before feeding reportlab (and pass unicode strings): ... coding = 'cp1254' ... #info c.drawCentredString(150,100,barcode_name.decode(coding)) #info c.drawCentredString(150,150, barcode_stf.decode(coding)) #barkod numarasi c.drawCentredString(100,40,barcode_number.decode(coding)) #down info (this one should already be utf8 encoded thanks to # -*- coding: utf-8 -*- c.drawCentredString(150,15,"1 adet ürün içerir. Contains 1 Piece. LOT:",) use the codecs module to re-encode the file at reading time (and pass utf8 encoded strings) ... import csv import codecs coding = 'cp1254' # or change if current encoding is different data_file="variteks.csv" #attendee_data=csv.reader(open(data_file,"rb")) def pdf_creater(data_file): attendee_data=csv.reader(codecs.EncodedFile(open(data_file,"rb"), coding, 'utf8')) ...
has comment: http://stackoverflow.com/comment/90178549
has comment: http://stackoverflow.com/comment/90178234
answers question: http://stackoverflow.com/q/51591705
downvote count: 0
has comment: http://stackoverflow.com/comment/90216896
has comment: http://stackoverflow.com/comment/90181724

http://stackoverflow.com/comment/90140226
type: Comment
has text: Meanshift has many more parameters. Such as the Kernel to use, the radius, ... You are quite fortunate if the defaults work for you. K largest gaps is what I suggested here!
comment on: http://stackoverflow.com/a/51580352
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90218132
comment on: http://stackoverflow.com/q/51626790
type: Comment
type: QuestionComment
score: 0
has text: Are you adding sudo before running the file/function?

http://stackoverflow.com/comment/89939471
type: QuestionComment
comment on: http://stackoverflow.com/q/51484983
score: 0
has text: Really, the problem is that a fully-general solution has to deal with the case where `startTime - timeMargin < 00:00`, even though that obviously isn't going to happen with a static time and margin of 08:00 and 00:01, so the fully-general solution is more complicated than you need—and may even be harder to understand even if it's easier to code up… I don't think it's a huge problem; either way you implement it should be fine. But I can see why it's frustrating.
type: Comment

http://stackoverflow.com/q/51526263
tagged with: python-3.x
has body: Is it possible to catch an exception raised from the loop in a callable from concurrent.futures.Executor such as this? -- with concurrent.futures.ThreadPoolExecutor(max_workers=num_cores) as executor: futures = {executor.submit(self._process_ticket, i) for i in items} concurrent.futures.wait(futures) I am trying to loop through thousands of objects in a list to perform tasks on and just set up multiprocessing to process them quicker. This is working great but because of the objects I am working on there is a possibility an exception can be raised from the for loop during the process and because it is being called by concurrent.futures.Executor I am unable to catch it the way I was catching it previously. Below is a simple example of how I was catching exceptions previously through a serialized process. I had to create a workaround to force the iteration to try and process the object again and continue from that step forward as the exception causes the loop to stop: def task(self, items, step=None): # items = [list,of,many,objects] try: for i in range(0 if step is None else step, len(items)): with app.app_context(): ## do things with items[i].. except Exception as e: self.task(items, i) I'm basically wanting to force an object to be processed again in the event the loop is interrupted by an exception and continue the loop from that step.
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51596913
tagged with: concurrency
tagged with: python-multiprocessing
type: Question
has title: Catching exceptions in a multiprocessing loop
has answer: http://stackoverflow.com/a/51596913
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51634251
has comment: http://stackoverflow.com/comment/90273280
has comment: http://stackoverflow.com/comment/90232795
has comment: http://stackoverflow.com/comment/90233298
has comment: http://stackoverflow.com/comment/90234142
has comment: http://stackoverflow.com/comment/90233007
type: Question
has comment: http://stackoverflow.com/comment/90233242
tagged with: neural-network
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/90233661
has comment: http://stackoverflow.com/comment/90234070
has body: I have been working with data sets that mostly show the linear relationship between different attributes/features. What activation should I be using with linear datasets? I have been using sigmoid function until now. Is there any other activation function I must try?
has comment: http://stackoverflow.com/comment/90232863
has comment: http://stackoverflow.com/comment/90234108
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90233092
tagged with: activation-function
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python
has title: Activation function for linear dataset
has answer: http://stackoverflow.com/a/51862778
downvote count: 4

http://stackoverflow.com/q/51490944
score: 0
tagged with: pandas
has title: Parse xml using panda
answer count: 1
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
has body: Trying to parse the xml and then reprsent them as Pandas dataframe &lt;?xml version="1.0"?&gt;&lt;results&gt; &lt;header&gt; &lt;cloc_url&gt;github.com/AlDanial/cloc&lt;/cloc_url&gt; &lt;cloc_version&gt;1.74&lt;/cloc_version&gt; &lt;elapsed_seconds&gt;0.940369129180908&lt;/elapsed_seconds&gt; &lt;n_files&gt;124&lt;/n_files&gt; &lt;n_lines&gt;8440&lt;/n_lines&gt; &lt;files_per_second&gt;131.863112209998&lt;/files_per_second&gt; &lt;lines_per_second&gt;8975.19892784178&lt;/lines_per_second&gt; &lt;report_file&gt;/Users/hariomsingh/Desktop/ignitechute/Repo/ignite-chute-aem_cloc.xml&lt;/report_file&gt; &lt;/header&gt; &lt;files&gt; &lt;file name="/Users/hariomsingh/Desktop/ignitechute/Repo/ignite-chute-aem/aem-parent/pom.xml" blank="13" comment="23" code="491" language="Maven" /&gt; &lt;file name="/Users/hariomsingh/Desktop/ignitechute/Repo/ignite-chute-aem/aem-core/aem-core-bundle/src/test/resources/assets.json" blank="0" comment="0" code="357" language="JSON" /&gt; &lt;file name="/Users/hariomsingh/Desktop/ignitechute/Repo/ignite-chute-aem/aem-core/aem-core-bundle/src/main/java/com/chute/aem/core/api/impl/UserServiceImpl.java" blank="26" comment="21" code="202" language="Java" /&gt; output something like file name blank comment language code Repo/ignite-chute-aem/aem-parent/pom.xml" "13" "23" Maven 491 &lt;fullpath&gt;/assets.json" "12" "3" c 432 I was just able to do few lines import pandas as pd from xml.etree import ElementTree tree = ElementTree.parse('/Users/hariomsingh/Desktop/individualxml/ignite-chute-aem_cloc.xml') root = tree.getroot() print(root) print(tree.iter()) csv_data = [] fields = ['file name','blank','comment', 'language', 'code']
type: Question
has answer: http://stackoverflow.com/a/51491649
accepted answer: http://stackoverflow.com/a/51491649
has comment: http://stackoverflow.com/comment/89951181

http://stackoverflow.com/comment/90011182
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51520077
type: Comment
has text: I don't know where the magic number `534` comes from -- that'd be my first line of investigation. Second is to look at which numbers *are* correct -- every integer corresponds to one hashed word in the above code, so if there are differences this is due to the string getting split up differently, or the results gathered up differently. I didn't debug the Python code very closely. (For example, try "configuration configuration configuration" -- does Python produce three numbers or just one?)

http://stackoverflow.com/q/51584866
score: 1
tagged with: matplotlib-basemap
favorite count: 0
has title: How to add legend in Basemap with Python
tagged with: python
has answer: http://stackoverflow.com/a/51624602
type: AnsweredQuestion
tagged with: matplotlib
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51624602
has answer: http://stackoverflow.com/a/51642638
tagged with: python-2.7
answer count: 2
has body: I am trying to put a legend in my world map. Every point is a different kind of devices from a different tweet. Here is my code: import geocoder import json from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt def openJSON(file, path): with open(path + file + '.json', 'r') as fp: data = json.load(fp) return data def App_users(data): android_users = [] iphone_users = [] other_users = [] #3 types of users: Android, Iphone and others: for a, b, c, d in data: if "Twitter for Android" in d: android_users.append([a, b]) elif "Twitter for iPhone" in d: iphone_users.append([a, b]) else: other_users.append([a, b]) data = (android_users, iphone_users, other_users) return data if __name__ == '__main__': posXY_add = [] for d in data[0:50]: if d["user"]["location"] != None: g = geocoder.google(d["user"]["location"]) if g.latlng != None: a = g.latlng + [g.address] + [str(d["source"])] posXY_add.append(a) data = App_users(posXY_add) map = Basemap(llcrnrlat=-70, urcrnrlat=70, llcrnrlon=-180, urcrnrlon=180, epsg=3395) map.arcgisimage(service='ESRI_Imagery_World_2D', xpixels = 1500, verbose= True) colors = ['r', 'g', 'b'] increment = 0 for app in data: for item in app: if len(item) == 2: lat, lon = item[0], item[1] x, y = map(lon, lat) map.plot(x, y, colors[increment] + 'o') increment += 1 plt.title("Geo-position Twitter Devices") plt.show() Have You any suggests to improve my map? Different colors, different map or else? I am using Python 2.7 by Pycharm. My sample data is: ([[21.8974003, 83.39496319999999], [40.2671941, -86.1349019], [10.4805937, -66.90360629999999]], [[50.719164, -1.880769], [37.0903748, -94.5134078], [44.9862701, -93.39398279999999], [47.6062095, -122.3320708], [-27.4697707, 153.0251235], [20.593684, 78.96288]], [[43.2648545, -79.9492978], [39.1767262, -94.4867155], [33.7489954, -84.3879824], [39.7392358, -104.990251], [38.8761634, -77.0337777], [41.0082376, 28.9783589], [36.0753128, -95.95646269999999], [36.0595387, -95.90582429999999], [29.76…
possible better answer: http://stackoverflow.com/a/51642638
downvote count: 0

http://stackoverflow.com/a/51575068
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51574952
accepted answer of: http://stackoverflow.com/q/51574952
score: 1
has comment: http://stackoverflow.com/comment/90115914
downvote count: 0
has body: This is simple with a groupby. But how do you intend on retaining the Filenames when you're aggregating on another column? I'd recommend extracting the absolute directory paths from the Filename using os.path.split and grouping on Filename as well as Language. import os (df.assign(Filename=[os.path.split(v)[0] for v in df.Filename]) .groupby(['Filename', 'Language']) .sum() .reset_index()) Filename Language Value 0 Repo/Repo_3 C 65 1 Repo/Repo_3 Python 59 2 Repo/Repo_3 YAML 20 3 Repo/Repo_3/chapter02/item01 Java 32

http://stackoverflow.com/q/51586870
has comment: http://stackoverflow.com/comment/90141244
has title: Change SQLAlchemy Primary Key after it has been defined
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90141347
has comment: http://stackoverflow.com/comment/90142257
favorite count: 0
has comment: http://stackoverflow.com/comment/90140843
has body: Problem: Simply put, I am trying to redefine a SQLAlchemy ORM table's primary key after it has already been defined. Example: class Base: @declared_attr def __tablename__(cls): return f"{cls.__name__}" @declared_attr def id(cls): return Column(Integer, cls.seq, unique=True, autoincrement=True, primary_key=True) Base = declarative_base(cls=Base) class A_Table(Base): newPrimaryKeyColumnsDerivedFromAnotherFunction = [] # Please Note: as the variable name tries to say, # these columns are auto-generated and not known until after all # ORM classes (models) are defined # OTHER CLASSES def changePriKeyFunc(model): pass # DO STUFF # Then do Base.metadata.create_all(bind=arbitraryEngine) # After everything has been altered and tied into a little bow *Please note, this is a simplification of the true problem I am trying to solve. Possible Solution: Your first thought might have been to do something like this: def possibleSolution(model): for pricol in model.__table__.primary_key: pricol.primary_key = False model.__table__.primary_key = PrimaryKeyConstraint( *model.newPrimaryKeyColumnsDerivedFromAnotherFunction, # TODO: ADD all the columns that are in the model that are also a primary key # *[col for col in model.__table__.c if col.primary_key] ) But, this doesn't work, because when trying to add, flush, and commit, an error gets thrown: InvalidRequestError: Instance &lt;B_Table at 0x104aa1d68&gt; cannot be refreshed - it's not persistent and does not contain a full primary key. Even though this: In [2]: B_Table.__table__.primary_key Out[2]: PrimaryKeyConstraint(Column('a_TableId', Integer(), ForeignKey('A_Table.id'), table=&lt;B_Table&gt;, primary_key=True, nullable=False)) as well as this: In [3]: B_Table.__table__ Out[3]: Table('B_Table', MetaData(bind=None), Column('id', Integer(), table=&lt;B_Table&gt;, nullable=False, default=Sequence('test_1', start=1, increment=1, metadata=MetaData(bind=None))), Column('a_TableId', Integer(), ForeignKey('A_Table.id'), table=&lt;B_Table…
tagged with: python
has comment: http://stackoverflow.com/comment/90144499
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51603541
tagged with: orm
has comment: http://stackoverflow.com/comment/90164882
downvote count: 1
tagged with: sqlalchemy
type: Question
linked to: http://stackoverflow.com/q/39383528
has comment: http://stackoverflow.com/comment/90141629
has comment: http://stackoverflow.com/comment/90140951
has comment: http://stackoverflow.com/comment/90142073
score: -1

http://stackoverflow.com/comment/90188946
comment on: http://stackoverflow.com/a/51612107
type: AnswerComment
score: 0
type: Comment
has text: still getting the error ,which spark version are you using?

http://stackoverflow.com/q/51514488
tagged with: flask
possible better answer: http://stackoverflow.com/a/51514835
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/70276207
tagged with: python
has answer: http://stackoverflow.com/a/51514835
type: AnsweredQuestion
has body: I have a simple Flask web app showing a table that I read from a TSV file (using Pandas). For each row, I'm showing the index, some text, a label (positive/negative) a date, and a "change label" button. I want to be able to change the label in the TSV file for the specific text for which I clicked the "change label" button. I was thinking of using a URL like /edit/<index> so I can use the index passed in the URL to find the corresponding row in the TSV and change it, but without luck. For instance, when I click the button "change label" in the first row of the table, the url would be /edit/0 Here's what I have. Python Flask app @app.route('/admin', methods=['GET', 'POST']) def admin(): if request.method == 'GET': return render_template('admin.html') if request.method == 'POST': if request.form['submit'] == 'Manage': from_date = '01-01-1900' to_date = '01-01-2900' df = pd.read_csv('dataset.tsv', sep='\t', encoding='utf-8') indexes = df.index.values.tolist() texts = df['text'].values.tolist() labels = df['label'].values.tolist() dates = df['date'].values.tolist() data = zip(indexes, texts, labels, dates) return render_template('admin.html', from_date=from_date, to_date=to_date, data=data) @app.route('/edit/<id>', methods=['GET', 'POST']) def edit(): if request.method == 'GET': return render_template('admin.html') if request.method == 'POST': # TODO, open TSV file and change label return render_template('admin.html') admin.html # Text Label Date Edit {% for index, text, label, date in data %} {{ index }} {{ text }} {{ label }} {{ date }} {% endfor %} I know the problem has to do with the in the admin.html, because it fails to pass the index in the URL. When I click any button it just redirects me to /edit/ without any index. Is it possible somehow to pass the variable {{ index }} in the URL or should this be done differently?
has answer: http://stackoverflow.com/a/51514884
accepted answer: http://stackoverflow.com/a/51514884
type: Question
has title: Python Flask: pass Jinja variable to backend

http://stackoverflow.com/q/51515253
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/41918795
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52326138
tagged with: optimization
favorite count: 0
has body: I used tf.keras to build a fully-connected ANN, "my_model". Then, I'm trying to minimize a function f(x) = my_model.predict(x) - 0.5 + g(x) using Adam optimizer from TensorFlow. I tried the below code: x = tf.get_variable('x', initializer = np.array([1.5, 2.6])) f = my_model.predict(x) - 0.5 + g(x) optimizer = tf.train.AdamOptimizer(learning_rate=.001).minimize(f) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(50): print(sess.run([x,f])) sess.run(optimizer) However, I'm getting the following error when my_model.predict(x) is executed: If your data is in the form of symbolic tensors, you should specify the steps argument (instead of the batch_size argument) I understand what the error is but I'm unable to figure out how to make my_model.predict(x) work in the presence of symbolic tensors. If my_model.predict(x) is removed from the function f(x), the code runs without any error. I checked the following link, link where TensorFlow optimizers are used to minimize an arbitrary function, but I think my problem is with the usage of underlying keras's model.predict() function. I appreciate any help. Thanks in advance!
tagged with: python
linked to: http://stackoverflow.com/q/45249476
has title: Optimizing a function involving tf.keras's "model.predict()" using TensorFlow optimizers?
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52326138
upvote count: 3

http://stackoverflow.com/comment/89977960
type: QuestionComment
comment on: http://stackoverflow.com/q/51504480
score: 0
has text: If you want to know the `type` of `data`, call `print(type(data))`
type: Comment

http://stackoverflow.com/comment/90144499
type: QuestionComment
type: Comment
has text: Please provide a clear question. Why do you want to redefine models, instead of simply creating them in their correct form? This question might seem pointless to you, but note that your use case seems rather rare. Also provide a [mcve]. The error you're getting cannot be reproduced with the example code given.
score: 1
comment on: http://stackoverflow.com/q/51586870

http://stackoverflow.com/comment/131578223
type: QuestionComment
has text: Much more specific: *[Suppress output of object when plotting in IPython](https://stackoverflow.com/questions/14506583/suppress-output-of-object-when-plotting-in-ipython)* (2013)
comment on: http://stackoverflow.com/q/51627233
score: 0
type: Comment

http://stackoverflow.com/a/51610987
has body: Firstly, note that the == operator calls __eq__ in the background. In your context it relates to a pd.Series object rather than pd.DataFrame. So these are equivalent: res = pd.Series([1, 2, 3]) == 1 res = pd.Series([1, 2, 3]).__eq__(1) You can then investigate this method: pd.Series.__eq__ &lt;function pandas.core.ops._comp_method_SERIES.&lt;locals&gt;.wrapper&gt; Further, you can investigate _comp_method_SERIES in ops.py: def _comp_method_SERIES(op, name, str_rep, masker=False): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ .... This should get you started. There are utility functions defined, e.g. to deal with null values, which indicate the value that Pandas adds for data manipulation. Optimized operations may end up calling C-level algorithms, which may make tracking performance issues difficult in pure Python.
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51610340
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51610340

http://stackoverflow.com/comment/90441533
type: QuestionComment
type: Comment
has text: @CarlosCordoba there is only one uncommented line matplotlibrc file which is `backend : qt5agg` i commented this but again i have same problem.
score: 0
comment on: http://stackoverflow.com/q/51613969

http://stackoverflow.com/a/51578990
has comment: http://stackoverflow.com/comment/90125419
has body: You could make use of grequests (requests and gevent) and instead of using Pillow to get the image size, you can identify the image size from the HTTP headers: Usually performance depends on the network connection/server speed and image size: import grequests def downloadImages(images): result = {} rs = (grequests.get(t) for t in images) downloads = grequests.map(rs, size=len(images)) for download in downloads: _status = 200 == download.status_code _url = download.url if _status: for k, v in download.headers.items(): if k.lower() == 'content-length': result[_url] = v continue else: result[_url] = -1 return result if __name__ == '__main__': urls = [ 'https://b.tile.openstreetmap.org/12/2075/1409.png', 'https://b.tile.openstreetmap.org/12/2075/1410.png', 'https://b.tile.openstreetmap.org/12/2075/1411.png', 'https://b.tile.openstreetmap.org/12/2075/1412.png' ] sizes = downloadImages(urls) pprint.pprint(sizes) Returns: {'https://b.tile.openstreetmap.org/12/2075/1409.png': '40472', 'https://b.tile.openstreetmap.org/12/2075/1410.png': '38267', 'https://b.tile.openstreetmap.org/12/2075/1411.png': '36338', 'https://b.tile.openstreetmap.org/12/2075/1412.png': '30467'}
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51571729
type: Answer
answers question: http://stackoverflow.com/q/51571729
upvote count: 2

http://stackoverflow.com/comment/90214088
type: QuestionComment
has text: Would agree to use a dictionary to represent the trie. Otherwise, you need to specify a way to represent it (e.g., an id or hash)
score: 0
comment on: http://stackoverflow.com/q/51624207
type: Comment

http://stackoverflow.com/comment/90002106
type: Comment
comment on: http://stackoverflow.com/q/51516510
score: 0
type: QuestionComment
has text: @schwobaseggl Can I request you to write an answer with the code please?

http://stackoverflow.com/a/51611431
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51611076
has body: Try it: with open("/etc/shadow/") as ff: for line in ff: login_name,pwd,remainder=line.split(":",maxsplit=2) print(login_name,pwd) # change it as you like
downvote count: 0
type: Answer

http://stackoverflow.com/q/51591216
type: Question
has answer: http://stackoverflow.com/a/51591929
downvote count: 4
answer count: 2
tagged with: nltk
upvote count: 0
has body: Hi i am using nltk first time and i want to Extract action/task from text using nltk Hi prakash, how are you ?. We need to complete the speech to action by 8 June then you will have to finish the UI by 15 july Above here the speech to action and UI is the action. I have started the token creation, don't know what to do next, Please guide. from nltk import sent_tokenize sample_text ="""Hi prakash, how are you ?. We need to complete the speech to action demo by 8 June then you will have to finish the Ui by 15 july""" sentences = sent_tokenize(sample_text) print(sentences) import nltk from nltk.tag import pos_tag from nltk.tokenize import word_tokenize sample_text = """Hi prakash, how are you ?. We need to complete the speech to action by today then you will have to finish the UI by 15 july after that you may go finish the mobile view""" sample_text = "need to complete the speech to action by today" tokens = word_tokenize(sample_text.lower()) # the lower is very much required, as June and june have diffrent code NN, NNP pos_tags = pos_tag(tokens) result = [] for i in range(len(tokens)): if (pos_tags[i][1] == 'VB') and (pos_tags[i][0] in ['complete','finish']): # Here we are looking for text like (finish, complete, done) owner = '' for back_tag in pos_tags[:i][::-1]: #traverse in back direction to know the owner who will (finish, complete, done) if back_tag[1]=='PRP': owner = back_tag[0] break message = '' date = '' for messae_index , token in enumerate(pos_tags[i:],i): #traverse forward to know what has to be done if token[1]=='IN': for date_index, date_lookup in enumerate(pos_tags[messae_index:],messae_index): if date_lookup[1]=='NN': date = pos_tags[date_index-1][0] + ' ' + pos_tags[date_index][0] if date_lookup[1]=='PRP': # This is trick to stop further propegation # Don't ask me why i am doing this, if you are still reading then read the nest line # Save futher interation as the next sentance is i/we/you break break else: message = message + ' ' + token[0] result +…
favorite count: 0
accepted answer: http://stackoverflow.com/a/51591327
tagged with: python
has title: Extract action/task from text using nltk
score: -4
tagged with: machine-learning
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51591327
possible better answer: http://stackoverflow.com/a/51591929

http://stackoverflow.com/a/51497257
has comment: http://stackoverflow.com/comment/89969386
has comment: http://stackoverflow.com/comment/89962788
accepted answer of: http://stackoverflow.com/q/51496802
has body: You should focus on the error without the Flatten, as you are already using 1D convolutions it wouldn't require flatten to pass to Dense. The actual error is complaining that although the target is (3,) which are your labels, your final Dense layer is outputting 33 values. So it seems like len(labels_index) == 33 and not 3 as you have in your data.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51496802

http://stackoverflow.com/comment/90161891
type: Comment
type: QuestionComment
has text: Maybe you have a `_common` symbol already imported?
comment on: http://stackoverflow.com/q/51568417
score: 0

http://stackoverflow.com/q/51625879
type: Question
linked to: http://stackoverflow.com/q/7585435
has comment: http://stackoverflow.com/comment/90216659
downvote count: 4
upvote count: 0
has answer: http://stackoverflow.com/a/51625991
has comment: http://stackoverflow.com/comment/90216498
favorite count: 0
has body: I want to convert a string 'hello world' to b'hello world' in python, how can I do that?
answer count: 3
has title: how can I convert a 'hello world' to b'hello world'
has answer: http://stackoverflow.com/a/51625954
tagged with: python
has answer: http://stackoverflow.com/a/51625922
type: UnansweredQuestion
score: -4

http://stackoverflow.com/q/51569238
tagged with: datetimeindex
answer count: 2
downvote count: 1
accepted answer: http://stackoverflow.com/a/51569274
has comment: http://stackoverflow.com/comment/90104655
has title: Bar Plot with recent dates left where date is datetime index
linked to: http://stackoverflow.com/q/29511645
tagged with: matplotlib
has body: I tried to sort the dataframe by datetime index and then plot the graph but no change still it was showing where latest dates like 2017, 2018 were in right and 2008, 2009 were left. I wanted the latest year to come left and old to the right. This was the dataframe earlier. Title Date 2001-01-01 0 2002-01-01 9 2003-01-01 11 2004-01-01 17 2005-01-01 23 2006-01-01 25 2007-01-01 51 2008-01-01 55 2009-01-01 120 2010-01-01 101 2011-01-01 95 2012-01-01 118 2013-01-01 75 2014-01-01 75 2015-01-01 3 2016-01-01 35 2017-01-01 75 2018-01-01 55 Ignore the values. Then I sort the above dataframe by index, and then plot but still no change in plots df.sort_index(ascending=False, inplace=True)
tagged with: pandas
type: AnsweredQuestion
upvote count: 0
tagged with: bar-chart
favorite count: 0
has answer: http://stackoverflow.com/a/51569274
type: Question
has answer: http://stackoverflow.com/a/51569559
tagged with: python
has comment: http://stackoverflow.com/comment/90106596
score: -1
possible better answer: http://stackoverflow.com/a/51569559

http://stackoverflow.com/comment/90107813
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51554023
has text: type `activate kz` in your terminal before doing the `conda install`
score: 1

http://stackoverflow.com/comment/90090282
has text: Yes. I set the pycharm preference Project Interpretor to ~/.pyvenv/versions/myvenv (i.e where 'myvenv' is the correctd virtual env)
comment on: http://stackoverflow.com/q/51561515
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89963894
type: QuestionComment
has text: Can you specify your object or clarify on what do you mean by ‘more generic form’....
comment on: http://stackoverflow.com/q/51497937
score: 0
type: Comment

http://stackoverflow.com/comment/90203404
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51602694
type: QuestionComment
has text: @ZevSpitz so there's no way to fix this within OpenPyXL? It's strange that such a relatively small file is causing such huge memory leaks.

http://stackoverflow.com/comment/90155807
score: 0
comment on: http://stackoverflow.com/a/51594855
type: AnswerComment
has text: Why it says: `TypeError: 'str' object does not support item assignment`
type: Comment

http://stackoverflow.com/comment/89957741
comment on: http://stackoverflow.com/q/51494587
has text: Reference https://stackoverflow.com/questions/328851/printing-all-instances-of-a-class
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89999484
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51515164
has text: the expression can be trusted and the expected result can evaluated using eval. I do not know the variables from the start that why I have created this allVariables visitor to retrieve them

http://stackoverflow.com/q/51513711
has comment: http://stackoverflow.com/comment/89995848
linked to: http://stackoverflow.com/q/29780060
tagged with: django
tagged with: request
has answer: http://stackoverflow.com/a/51534462
has comment: http://stackoverflow.com/comment/89996042
has comment: http://stackoverflow.com/comment/89996320
has comment: http://stackoverflow.com/comment/89996981
has comment: http://stackoverflow.com/comment/89996479
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/89997571
has comment: http://stackoverflow.com/comment/89997163
has comment: http://stackoverflow.com/comment/89995772
tagged with: post
type: Question
has comment: http://stackoverflow.com/comment/89996342
has body: I'm crawling a website and gathering it's data. I have some crawler machine, where they send data to a central server. Part of code in crawlers which send data to server is as follows : requests.post(url, json=data, timeout=timeout, cookies=cookies, headers=headers) At the central server side which uses django, I have the following code: def save_users_data(request): body = json.loads(request.body) // do something on data received sometimes server receives incomplete data from crawlers and so json package cannot load data and raises error. For example server received following data in request.body : b'{"social_network": "some network", "text": "\\u0646\\u06cc\\u0633 \\u0628\\u0627\\u06cc\\u062f \\u0622\\u062a\\u06cc\\u0634 \\u062f\\u0631\\u0633\\u062a \\u06a9\\u0631\\u062f\\u0628\\u0631\\u06af\\u0634\\u062a\\u' and raises following error : json.decoder.JSONDecodeError: Invalid \uXXXX escape Where is the problem? EDIT This some lines of nginx error.log file : 2018/07/25 12:54:39 [info] 29199#29199: *2520751 client 45.55.4.47 closed keepalive connection 2018/07/25 12:54:39 [info] 29199#29199: *2520753 client 188.166.71.114 closed keepalive connection 2018/07/25 12:55:35 [info] 29199#29199: *2520755 client 45.55.4.47 closed keepalive connection 2018/07/25 12:55:58 [info] 29199#29199: *2520757 client 45.55.4.47 closed keepalive connection 2018/07/25 12:55:59 [info] 29199#29199: *2520759 client 45.55.197.140 closed keepalive connection 2018/07/25 12:56:03 [info] 29199#29199: *2520761 client 188.166.71.114 closed keepalive connection 2018/07/25 12:56:04 [info] 29197#29197: *2520715 epoll_wait() reported that client prematurely closed connection, so upstream connection is closed too while sending request to upstream, client: 167.99.189.246, server: 91.208.165.33, request: "POST /crawler/save/users-data/ HTTP/1.1", upstream: "http://unix:/home/social/centralsystem/centralsystem.sock:/crawler/save/users-data/", host: "91.208.165.33" 2018/07/25 12:56:11 [info] 29197#29197: *2…
has comment: http://stackoverflow.com/comment/89997235
answer count: 2
has comment: http://stackoverflow.com/comment/89995927
has comment: http://stackoverflow.com/comment/89996932
upvote count: 1
has comment: http://stackoverflow.com/comment/89995869
favorite count: 0
has title: receiving incomplete data when using python requests
has answer: http://stackoverflow.com/a/51513793
has comment: http://stackoverflow.com/comment/89997014
tagged with: python
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89997406

http://stackoverflow.com/q/51582540
has comment: http://stackoverflow.com/comment/90130411
has comment: http://stackoverflow.com/comment/90130417
type: Question
has body: I have come up with the below code but somehow its not working as expected. What could be the reason of this. Idea is to make a pair of count and item to be pushed to the priority queue and then just pop.But how to implement this in python3? import heapq class Stack: def __init__(self): self.dict ={} self.cnt = 0 self.hq = [] def push(self, item): self.cnt += 1 self.heappush(hq, {self.cnt:item}) def pop(self): self.cnt -= 1 return self.heappop(hq) if __name__ == '__main__': s = Stack() s.push(10) s.push(20) s.push(30) print(s.pop()) I am receiving the below error. Traceback (most recent call last): File "/home/shrivatsa/Documents/E/Learning-Path/Python/Algorithms and Datastructure/stackpriorityqueue.py", line 19, in &lt;module&gt; s.push(10) File "/home/shrivatsa/Documents/E/Learning-Path/Python/Algorithms and Datastructure/stackpriorityqueue.py", line 11, in push self.heappush(hq, {self.cnt:item}) AttributeError: 'Stack' object has no attribute 'heappush'
answer count: 2
has answer: http://stackoverflow.com/a/51582812
has title: Stack using priority Queue in Python3
has comment: http://stackoverflow.com/comment/90130447
tagged with: python
has comment: http://stackoverflow.com/comment/90130372
tagged with: python-3.x
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51582753
has comment: http://stackoverflow.com/comment/90130451

http://stackoverflow.com/comment/90126535
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51578948
has text: Not sure, this is probably not the case as I have python 3.7 Anyway, Thanks!

http://stackoverflow.com/q/51625265
tagged with: airflow
tagged with: python-2.7
has body: I am trying to schedule a spark job in airflow, here is my dag, from __future__ import print_function import airflow from airflow.contrib.operators.spark_submit_operator import SparkSubmitOperator from airflow.models import DAG from datetime import datetime, timedelta import os APPLICATION_FILE_PATH = "/home/ubuntu/airflow/dags/scripts/" default_args = { 'owner': 'Airflow', 'depends_on_past': False, 'retries': 0, } dag = DAG('datatodb', default_args=default_args, start_date=(datetime(2018,7,28)),schedule_interval='0 5 * * *') data_to_db = SparkSubmitOperator( task_id='data_to_db', application=APPLICATION_FILE_PATH+"ds_load.py", dag=dag, run_as_user='ubuntu', application_args=["{{ ds }}"] ) data_to_db And my python script is this, from pyspark import SparkContext from pyspark.sql import SQLContext, SparkSession from datetime import datetime, timedelta import sys def write_to_db(previous_day,spark_session): drop_cols = ['created_date','Year','Month'] datapath = "s3a://***/" s3path = datapath + 'date=' + str(previous_day) data_to_load_df = spark_session.read.parquet(s3path).drop(*drop_cols).withColumn('date',lit(previous_day)) data_to_load_df.write.format('jdbc').options(url='jdbc:mysql://servername:3306/dbname', driver='com.mysql.jdbc.Driver', dbtable='report_table', user='****', password="***").mode('append').save() def main(previous_day,spark_session=None): if spark_session is None: spark_session = SparkSession.builder.appName("s3_to_db").getOrCreate() write_to_db(previous_day,spark_session) if __name__ == "__main__": previous_day = sys.argv[1] main(previous_day) Not sure what is wrong with this, I keep getting this error, [2018-08-01 02:08:37,278] {base_task_runner.py:98} INFO - Subtask: [2018-08-01 02:08:37,278] {base_hook.py:80} INFO - Using connection to: local [2018-08-01 02:08:37,298] {base_task_runner.py:98} INFO - Subtask: Traceback (most recent call last): [2018-08-01 02:08:37,299] {base_task_runner.py:98} INFO - Subtask: File "/home/ubuntu/anaconda2/bin/ai…
answer count: 1
has title: airflow spark-submit operator - No such file or directory
downvote count: 0
favorite count: 0
tagged with: apache-spark
tagged with: python
has answer: http://stackoverflow.com/a/51625871
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/90213511
type: QuestionComment
comment on: http://stackoverflow.com/q/51624207
has text: You can represent a trie with a standard dictionary ([see my answer here](https://stackoverflow.com/a/51296069/6779307)), then you can use `json.dump` to convert it to a json file.
score: 1
type: Comment

http://stackoverflow.com/q/51618820
has body: I pretend crawl every item in of the drop-down list in the top of this page: https://www.anmp.pt/anmp/pro/mun1/mun101w3.php?cod=M2200 with Scrapy framework. Then for every item found I get a new page, where I get some more data that must fill the models instantiated in Models.py I can get the data, but I have been unable to put it in the flask.Fields() of my model. I searched in the web for hints but no success. The field "contacto" in the spider is just to collect the other two fields after: Sorry the names are in portuguese, but it is a portuguese app! This is my Spider.py: # -*- coding: utf-8 -*- import scrapy import urlparse from scrapy.http import FormRequest from scrapy.loader import ItemLoader from municipios.items import Municipio import time class GetmunSpider(scrapy.Spider): name = 'getMun' allowed_domains = ['anmp.pt'] start_urls = ['https://www.anmp.pt/anmp/pro/mun1/mun101w3.php?cod=M2200'] def municipio_attr(self, response): municipios_url = response.xpath('//select/option/@value').extract() for municipio in municipios_url: full_url = ['https://www.anmp.pt/anmp/pro/mun1/{0}'.format(i) for i in municipios_url] yield FormRequest.from_response(str(full_url), callback=self.parse) def parse(self, response): #dados do municipio municipio = ItemLoader(item = Municipio(), response = response) municipio.add_xpath('nome', '//div[@class="sel3"]/text()'.extract()) municipio.add_xpath('pres_camara','//div[@class="f3"]/text()' [3].extract().split(",")[0] municipio.add_xpath('pres_assembleia','//div[@class="f3"]/text()' [4].extract().split(",")[0] municipio.add_xpath('contacto','//div[@class="sel2"]/text( )').extract() municipio.add_value('endereco', " ".join(contacto)[:-42]) municipio.add_value('telefone', contacto[2]) municipio.add_value('fax', contacto[3]) return Municipio.load_item() And these are the fields to populate: import scrapy from scrapy.item import Item, Field class Municipio(scrapy.Item): nome = scrapy.Field() pres_camara = scrapy.Field() pres_assemblei…
downvote count: 0
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
tagged with: web-crawler
tagged with: scrapy
type: Question
has title: collect values with Scrapy

http://stackoverflow.com/comment/90136022
score: 0
type: AnswerComment
has text: Wow, I am really dumb. I think I may be blind. I don't see how I was stuck on this for an entire day. But apparently that isn't enough to fix the problem. Any advice?
type: Comment
comment on: http://stackoverflow.com/a/51584978

http://stackoverflow.com/q/51508906
type: Question
has body: Ok, I need help with this problem and its my last project of college and I am not a csc major so I really just need some help!! I need to read from a file of random numbers and find the max, min and avg. And then group how many scores are in each (10%) decile from 0-100. Not sure why my code isn't running, I have only attempted getting the min, max and average so far. I have looked for help with the reading file to list issue but a lot of the solutions include some type of "with" loop thing, which I haven't learned yet. Also, was thinking of maybe having separate functions/methods for the sorting and then the percentage/stars. Thank you for any help! Example output: The high score is: 100 The low score is: 0 The average is: 55.49 Range Number Percent ========================================= 0-9 75 7.5% ******* 10-19 82 8.2% ******** etc.... Input file is a .txt file with each score on a new line. 33 99 14 52 76 78 This is the error that comes out: Traceback (most recent call last): File "/Users/meganhorton/Desktop/Python/hw5.py", line 36, in &lt;module&gt; main() File "/Users/meganhorton/Desktop/Python/hw5.py", line 20, in main avgScore = float(sum(scoresList)/len(scoresList)) TypeError: unsupported operand type(s) for +: 'int' and 'str' &gt;&gt;&gt;
answer count: 2
has title: Python: How to read from file of numbers (scores) use as list and get high score, low, and average score, and group into deciles
has comment: http://stackoverflow.com/comment/89986852
has comment: http://stackoverflow.com/comment/89987977
score: 0
has comment: http://stackoverflow.com/comment/89987089
has answer: http://stackoverflow.com/a/51509363
tagged with: readfile
has answer: http://stackoverflow.com/a/51515469
has comment: http://stackoverflow.com/comment/89986878
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89988062
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89986975
tagged with: file
tagged with: python
has comment: http://stackoverflow.com/comment/89987950
tagged with: list

datatables
tags question: http://stackoverflow.com/q/51549315
tags question: http://stackoverflow.com/q/51537914
type: Tag
tag name: datatables

http://stackoverflow.com/a/51576990
type: Answer
accepted answer of: http://stackoverflow.com/q/51576967
has comment: http://stackoverflow.com/comment/90119567
answers question: http://stackoverflow.com/q/51576967
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/90119413
has comment: http://stackoverflow.com/comment/90165792
type: AcceptedAnswer
downvote count: 0
has body: You may not need a rolling window here. Let's try where/mask + ffill: df['col3'] = df['col1'].where(df['col2']).shift().ffill().fillna(df.at[0, 'col1']) df col1 col2 col3 0 a False a 1 b False a 2 c True a 3 d False c 4 e True c 5 f False e
has comment: http://stackoverflow.com/comment/90121997

http://stackoverflow.com/comment/90132711
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51583643
has text: tangent: input() returns a string - not need to stringify it.
type: Comment

http://stackoverflow.com/comment/90119621
type: AnswerComment
type: Comment
has text: I believe the intention is to create a list of coins, not a dict-of-dicts.
comment on: http://stackoverflow.com/a/51576939
score: 0

http://stackoverflow.com/comment/90409127
score: 1
type: Comment
type: QuestionComment
has text: Sure, it's a major drawback as you need to keep your `__init__.py` consistent on changes; but why don't you want to build the shared object from C source code by configuring an `Extension`? This would be the most straightforward way IMO. Should you need a prebuilt shared object in `dddd` for development, you can always build one via `python setup.py build_ext`. You would then also eliminate the need of the `dddd` package completely and your imports would work by default.
comment on: http://stackoverflow.com/q/51607349

http://stackoverflow.com/q/51586693
has body: When src has shape [?], tf.gather(src, tf.where(src != 0)) returns a tensor with shape [?, 0]. I'm not sure how a dimension can have size 0, and I'm especially unsure how to change the tensor back. I didn't find anything in the documentation to explain this, either. I tried to tf.transpose(tensor)[0], but the first dimension of the transposed tensor has size 0 and cannot be accessed! What's wrong?
tagged with: reshape
upvote count: 1
tagged with: tensorflow
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90138896
score: 1
has answer: http://stackoverflow.com/a/51586823
answer count: 1
downvote count: 0
tagged with: tensorflow-datasets
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51586823
tagged with: python-3.x
has title: Tensor has shape [?, 0] -- how to reshape to [?,]

http://stackoverflow.com/q/51512550
has comment: http://stackoverflow.com/comment/89994830
answer count: 1
has comment: http://stackoverflow.com/comment/89993640
score: 0
has body: I'm writing a dictionary into a csv file using Python's csv library and a DictWriter object like so: with open('test.csv', 'w', newline='') as fp: fieldnames = [&lt;fieldnames for csv DictWriter&gt;] dict_writer = csv.DictWriter(fp, fieldnames=fieldnames) dict_writer.writeheader() dict_writer.writerow(&lt;some dictionary here&gt;) The result is that if i have a long name as one of the dictionary's values the cells look like this: But i want it to look like this: Is there a way to fit the cells' size to the string lengths ? I imagine this is a relatively common issue since you don't want to manually do it each time you open a csv file. How can i fit it beforehand ?
has answer: http://stackoverflow.com/a/51512664
tagged with: python
accepted answer: http://stackoverflow.com/a/51512664
tagged with: python-3.x
type: AnsweredQuestion
has title: Python csv - fit cells' size to fit strings' length?
has comment: http://stackoverflow.com/comment/89993662
linked to: http://stackoverflow.com/q/17326973
type: Question

http://stackoverflow.com/q/51485353
possible better answer: http://stackoverflow.com/a/51485546
has answer: http://stackoverflow.com/a/51485546
has comment: http://stackoverflow.com/comment/89939991
type: Question
type: AnsweredQuestion
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51485549
answer count: 2
has body: I have a df1 like this: Type Name Identifier Number Amount A xx 0001 12 0.89 xx 0001 56 0.78 zz 0002 33 0.56 yy 0020 44 0.45 yy 0020 67 0.45 B ww 0300 12 0.34 ww 0300 54 0.1 kk 0900 43 0.2 I want to get the count of the duplicated identifier per type such that the resulting dataframe now looks like Type Count_Dups Ave. Amount A 2 2.345 B 1 0.44 where ave. amount is the sum of all duplicated values / count of duplicated values. (example: A = (0.89+0.78+0.45+0.45)/2) should I use a for loop? is groupby enough?
has answer: http://stackoverflow.com/a/51485549
score: 4
has comment: http://stackoverflow.com/comment/89940045
has comment: http://stackoverflow.com/comment/89970317
favorite count: 0
upvote count: 5
has title: Get count of duplicated values per category/group in pandas python
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/89970265
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89939865
has comment: http://stackoverflow.com/comment/89970329

http://stackoverflow.com/a/51640036
score: 0
type: Answer
has body: If I understand your problem clearly, You have predecided the place and the title and want the user to enter only the image. Only image should be kept in the form, but you want to enter the title and the place in the view. If that's the case,do this : Your view function: def some_view(request): if request.method == "POST": T,P = get_title_and_place() # This fuction will return a tuple with the title and the place that you need. # Or Alternatively, you can pass the title and place as argument to the view obj = Picture(title=T,place=P) #Initialise object with title and place received from function or arguments pic_form = PictureForm(request.POST, request.FILES) #The form contains only the image field as in your last block of code if pic_form.is_valid(): obj.image = request.FILES['image'] obj.save() #Save the object return redirect('some_url') else: return render('xyz.html',{"form":pic_form}) #Incoming image is invalid. Throw back the invalid form to the user else: #Incoming method is not POST, give user the form to fill the image pic_form = PictureForm() return render('xyz.html',{"form:pic_form}) On submission of the form from xyz.html, you should redirect back to this view. This is the reason why I made a seperate function to get the title and place so that user doesn't know about it via the url. However be careful with this method. You have to take care of validating the title and place. Otherwise the obj.save() will throw error
accepted answer of: http://stackoverflow.com/q/51637195
answers question: http://stackoverflow.com/q/51637195
type: AcceptedAnswer

http://stackoverflow.com/comment/101893363
type: AnswerComment
type: Comment
has text: Yep, a restart is required for pylint to work properly after installation. I had the same problem with false error messages before.
comment on: http://stackoverflow.com/a/51541184
score: 1

http://stackoverflow.com/comment/90282147
score: 0
type: AnswerComment
type: Comment
has text: I've got my model with the .pb file and related variables file saved on google cloud storage and linked to a model in the ml engine. How do I go about finding the URL for a post request or actually using the model for prediction?
comment on: http://stackoverflow.com/a/51636865

http://stackoverflow.com/q/51492423
has answer: http://stackoverflow.com/a/63515550
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/94553989
has body: Is there a way in pipenv to specify the minimum version of python in the Pipfile? Would something like this work? [requires] python_version = "&gt;=python 3.5"
has comment: http://stackoverflow.com/comment/89961897
favorite count: 0
type: UnansweredQuestion
upvote count: 56
tagged with: pipfile
tagged with: python
has comment: http://stackoverflow.com/comment/94553010
has comment: http://stackoverflow.com/comment/89953512
has comment: http://stackoverflow.com/comment/89970895
has title: pipenv: how to specify the minimum python version in the pipfile?
has answer: http://stackoverflow.com/a/76191377
type: Question
tagged with: pipenv
score: 56

http://stackoverflow.com/q/51587643
has body: Basically my text file looks like this. **A: lorem ipsum verade(unique)** a: asd b: asd c: alsd d: def **B: korem ipsum vladmir(unique)** c: fdh e: asd **C: lorum ipsum vladmir(unique)** a: asd b: asd d: def e: asd As one can see here let say example.txt have 3 main entries(A, B, C) having multiple data. My question is hoe can I check Multiple condition for A eg i want all entries from A,B,C if a: asd and d: def. So output should be A and C. Basically I want to know how to chexk multiple line while keeping track of line earlier. I hope i made it clear.Just to remember this is a huge file so multiple loops need to be avoided if possible.
tagged with: sed
has answer: http://stackoverflow.com/a/51588402
tagged with: awk
has answer: http://stackoverflow.com/a/51589095
score: 4
has comment: http://stackoverflow.com/comment/90143131
favorite count: 0
has answer: http://stackoverflow.com/a/51590438
upvote count: 5
answer count: 5
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90142639
has comment: http://stackoverflow.com/comment/90142799
tagged with: python-3.x
has title: how to Check multiple conditions on multiple line belonging to variable size block of lines and return the main line
has comment: http://stackoverflow.com/comment/90145157
has answer: http://stackoverflow.com/a/51602747
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51589134

http://stackoverflow.com/q/51549448
has comment: http://stackoverflow.com/comment/90066567
has comment: http://stackoverflow.com/comment/90066589
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
tagged with: delimiter
has answer: http://stackoverflow.com/a/51637563
favorite count: 0
has comment: http://stackoverflow.com/comment/90066457
type: UnansweredQuestion
tagged with: separator
tagged with: python
has comment: http://stackoverflow.com/comment/90066490
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90066511
has comment: http://stackoverflow.com/comment/90066486
type: Question
has comment: http://stackoverflow.com/comment/90126546
upvote count: 1
has comment: http://stackoverflow.com/comment/90126551
has title: Space delimiter in CSV import to Python
has comment: http://stackoverflow.com/comment/90066503
has comment: http://stackoverflow.com/comment/90066449
has body: I know there are more than a few questions regarding space delimiters in CSV files. I have a CSV file that appears to be separated by a space. When importing to Python, I have tried every code out there to identify space as a delimiter. However, I keep getting error messages. For example: test_filepath = 'test_data.csv' with codecs.open(test_filepath, "r", "Shift-JIS", "ignore") as file: # import UTF8 based csv file test_df = pd.read_table( file, delim_whitespace=True ) this yields the following error: EmptyDataError: No columns to parse from file when I try this: test_filepath = 'test_data.csv' with codecs.open(test_filepath, "r", "Shift-JIS", "ignore") as file: # import UTF8 based csv file test_df = pd.read_table( file, delimiter=" " ) it gives the same error. when i try this: test_filepath = 'test_data.csv' with codecs.open(test_filepath, "r", "Shift-JIS", "ignore") as file: # import UTF8 based csv file test_df = pd.read_table( file, sep = "/s+" ) I get the same error. When I try this: test_filepath = 'test_data.csv' with codecs.open(test_filepath, "r", "Shift-JIS", "ignore") as file: # import UTF8 based csv file test_df = pd.read_table( file, delimiter='\t') I get the same error. the ONLY WAY I dont get an error is if I do this: test_filepath = 'test_data.csv' with codecs.open(test_filepath, "r", "Shift-JIS", "ignore") as file: # import UTF8 based csv file test_df = pd.read_table( file, delimiter=',') but the results look completely off, and test_df.info() shows that only one column is created (there should be like 100 columns).

http://stackoverflow.com/comment/90094566
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51563435
has text: IP and User can be a string or a list, it doesn't matter for my use case. I don't think that MultiIndex is important, the output is just being analyzed by a human so as long as it is readable it would be fine

http://stackoverflow.com/q/51587656
favorite count: 0
has comment: http://stackoverflow.com/comment/90140879
tagged with: python
has body: I was searching about how to trace function graphs, but not only linear ones, I know how to plot with simple points, they are the linear ones like this one below: import numpy import matplotlib.pyplot as plt %matplotlib inline _=plt.plot([4,7],[5,7],color ='w') _=plt.plot([4,7],[7,7],color ='w') ax = plt.gca() ax.set_facecolor('xkcd:red') plt.show() then after a bit of searching, I've found this code: import pylab import numpy x = numpy.linspace(-15,15,100) # 100 linearly spaced numbers y = numpy.sin(x)/x # computing the values of sin(x)/x # compose plot pylab.plot(x,y) # sin(x)/x pylab.plot(x,y,'co') # same function with cyan dots pylab.plot(x,2*y,x,3*y) # 2*sin(x)/x and 3*sin(x)/x pylab.show() # show the plot That works perfectly! But what I'm wondering is: do we really need to use standard functions that have defined by Numpy?( like sin(x)/x here ) Or can we define a function ourselves and use it in Numpy function too, like x**3?
accepted answer: http://stackoverflow.com/a/51607572
type: AnsweredQuestion
score: 1
upvote count: 1
has title: Tracing functions in python
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90140487
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51607572
downvote count: 0
answer count: 1

http://stackoverflow.com/q/51495274
upvote count: 1
has comment: http://stackoverflow.com/comment/89959082
score: 1
has title: Accessing diagonal elements in python square matrix without NumPy
type: Question
has comment: http://stackoverflow.com/comment/89959005
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89958777
tagged with: multidimensional-array
linked to: http://stackoverflow.com/q/240178
tagged with: python
has comment: http://stackoverflow.com/comment/89959043
answer count: 0
type: UnansweredQuestion
has body: I am trying to set all the elements in the principal diagonal of the matrix to be equal to one. Here is my code for the same, using a matrix named "a": for i in range(len(a)): a[i][i] = 1 However, this is setting all elements in a to be 1. I found out that this is because the call a[i][i] is accessing the entire i'th row and not the i'th diagonal element. How do I modify the code to have the intended effect?

http://stackoverflow.com/q/51599289
favorite count: 0
has title: Python - Search list for value in dataframe column, append result of operation involving other column to list
score: -3
has comment: http://stackoverflow.com/comment/90164520
tagged with: python
tagged with: regex
type: AnsweredQuestion
has body: I have a list of strings, like so: m = ['First Officer', 'Executive Officer'] As well as a Pandas dataframe like so: d = {'match': ['and', 'first'], 'use': ['&amp;', '1st']} df = pd.DataFrame(data=d) I'd like to re.search every string in the m for every substring in df.match, and when there is a match, to append the re.sub of m[i] and df.match[i] for the respective df.use[i] to m. Expected output is: &gt;&gt; ['First Officer', 'Executive Officer', '1st Officer'] What would the fastest implementation of this be?
has answer: http://stackoverflow.com/a/51599468
has comment: http://stackoverflow.com/comment/90164644
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90164594
has comment: http://stackoverflow.com/comment/90164623
has comment: http://stackoverflow.com/comment/90164555
accepted answer: http://stackoverflow.com/a/51599468
downvote count: 4
tagged with: pandas
answer count: 1

http://stackoverflow.com/a/51572888
type: AcceptedAnswer
has body: You can extract Dot11Elt layers like this: pkt_elt = pkt[Dot11Elt] while isinstance(pkt_elt, Dot11Elt): print "tag id = %d" % pkt_elt.ID pkt_elt = pkt_elt.payload
answers question: http://stackoverflow.com/q/51569251
type: Answer
accepted answer of: http://stackoverflow.com/q/51569251
score: 0

http://stackoverflow.com/q/51568251
has title: converting nested list into a dictionary
has comment: http://stackoverflow.com/comment/90102910
has answer: http://stackoverflow.com/a/51568308
has answer: http://stackoverflow.com/a/51568351
type: Question
tagged with: python
tagged with: dictionary
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51568281
has body: b = [['a', '1'], ['b', '2'], ['c', '3']] c = {} for i in range(len(b)): m = i[0] c[m] = i[1] My goal is to make the nested list b into a dictionary. However, I keep getting an error saying TypeError: 'int' object is not subscriptable
has comment: http://stackoverflow.com/comment/90102805
has comment: http://stackoverflow.com/comment/90102880
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90102878

http://stackoverflow.com/q/51618103
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: cosine-similarity
accepted answer: http://stackoverflow.com/a/51618254
has title: Handling Error for Continuous Features in a Content-Based Filtering Recommender System
has body: I've got a content-based recommender that works... fine. I was fairly certain it was the right approach to take for this problem (matching established "users" with "items" that are virtually always new, but contain known features similar to existing items). As I was researching, I found that virtually all examples of content-based filtering use articles/movies as an example and look exclusively at using encoded tf-idf features from blocks of text. That wasn't exactly what I was dealing with, but most of my features were boolean features, so making a similar vector and looking at cosine distance was not particularly difficult. I also had one continuous feature, which I scaled and included in the vector. As I said, it seemed to work, but was pretty iffy, and I think I know part of the reason why... The continuous feature that I'm using is a rating (let's call this "deliciousness"), where, in virtually all cases, a better score would indicate an item more favorable for the user. It's continuous, but it also has a clear "direction" (not sure if this is the correct terminology). Error in one direction is not the same as error in another. I have cases where some users have given high ratings to items with mediocre "deliciousness" scores, but logically they would still prefer something that was more delicious. That user's vector might have an average deliciousness of 2.3. My understanding of cosine distance is that in my model, if that user encountered two new items that were exactly the same except that one had a deliciousness of 1.0 and the other had a deliciousness of 4.5, it would actually favor the former because it's a shorter distance between vectors. How do I modify or incorporate some other kind of distance measure here that takes into account that deliciousness error/distance in one direction is not the same as error/distance in the other direction? (As a secondary question, how do I decide how to best scale this continuous feature next to my boolean features?)
answer count: 1
downvote count: 0
favorite count: 0
tagged with: recommendation-engine
has answer: http://stackoverflow.com/a/51618254

http://stackoverflow.com/comment/90147431
comment on: http://stackoverflow.com/a/51558427
type: AnswerComment
score: 0
type: Comment
has text: I added another example which may be closer to what you want. I think there are many ways to write this and I am not sure the solution here is the clearest and less confusing... I advice you to try different things in order to find the most coherent code according to the structure of your input data and the wanted output

http://stackoverflow.com/q/51587960
has body: Say I got a vector of size [1 x 300], in which each element consists of 0 or 1. I might need to store a bunch of these iteratively during the run time. How do I effectively represent it so that I can effeciently store them (python)? I guess there are two ways to do it. The first method is to do something like a bitmap (do they even have this in python)? The second approach I was thinking maybe is to store the 1's position. eg. [0, 1, 1, 1]. I will store them as [1,2,3]. Any ideas?
tagged with: memory-management
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90141793
tagged with: store
tagged with: python
score: 3
linked to: http://stackoverflow.com/q/18948382
upvote count: 3
tagged with: memory
has comment: http://stackoverflow.com/comment/90141389
type: Question
tagged with: algorithm
has answer: http://stackoverflow.com/a/51588199
answer count: 1
has comment: http://stackoverflow.com/comment/90141720
downvote count: 0
has title: Compress long vector consists of 0 and 1
favorite count: 0

http://stackoverflow.com/q/51565618
upvote count: 5
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/53462811
downvote count: 0
tagged with: ckeditor
has answer: http://stackoverflow.com/a/51578685
favorite count: 0
tagged with: python
type: UnansweredQuestion
has body: Im installing the ckeditor app in my django, follow the instructions from ckeditor documentation at the moment of run the runserver, doesn't works, well,I get the error when add the from ckeditor.fields import RichTextField in the models.py This is my settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'suj4$h^8p&amp;x#p_#i$_p&amp;z@&amp;d^46=#7kf6a#_tkqh68er^)872s' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'ckeditor', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.j…
tagged with: django
type: Question
has title: ImportError: cannot import name 'get_default_renderer'

http://stackoverflow.com/comment/90173010
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51603442
type: Comment
has text: Can you look into the output for `filevalues[filevalues.isnull()]`?

http://stackoverflow.com/a/51627877
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Try setting hovermode to closest in layout. import plotly plotly.offline.init_notebook_mode() x = [0] * 10 y = [y for y in range(0, 10)] data = [plotly.graph_objs.Scatter(x=x, y=y)] layout = plotly.graph_objs.Layout(hovermode='closest') figure = plotly.graph_objs.Figure(data=data, layout=layout) plotly.offline.iplot(figure)
upvote count: 3
answers question: http://stackoverflow.com/q/51620933
accepted answer of: http://stackoverflow.com/q/51620933

http://stackoverflow.com/a/51545167
downvote count: 0
answers question: http://stackoverflow.com/q/51544775
type: Answer
accepted answer of: http://stackoverflow.com/q/51544775
upvote count: 3
has body: All you need is: import pandas as pd # Group it group_df = combo_df.groupby(['city','type']) # Aggregate it aggregated_df = group_df.agg({'fare': 'mean', 'ride_id': 'count'}) # Reset index (only type) summary_df = aggregated_df.reset_index(level=1)
score: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/90070388
comment on: http://stackoverflow.com/q/51550181
score: 0
has text: My bad,sir.That's all right there.Thanks
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51608912
duplicate of: http://stackoverflow.com/q/14241133
tagged with: declaration
answer count: 0
tagged with: join
has comment: http://stackoverflow.com/comment/90183417
type: Question
has comment: http://stackoverflow.com/comment/90183309
has body: I have 2 lists where rakam = 1 to 9 sakla_l = sakla,sakla,sakla etc 9 times. I want to join these 2 lists to become sakla0,sakla1,sakla2 etc till sakla9 then I want to declare all as one like sakla0 =1 sakla1= 1 sakla2= 1 etc.. I am accessing these declarations from below parts of my code now I declared manually but I didn't like to code and I am trying to improve with for loop but no success searched a lot within stackoverflow but I can't find nothing similar to that.Please don't say it's duplicate question because it's not. My aim not to print these items.My aim is to have that declaration of these items equal to 1. import string rakam= list(range(10)) sakla_l =["sakla"] * 10 for i in range(10): j_list=sakla_l[i].join(str(i)) j_list[i] = 1 print(j_list) My working undesired code is below: sakla0=1 sakla1=1 sakla2=1 sakla3=1 sakla4=1 sakla5=1 sakla6=1 sakla7=1 sakla8=1 sakla9=1 You might ask why you need to declare, the reason I am hiding some tables or unhiding some tables within the django html template based on these values.
score: 0
has comment: http://stackoverflow.com/comment/90183297
has comment: http://stackoverflow.com/comment/90183449
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/14241133
tagged with: django
has comment: http://stackoverflow.com/comment/90183239
has title: looping declaration code improvement for django
tagged with: python
has comment: http://stackoverflow.com/comment/90183370

http://stackoverflow.com/q/51569281
has title: What does get_rect() do in the following program? Why was it used?
has answer: http://stackoverflow.com/a/51569314
tagged with: python
tagged with: pygame
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I was going through a tutorial here - www.raywenderlich.com/24252/beginning-game-programming-for-teens-with-python. In Step 4, he used the following statement : # 6.1 - Set player position and rotation position = pygame.mouse.get_pos() angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26)) playerrot = pygame.transform.rotate(player, 360-angle*57.29) playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2) screen.blit(playerrot, playerpos1) what exactly did he do? and why did he do so?
type: Question
possible better answer: http://stackoverflow.com/a/51569314
has answer: http://stackoverflow.com/a/51569527
has comment: http://stackoverflow.com/comment/90104862
has answer: http://stackoverflow.com/a/51569866
accepted answer: http://stackoverflow.com/a/51569866
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/90104743
favorite count: 0

http://stackoverflow.com/comment/89996632
type: QuestionComment
comment on: http://stackoverflow.com/q/51514077
score: 0
has text: Welcome to StackOverflow. However, your question is not clear. What does your linked code have to do with this question? Please explain more.
type: Comment

http://stackoverflow.com/comment/90171019
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51585286
has text: Try executing `sudo pip3 install --upgrade setuptools`, then do the same.

http://stackoverflow.com/q/51632468
favorite count: 0
has title: why xlwings suppresses logging to a file
has body: In my app.py module I set up a logger with console and file handlers like this: import logging logger = logging.getLogger('app') logger.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() file_handler = logging.FileHandler('gsam_log.txt') console_handler.setLevel(logging.INFO) file_handler.setLevel(logging.INFO) c_formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') f_formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') console_handler.setFormatter(c_formatter) file_handler.setFormatter(f_formatter) logger.addHandler(console_handler) logger.addHandler(file_handler) If I work in Python Console and I do: from app import logger it works as expected - printing both to console and the file. I would like to use this logger to log from my xlwings subs (decorated with @xw.sub). But for some reason the logs are only sent to console and not to the file. Below is the code from test.py module, which I import as UDF module via xlwings. from app import logger import xlwings as xw @xw.sub def test(): logger.debug('test') logger.info('test') logger.warning('test')
tagged with: python
tagged with: logging
type: AnsweredQuestion
score: 2
tagged with: xlwings
downvote count: 0
accepted answer: http://stackoverflow.com/a/51675571
type: Question
has answer: http://stackoverflow.com/a/51675571
upvote count: 2
answer count: 1

http://stackoverflow.com/q/51574580
answer count: 0
has comment: http://stackoverflow.com/comment/90238558
tagged with: image-processing
type: Question
has body: I'm trying to find the dominant color of an image such that the dominant color fits into some "region" of one of twelve pre-specified colors (red, orange, yellow, green, teal, blue, purple, pink, white, gray, black, brown). That is, I want to input an image and if, for example, the image is mainly yellow-green, then the program should output either yellow or green (depending on if it more green than yellow or more yellow than green). It seems that most people use k-means clustering to find the dominant color, but (if I am correct) these k regions don't really seem to be pre-specified. That is the number k is specified, but if I input k = 12, I don't think that the algorithm will necessarily divide the regions according to my color list. Are there any other ways to do this? I tried the following method (using PIL in Python): retrieve the histogram of the image and find the max values that correspond to the R, G, and B values (call them R1, G1, B1, respectively). Then find the color that is "closest" by finding the minimum Euclidean distance between the R1,G1,B1 and that of the R,G,B values from my palette list. This didn't seem to work so well because many of the colors retrieved were just gray and black, while the image itself didn't seem to have much gray nor much black in it, relative to the other colors. This program is being coded in Python. Is there another method to find the dominant color given a pre-specified palette?
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/90115030
tagged with: image
score: 0
has comment: http://stackoverflow.com/comment/90115003
tagged with: colors
type: UnansweredQuestion
has title: How to find the dominant color of an image with a palette of prespecified colors?
tagged with: python

http://stackoverflow.com/q/51547474
score: 3
has answer: http://stackoverflow.com/a/51548086
upvote count: 3
has body: I am trying to generate some random expressions in the form f(g(x)). I'd like to be able to replace g with something like sin(x) or x**2 and f with something like cos(x) or log(x). So I'd get something like sin(cos(x)) or log(x**2) (but randomized). The part of this task I'm having trouble with is replacing both an outer and inner function. Here's my code: import sympy from sympy import abc x = abc.x f = sympy.Function('f')(x) g = sympy.Function('g')(x) full=f.subs(x, g) newExpr = sympy.sin(x) newExpr2 = sympy.cos(x) print(full) replaced_inner = full.subs(g, newExpr) print(replaced_inner) both = replaced_inner.subs(f, newExpr2) print(both) full prints f(g(x)) so that works replaced_inner prints f(sin(x)) so that works as well both prints f(sin(x)) when I want it to print cos(sin(x)) I've tried using args[0] and f.func but haven't made progress. How can I replace both the inner and outer functions (and eventually more complex things like f(g(h(x))). I could simply create cos(sin(x)) but I want to do it using variables so I can randomize what function gets replaced.
type: Question
tagged with: sympy
accepted answer: http://stackoverflow.com/a/51548086
answer count: 1
downvote count: 0
favorite count: 0
has title: Replacing composed functions in Sympy
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/89941002
score: 0
has text: Sometimes it helps to double check the server ip is accesible. On a command line you can double check by using `ping <server ip>`
comment on: http://stackoverflow.com/q/51485828
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51498991
has answer: http://stackoverflow.com/a/51887290
score: 0
has body: I'am trying to get case attachment to save in local folder. I have problem with using attachment url to download it, each time server returns empty results and status code 200. This is a sample url I use (changed host and token) : https://example.fogbugz.com/default.asp?pg=pgDownload&amp;pgType=pgFile&amp;ixBugEvent=385319&amp;ixAttachment=56220&amp;sFileName=Log.7z&amp;sTicket=&amp;sToken=1234567890627ama72kaors2grlgsk I have tried using token instead of sToken but no difference. If I copy above url to chrome then it won't work either, but If I login to FogBugz (manuscript) and then try this url again then it works. So I suppose there are some security issues here. btw. I use python FogBugz api for this and save url using urllib urllib.request.urlretrieve(url, "fb/" + file_name)
answer count: 1
has comment: http://stackoverflow.com/comment/90903744
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90875897
has title: When saving FogBugz attachment, server always returns empty response (with some headers)
tagged with: fogbugz
tagged with: python
type: Question
linked to: http://stackoverflow.com/q/46521253
tagged with: fogbugz-api

http://stackoverflow.com/comment/89986299
comment on: http://stackoverflow.com/q/51508096
score: 1
type: Comment
has text: See [this answer](https://stackoverflow.com/a/10061143). You need to use a `UniqueConstraint` object.
type: QuestionComment

http://stackoverflow.com/a/51516522
score: 1
has body: You need two steps, as Python regular expressions are not powerful enough to do it in one go. re.findall(r'[\[\].\\,();~-]', re.sub(r'"(?:\\.|[^"\\])*"', '', s)) # =&gt; ['.', '(', ')', ';'] The inner re.sub deletes all double-quoted strings (ignoring escaped double quotes); then you can use re.findall to easily pick up what you want.
downvote count: 0
has comment: http://stackoverflow.com/comment/90003325
has comment: http://stackoverflow.com/comment/90001628
answers question: http://stackoverflow.com/q/51516361
type: Answer
upvote count: 1

for-loop
tags question: http://stackoverflow.com/q/51503850
tags question: http://stackoverflow.com/q/51568024
tags question: http://stackoverflow.com/q/51534605
tags question: http://stackoverflow.com/q/51521333
tags question: http://stackoverflow.com/q/51548878
tags question: http://stackoverflow.com/q/51627001
tags question: http://stackoverflow.com/q/51521291
tags question: http://stackoverflow.com/q/51615993
tags question: http://stackoverflow.com/q/51577748
tags question: http://stackoverflow.com/q/51502615
tags question: http://stackoverflow.com/q/51542543
tags question: http://stackoverflow.com/q/51501402
tags question: http://stackoverflow.com/q/51624320
tags question: http://stackoverflow.com/q/51502392
tags question: http://stackoverflow.com/q/51492335
tags question: http://stackoverflow.com/q/51576511
tags question: http://stackoverflow.com/q/51611160
tags question: http://stackoverflow.com/q/51578043
tags question: http://stackoverflow.com/q/51555288
tags question: http://stackoverflow.com/q/51608823
tags question: http://stackoverflow.com/q/51604147
tags question: http://stackoverflow.com/q/51582764
tags question: http://stackoverflow.com/q/51569748
tag name: for-loop
tags question: http://stackoverflow.com/q/51617624
tags question: http://stackoverflow.com/q/51556631
tags question: http://stackoverflow.com/q/51520114
tags question: http://stackoverflow.com/q/51626747
tags question: http://stackoverflow.com/q/51600013
tags question: http://stackoverflow.com/q/51567675
tags question: http://stackoverflow.com/q/51572991
tags question: http://stackoverflow.com/q/51553693
tags question: http://stackoverflow.com/q/51506897
tags question: http://stackoverflow.com/q/51639252
tags question: http://stackoverflow.com/q/51578126
tags question: http://stackoverflow.com/q/51487677
tags question: http://stackoverflow.com/q/51509829
tags question: http://stackoverflow.com/q/51626787
tags question: http://stackoverflow.com/q/51490114
tags question: http://stackoverflow.com/q/51625776
tags question: http://stackoverflow.com/q/51603684
tags question: http://stackoverflow.com/q/51522375
type: Tag
tags question: http://stackoverflow.com/q/51576862
tags question: http://stackoverflow.com/q/51518189
tags question: http://stackoverflow.com/q/51549363
tags question: http://stackoverflow.com/q/51598295
tags question: http://stackoverflow.com/q/51525385
tags question: http://stackoverflow.com/q/51618228
tags question: http://stackoverflow.com/q/51547898
tags question: http://stackoverflow.com/q/51573711
tags question: http://stackoverflow.com/q/51560738
tags question: http://stackoverflow.com/q/51516709
tags question: http://stackoverflow.com/q/51608043
tags question: http://stackoverflow.com/q/51527566
tags question: http://stackoverflow.com/q/51571680

http://stackoverflow.com/q/51638826
has comment: http://stackoverflow.com/comment/90242215
has comment: http://stackoverflow.com/comment/90251021
tagged with: python-unittest
has comment: http://stackoverflow.com/comment/90242129
tagged with: unit-testing
type: Question
has answer: http://stackoverflow.com/a/51638947
has title: Assert Equal an Object which has an Array within it
score: 0
answer count: 1
has body: My goal is to check the similarity of an object using unittesting in python. I have this kind of object class ImageModel(object): def __init__(self): self.data = data #this an array self.name = name self.path = path I have read that if you want to do test the similarity of an array self.assertEqual(arr1,arr2) you have to put .all() after each array. But I have to check the similarity of an object which has an array within it. For my case, it would be: self.assertEqual(ImageObj1, ImageObj2) But it always show that those object isn't similar, i assume the problem is at the ImageObj.data so, is there any way to assert equal an array within an object?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90093611
has text: Possible duplicate of [Using pywin32, what is the difference between Dispatch and DispatchEx?](https://stackoverflow.com/questions/18648933/using-pywin32-what-is-the-difference-between-dispatch-and-dispatchex)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51562092
score: 0

http://stackoverflow.com/q/51590263
tagged with: rpy2
tagged with: http://stackoverflow.com/tag/r
upvote count: 1
favorite count: 0
has body: I am trying to import a SPSS file into python through rpy2 using the following code. from rpy2.robjects import pandas2ri, r filename = 'x.sav' df = r('foreign::read.spss("%s", reencode = "cp1252", use.value.labels=TRUE, to.data.frame = TRUE)' % filename) I have missing values inside my file that I would like to keep. For example: df[361] #Returns R object with classes: ('factor',) mapped to: &lt;FactorVector - Python:0x0000000011657CC8 / R:0x0000000012DAE738&gt; [NA_integer_, NA_integer_, NA_integer_, NA_integer_, ..., NA_integer_, NA_integer_, NA_integer_, NA_integer_] print(df[361]) #Returns [1] &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; [2] &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; [3] &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; [4] Agree (2) Agree (2) &lt;NA&gt; &lt;NA&gt; [5] &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; &lt;NA&gt; 5 Levels: Strongly Agree (1) Agree (2) ... Strongly Disagree (5) However, when I perform a pandas2ri.ri2py conversion, it changes all NA_interger_ to integer value 1 and takes after the value label. df = pandas2ri.ri2py(df) df.iloc[:, 361] #Returns 1 Strongly Agree (1) 2 Strongly Agree (1) 3 Strongly Agree (1) 4 Strongly Agree (1) ... 13 Agree (2) 14 Agree (2) ... 19 Strongly Agree (1) 20 Strongly Agree (1) How can I stop prevent pandas2ri.ri2py() from automatically converting these NA_Integers_ ?
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: na
has title: (rpy2) pandas2ri.ri2py(df) converting NA_integer_ to integer 1
downvote count: 0
score: 1
type: Question

http://stackoverflow.com/q/51505795
favorite count: 0
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89989219
has comment: http://stackoverflow.com/comment/89981786
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89986366
tagged with: text
score: 1
has title: Python Tkinter: Scrolling two text boxes at the same time; lines get out of sync
tagged with: scroll
tagged with: scrollbar
type: Question
downvote count: 0
has body: I have a Text widget, textbox, where the user can type, and another Text widget, linenumbers, directly to the left of it which displays line numbers. I have it working, but with one problem: the more lines I create, the more the two Text widgets get out of sync when scrolled. Here's a gif showing what happens. And here's my code (scroll_both and update_scroll came from another StackOverflow thread): class MainGUI: def scroll_both(self, action, position, type=None): self.textbox.yview_moveto(position) self.linenumbers.yview_moveto(position) def update_scroll(self, first, last, type=None): self.textbox.yview_moveto(first) self.linenumbers.yview_moveto(first) self.scrollbar_y.set(first, last) def on_textbox_update(self, event): modified = self.textbox.edit_modified() if modified: #If the number of lines in the textbox has changed: if self.linecount != self.textbox.index("end").split('.')[0]: #Update textbox's linecount self.linecount = self.textbox.index("end").split('.')[0] # Clear the line count sidebar self.linenumbers.config(state="normal") self.linenumbers.delete(0.0, "end") # Fill it up again for LineNum in range(1, int(self.linecount)): self.linenumbers.insert(self.linenumbers.index("end"), str(LineNum)+"\n", "justifyright") if len(str(LineNum)) == 1: self.linenumbers.config(width=2) else: self.linenumbers.config(width=len(str(LineNum))) self.linenumbers.config(state="disabled") def __init__(self, master): self.master = master Grid.rowconfigure(master, 1, weight=1) Grid.columnconfigure(master, 2, weight=1) self.linenumbers = Text(master, width=2, borderwidth=0, takefocus=0, padx=6, fg="gray") self.linenumbers.config(font="TkTextFont") self.linenumbers.tag_configure("justifyright", justify="right") self.linenumbers.grid(row=0, column=1, rowspan=2, sticky=NSEW) self.textbox = Text(master, padx=6, borderwidth=0, wrap=NONE) self.textbox.config(font="TkTextFont") self.textbox.grid(row=0, column=2, rowspan=2, sticky=NSEW) self.textbox.bind("&lt;&lt;Modified&gt;&gt;", …
linked to: http://stackoverflow.com/q/16369470

http://stackoverflow.com/a/51639371
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90243342
downvote count: 0
has comment: http://stackoverflow.com/comment/90243517
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51639152
answers question: http://stackoverflow.com/q/51639152
has body: Pass infoval as a parameter to the function: def Animals(infoval): ...... ...... and then when calling the function pass in the different values for each button: def button2click(): Animals(1)
has comment: http://stackoverflow.com/comment/90243386

http://stackoverflow.com/comment/90039804
score: 0
type: AnswerComment
has text: Yea, I am ok with any increment as I just want to know how to increase it and then replace the old with new values and print the whole file with new values. Is it possible?
type: Comment
comment on: http://stackoverflow.com/a/51535918

http://stackoverflow.com/comment/90342119
type: Comment
has text: Found my error, it works. It appears that the `MultiDict` does not work for updating`SelectField` objects, from what I've observed so far.
type: AnswerComment
comment on: http://stackoverflow.com/a/51579212
score: 0

http://stackoverflow.com/q/51622712
accepted answer: http://stackoverflow.com/a/51623235
favorite count: 0
possible better answer: http://stackoverflow.com/a/65859504
tagged with: python
type: AnsweredQuestion
has body: Prologue: I am just moving first stesp in ansible, so please be patient Also: I read the answers at 'Ansible demands installing MySQL-python despite it was already installed' but my case is different because locally, on the control machine, is all perfect; thanks to this question I discovered that my problem was in the remote controlled machine. So my questions is the same but the question linked do not contains an answer to resolve my problem. I'm testing ansible from command line. For example, I succesfully can ping ~/.ssh$ ansible openvpn -C -m "ping" 192.168.1.225 | SUCCESS => { "changed": false, "ping": "pong" } I tried to launch an apt update. I am not sure if this is the right syntax for having the equivalent of apt-get update, but this is not the question I am using -C to see what ansible says to me when I ask to do a dry run. $ ansible openvpn -C -m "apt update-cache=yes" 192.168.1.225 | FAILED! => { "changed": false, "msg": "python-apt must be installed to use check mode. If run normally this module can auto-install it." } EDIT : As @Davide Maze suggested, it could be due to missing python-apt. So I checked, but _I have python-apt $ python -V Python 2.7.15rc1 $ pip list ... cut ... python-apt (1.6.2) ... cut ... $ which python /usr/bin/python My question is: why does ansible tell me that python-apt is not installed, and how to fix this?
has title: Ansible requires python-apt but it's already installed
upvote count: 17
type: Question
has answer: http://stackoverflow.com/a/51623235
linked to: http://stackoverflow.com/q/33458889
score: 17
has answer: http://stackoverflow.com/a/65859504
answer count: 2
tagged with: ansible
downvote count: 0

http://stackoverflow.com/comment/90115392
type: QuestionComment
comment on: http://stackoverflow.com/q/51551821
type: Comment
has text: Please edit your question to include a sample CSV file that reproduces this error. I ran your code on a CSV file I made up and it completed without error.
score: 0

http://stackoverflow.com/comment/90196792
type: Comment
comment on: http://stackoverflow.com/q/51615325
score: 0
has text: Please fix your code indentation.
type: QuestionComment

http://stackoverflow.com/q/51509289
has answer: http://stackoverflow.com/a/51509352
accepted answer: http://stackoverflow.com/a/51509352
has comment: http://stackoverflow.com/comment/89987568
has comment: http://stackoverflow.com/comment/89987621
tagged with: jython
answer count: 1
has comment: http://stackoverflow.com/comment/89987690
upvote count: 1
favorite count: 0
has title: VirtualEnv Python as Java PythonInterpreter in MacOS
tagged with: python
has body: I'm currently finding a way to get some output from a python script through Java. After finding jython, I used PythonInterpreter to send parameters and receive output I expect. My Code PythonInterpreter interpreter = new PythonInterpreter(); String fileUrlPath = "/Users/me/Desktop/"; String scriptName = "pythonScript"; interpreter.exec("import sys\n" + "import os \n" + "sys.path.append('" + fileUrlPath + "')\n"+ "from "+scriptName+" import * \n"); String funcName = "predictionFunction"; PyObject someFunc = interpreter.get(funcName); try { PyObject out = someFunc.__call__(new PyString(pathToImageFolder), new PyString(fileName)); System.out.println(out); } catch (PyException e) { e.printStackTrace(); } My Problem But whenever I launch my program, It shows, numpy module not found error. So I checked the python version and it showed 2.7.0 which is version of jython python interpreter. But all my python libraries has been installed in a Virtual environment in path path/to/vir/env/bin. So I need to change the interpreter of java PythonInterpreter function to the python I've installed in my virtual environment. is it possible? If so, really appreciate if someone can help.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89987604
downvote count: 0
score: 1
tagged with: java
type: Question

statistics
tags question: http://stackoverflow.com/q/51563711
tags question: http://stackoverflow.com/q/51536068
tags question: http://stackoverflow.com/q/51504535
tags question: http://stackoverflow.com/q/51637757
tags question: http://stackoverflow.com/q/51612755
tag name: statistics
tags question: http://stackoverflow.com/q/51526515
tags question: http://stackoverflow.com/q/51541985
tags question: http://stackoverflow.com/q/51594501
tags question: http://stackoverflow.com/q/51598038
tags question: http://stackoverflow.com/q/51487626
tags question: http://stackoverflow.com/q/51515165
tags question: http://stackoverflow.com/q/51615868
tags question: http://stackoverflow.com/q/51579073
tags question: http://stackoverflow.com/q/51622490
tags question: http://stackoverflow.com/q/51545659
tags question: http://stackoverflow.com/q/51548666
tags question: http://stackoverflow.com/q/51515423
tags question: http://stackoverflow.com/q/51532359
tags question: http://stackoverflow.com/q/51609299
type: Tag

http://stackoverflow.com/comment/90088033
has text: @Dyno I edited my question to explain the difference from the possible duplicate question.
comment on: http://stackoverflow.com/q/51559978
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/51632831
has body: Your algorithm seems to be O(n/log(n)) There are sqrt(n) passes through the outer loop. The inner loop is bounded by the number of primes which are less than sqrt(n). By the Prime Number Theorem this is asymptotically given by sqrt(n)/log(sqrt(n)). By the laws of logarithms this is equivalent to sqrt(n)/(0.5*log(n)) = 2*sqrt(n)/log(n). The overall complexity is thus O(sqrt(n)*2*sqrt(n)/log(n)) = O(2*n/log(n)) = O(n/log(n)) Needless to say, this isn't a very efficient way to check if n is prime. It is asymptotically little better than the O(n) naive check for divisibility by all numbers less than n.
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/51632183
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51632183
type: Answer

http://stackoverflow.com/comment/90538692
type: AnswerComment
has text: can we reduce the complexity of this logic df=pd.concat([pd.DataFrame({'start': pd.date_range(row.start, row.end, freq='AS'),'series_id': row.series_id}, columns=['start', 'id']) for i, row in df.iterrows()], ignore_index=True) this logic extract the start date and end for id.
type: Comment
comment on: http://stackoverflow.com/a/51600796
score: 0

http://stackoverflow.com/a/51621878
score: 0
answers question: http://stackoverflow.com/q/51621823
type: Answer
has comment: http://stackoverflow.com/comment/90209298
has body: From the docs: Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero. Note that these methods round the values to the given number of decimal places (i.e. like the round() function) and not significant digits. In your case, round(41.7777777777776 - 41.777, 3) != 0.0.

http://stackoverflow.com/a/51629674
accepted answer of: http://stackoverflow.com/q/51629480
answers question: http://stackoverflow.com/q/51629480
has comment: http://stackoverflow.com/comment/90229983
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90224713
has body: Each LSTM cell produces 100 outputs, so after you execute tf.nn.dynamic_rnn you need to flatten that output. I'd rather use reshaped_outputs = tf.layers.Flatten()(outputs) after this line: outputs, states = tf.nn.dynamic_rnn(cell, x_p, dtype = tf.float32, time_major = True) instead of this line: reshaped_outputs = tf.reshape(outputs, [-1,100]) Hope it helps :) EDIT: I didn't notice that you used time_major = True. I have changed your code a bit, with time_major = False, because it's simpler to use. I assume that you want to predict nb_steps outputs. code: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt x = np.linspace(0,30.,500) y = x*np.sin(x) + 2*np.sin(5*x) nb_steps = 20 def load_batch(batch_size = 32): x_b = np.zeros((batch_size, nb_steps)) y_b = np.zeros((batch_size, nb_steps)) inds = np.random.randint(0, 479, (batch_size)) for i,ind in enumerate(inds): x_b[i] = x[ind:ind+nb_steps] y_b[i] = y[ind+1:ind+nb_steps+1] return x_b, y_b adam = tf.train.AdamOptimizer layers = tf.layers dense = layers.dense lstm = tf.contrib.rnn.LSTMCell batch_size = 64 with tf.variable_scope('data'): x_p = tf.placeholder(tf.float32, shape = [None, nb_steps], name = 'x') x_rnn = tf.expand_dims(x_p, 2) # batch, steps, features y_p = tf.placeholder(tf.float32, shape = [None, nb_steps], name = 'labels') with tf.variable_scope('network'): cell = lstm(num_units = 100) outputs, states = tf.nn.dynamic_rnn(cell, x_rnn, dtype = tf.float32, time_major = False) reshaped_outputs = tf.layers.Flatten()(outputs) projection = dense(reshaped_outputs, nb_steps, activation = None, name = 'projection') with tf.variable_scope('training'): loss = tf.reduce_mean(tf.square(projection - y_p)) train_lstm = adam(1e-3).minimize(loss) epochs = 1000 batch_size = 64 f, ax = plt.subplots(2,1) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) mean_loss = 0. for epoch in range(1,epochs+1): x_b,y_b = load_batch(batch_size) batch_loss,_ = sess.run([loss, train_lstm], feed_di…
type: Answer
has comment: http://stackoverflow.com/comment/90225724
has comment: http://stackoverflow.com/comment/90230877

http://stackoverflow.com/comment/91749370
score: 0
has text: https://stackoverflow.com/questions/21888546/regularly-spaced-orthogonal-grid-delaunay-triangulation-computing-the-paraboloi
comment on: http://stackoverflow.com/q/51591212
type: QuestionComment
type: Comment

transcrypt
tags question: http://stackoverflow.com/q/51621205
tag name: transcrypt
type: Tag
tags question: http://stackoverflow.com/q/51527163

http://stackoverflow.com/q/51598038
has comment: http://stackoverflow.com/comment/90162345
downvote count: 0
favorite count: 0
tagged with: statistics
has body: Correct me or ask me for informations if it is unclear, I try to be precise as possible. I have pandas series / a list , with values with a range between 1 and 30. and a class list with the same steps. Now I want to do a cross level counting of the list for my classes. In the Picture below I described what I want to do. What is the best way to loop through my list and count the number of occurence in the classes ? import random import matplotlib.pyplot as plt import numpy as np def Rand(start, end, num): res = [] for j in range(num): res.append(random.randint(start, end)) return res s=Rand(-1,20,50) #number of classes classlist=np.linspace(1,30,40) for yc in classlist: plt.axhline(y=yc) plt.plot(s)
tagged with: count
tagged with: python
has title: level crossing counting with python
has comment: http://stackoverflow.com/comment/90162438
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/90162357
score: 1
type: Question

http://stackoverflow.com/comment/90130971
type: AnswerComment
has text: The data is confidential so uploading it on web may be problem
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51580854

http://stackoverflow.com/q/51628357
accepted answer: http://stackoverflow.com/a/51628825
tagged with: python
tagged with: dlib
type: AnsweredQuestion
upvote count: 1
tagged with: computer-vision
type: Question
tagged with: opencv
has title: How do I subtract two images from each other using python and opencv?
score: 1
tagged with: image-processing
has answer: http://stackoverflow.com/a/51628825
has body: The objective here is to subtract the mouth from the original image of the face. Now I know how to crop the mouth using dlib and facial landmarks (which is what this script does). The question is how do I modify the original image such that it remains entirely the same except without the mouth? Basically I want to cut it out. predictor_path = "/home/victor/facial-landmarks/shape_predictor_68_face_landmarks.dat" faces_folder_path = "/home/victor/TryImage/" detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(predictor_path) i = 0 for f in glob.glob(os.path.join(faces_folder_path, "*.jpg")): print("Processing file: {}".format(f)) img = cv2.imread(f) dets = detector(img, 1) print("Number of faces detected: {}".format(len(dets))) for k, d in enumerate(dets): print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format( k, d.left(), d.top(), d.right(), d.bottom())) shape = predictor(img, d) i += 1 xmouthpoints = [shape.part(x).x for x in range(48,68)] ymouthpoints = [shape.part(x).y for x in range(48,68)] maxx = max(xmouthpoints) minx = min(xmouthpoints) maxy = max(ymouthpoints) miny = min(ymouthpoints) pad = 10 filename = os.path.splitext(os.path.basename(f))[0] crop_image = img[(miny-pad):(maxy+pad),(minx-pad):(maxx+pad)] img = cv2.subtract(img, crop_image) imshow(crop_image, 1) imshow(new_image, 1) cv2.imwrite(str(filename) + '.jpg',crop_image) Using cv2.subtract yields the following error: error: OpenCV(3.4.1) /io/opencv/modules/core/src/arithm.cpp:659: error: (-209) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function arithm_op I've also thought about using image subtraction, is that possible? Even if it will be some black or white box or circle instead of the mouth, it'd be perfect. Note: I would use GIMP or Photoshop, but I'm dealing with thousands of selfies, so it's not really an option. Thank you : ) The image I am using…
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90072234
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51536478
score: 0
has text: Have done that! Thanks! https://stats.stackexchange.com/questions/359297/simulation-of-t-copula-in-python

http://stackoverflow.com/a/51495542
accepted answer of: http://stackoverflow.com/q/51493768
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: If your question is if you have to literally type every letter 25 times, than no. Ignored 'lijst' as I don't think it is relevant for your question. You could simply do: letters = ['a', 'j', 'd'] #The letters you want here aa = [] for l in letters: aa += [l]*25 alfascii = ['097','98','99','100','101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117','118','119','120','121','122'] alfascii = aa[:len(alfascii)] Or if you don't want the helper aa list: letters = ['a', 'j', 'd'] #The letters you want here alfascii = ['097','98','99','100','101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117','118','119','120','121','122'] for i, l in enumerate(alfascii): letter_index = round((i+1)/25 - 0.5) alfascii[i] = letters[letter_index]
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51493768

http://stackoverflow.com/q/51525362
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51525648
score: 0
has title: Pandas Using .str on a dataframe filtered with .loc
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51525648
upvote count: 1
downvote count: 1
type: Question
has body: I am trying to pad the float(64) values with some zeros in a column called date_of_birth within a dataframe called drugs_tall. date_of_birth contains some NA. This was my initial idea: drugs_tall.loc[drugs_tall['date_of_birth'].isnull() == False, ['date_of_birth']] = drugs_tall.loc[drugs_tall['date_of_birth'].isnull() == False, ['date_of_birth']].astype('int').astype('str').str.zfill(6) However, this generates the error AttributeError: 'DataFrame' object has no attribute 'str' I got around this by simply doing (this works): drugs_tall.loc[drugs_tall['date_of_birth'].isnull() == False, ['date_of_birth']] = drugs_tall.loc[drugs_tall['date_of_birth'].isnull() == False, ['date_of_birth']].astype('int').astype('str') drugs_tall['date_of_birth'] = drugs_tall['date_of_birth'].str.zfill(6) Note that it is not possible to go directly to: drugs_tall['date_of_birth'] = drugs_tall['date_of_birth'].str.zfill(6) As this will generate the error: AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas It is also not possible to change the data type without using .loc selection: drugs_tall['date_of_birth'].astype('int').astype('str') As this will give: ValueError: Cannot convert non-finite values (NA or inf) to integer Am I going about this in a strange way or misunderstanding how the dataframes work? I know my two line solution is reasonably brief, but I don't understand what makes the two line solution different from my initial idea. Thank you

http://stackoverflow.com/a/51541582
type: Answer
answers question: http://stackoverflow.com/q/51540331
score: 0
has body: @pault has already given an awsome answer using regex and split and concat_ws inbuilt functions Heres an alternative of doing it simple using udf function as from pyspark.sql.functions import col, udf from pyspark.sql.types import ArrayType, StringType @udf(ArrayType(StringType())) def splitUdf(x): splitted = x.split('_') return [splitted[0], '_'.join(splitted[1:])] df.withColumn('city', splitUdf(col('city')))\ .select(col('ranking'), col('coordenate'), col('city')[0].alias('city'), col('city')[1].alias('code'))\ .show() which should give you +-------+----------+-------+---------------+ |ranking|coordenate| city| code| +-------+----------+-------+---------------+ | 1| 1.8|newyork| 3434_north| | 4| 2.6| la|432432432_south| | 6| 3.3| boston| 234324_east| | 8| 4.1|detroit| 6757_west| | 2| 5.7| miami| 133123_north| | 3| 6.2|atlanta| 093394_west| | 1| 6.1|houston| 87342_east| +-------+----------+-------+---------------+ I hope the answer is helpful

http://stackoverflow.com/q/51528643
favorite count: 0
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/51528720
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I have a dataframe with the below dictionaries within a single list in every row and per row, the list are different sizes with they are of different sizes as below: ID unnest_column 1 [{'abc': 11, 'def': 1},{'abc': 15, 'def': 1}, {'abc': 16, 'def': 1}, {'abc': 17, 'def': 1}, {'abc': 18, 'def': 1, 'ghi': 'abc'}, {'abc': 23, 'def': 'xxx', 'def': 1}, {'abc': 23, 'def': 'xxx', 'def': 2}, {'abc': 23, 'def': 'xxx', 'def': 4}] 2 [{'abc': 11, 'def': 1}] How do I unpack the dictionaries in the list and make the key values columns? new df potentially, not sure exactly how it will look, just need keys into columns: id abc def ghi 1 2 3 abc
type: Question
has answer: http://stackoverflow.com/a/51528720
tagged with: pandas
downvote count: 0
answer count: 1
has title: How to unpack multiple dictionary objects inside list within a row of dataframe?

http://stackoverflow.com/comment/90124527
comment on: http://stackoverflow.com/q/51579478
score: 0
type: Comment
has text: @MartijnPieters It's not a duplicate since this question contains the specific constraint of *not* reading / writing the whole file content each time an element is added. None of the answers addresses this issue.
type: QuestionComment

http://stackoverflow.com/comment/90018574
type: Comment
type: QuestionComment
has text: Do you mean integer series, like in IQ tests? If so, you will not be successful with RNNs. Its one of those examples, which are used to show, that AI models are quite stupid
comment on: http://stackoverflow.com/q/51524005
score: 0

http://stackoverflow.com/q/51550838
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
score: 2
upvote count: 2
tagged with: selenium
tagged with: web-scraping
tagged with: scrapy
type: Question
has answer: http://stackoverflow.com/a/51558094
has body: I am new to Python (Selenium, Scrapy, etc.) &amp; Web-Scraping in general, but I am pretty familiar with other languages such as Java , so please forgive me if I am missing something very simple! My end goal is to visit a page, sit there for around 10 seconds and then close the browser and repeat. However, I am trying to practice rotating my IP address via proxy with each request. I have been able to accomplish visiting the page but when I try to throw the rotating Proxy in the mix, I get a long connection error that I can't seem to figure out that seems to include a bunch of CSS. Complete Code Snippet The issue seems to be caused by the second line in the try-block where the driver is trying to access the website import scrapy import requests from selenium import webdriver from selenium.webdriver.common.proxy import Proxy, ProxyType from scrapy.http import Request from lxml.html import fromstring from itertools import cycle class VisitPageSpider(scrapy.Spider): name = 'visitpage' allowed_domains = ['books.toscrape.com'] def start_requests(self): test_url = 'http://books.toscrape.com' proxies = self.get_proxies() proxy_pool = cycle(proxies) prox = Proxy() prox.proxy_type = ProxyType.MANUAL view_count = 0 url = 'https://httpbin.org/ip' for i in range(1, 11): proxy = next(proxy_pool) prox.http_proxy = proxy prox.socks_proxy = proxy prox.ssl_proxy = proxy capabilities = webdriver.DesiredCapabilities.INTERNETEXPLORER prox.add_to_capabilities(capabilities) print("Request #%d" % i) try: self.driver = webdriver.Ie(desired_capabilities=capabilities) self.driver.get(test_url) view_count += 1 time.sleep(10) self.driver.quit() except: print("Skipping. Connection error") print('Total New Views ' + view_count) yield Request(test_url, callback=self.visit_page) def visit_page(self, response): pass def get_proxies(self): url = 'https://free-proxy-list.net/' response = requests.get(url) parser = fromstring(response.text) proxies = set() for i in parser.xpath('//tbody/tr')[:10]: if i…
downvote count: 0
answer count: 1
has title: Unable to connect using selenium driver.get()

http://stackoverflow.com/q/51540167
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51540341
has body: Want to plot some data from a pandas dataframe Relevant info df13.head() Country HDI 1 Norway 0.949 2 Australia 0.939 3 Switzerland 0.939 4 Germany 0.926 5 Denmark 0.925 df13.shape &gt;&gt;&gt; (169, 2) df13['HDI'].dtype &gt;&gt;&gt; dtype('float64') len(df13['Country'].unique()) &gt;&gt;&gt; 169 So there's no duplicate Country Names Doing a plot this way creates a plot without the Country names df13.plot.barh(figsize=(20,20), use_index=False) Trying to assign the x,y to the plot throws an error, doing it with HDI column only the digits column throws this error df13.plot(kind='barh', x='HDI') TypeErrorTraceback (most recent call last) &lt;ipython-input-77-c7ec3932c7c4&gt; in &lt;module&gt;() ----&gt; 1 df13.plot(kind='barh', x='HDI') c:\python27\lib\site-packages\pandas\plotting\_core.pyc in __call__(self, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds) 2939 fontsize=fontsize, colormap=colormap, table=table, 2940 yerr=yerr, xerr=xerr, secondary_y=secondary_y, -&gt; 2941 sort_columns=sort_columns, **kwds) 2942 __call__.__doc__ = plot_frame.__doc__ 2943 c:\python27\lib\site-packages\pandas\plotting\_core.pyc in plot_frame(data, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds) 1975 yerr=yerr, xerr=xerr, 1976 secondary_y=secondary_y, sort_columns=sort_columns, -&gt; 1977 **kwds) 1978 1979 c:\python27\lib\site-packages\pandas\plotting\_core.pyc in _plot(data, x, y, subplots, ax, kind, **kwds) 1802 plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds) 1803 -&gt; 1804 plot_obj.generate() 1805 plot_obj.draw() 1806 return plot_obj.result c:\python27\lib\site-packages\pandas\plotting\_core.pyc in generate(self) 256 …
tagged with: pandas
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51540341
favorite count: 0
has title: pandas plotting bug TypeError: Empty 'DataFrame': no numeric data to plot

http://stackoverflow.com/a/51541290
downvote count: 0
score: 42
has body: Updated. You can get output of profiler using io.StringIO() and save it into file. Here is an example: import cProfile import pstats import io def my_func(): result = [] for i in range(10000): result.append(i) return result pr = cProfile.Profile() pr.enable() my_result = my_func() pr.disable() s = io.StringIO() ps = pstats.Stats(pr, stream=s).sort_stats('tottime') ps.print_stats() with open('test.txt', 'w+') as f: f.write(s.getvalue()) Run our script and open test.txt. You will see readable result: 10002 function calls in 0.003 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.002 0.002 0.003 0.003 /path_to_script.py:26(my_func) 10000 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} Also I can recommend to use dump_stats + pstats.Stats. Here is an example how to use it. Structure of files: # test_ex.py - just a small web app import cProfile import json from functools import wraps from flask import Flask from example.mod1 import func1 from example.mod2 import func2 app = Flask(__name__) # profiling decorator def profiling(): def _profiling(f): @wraps(f) def __profiling(*rgs, **kwargs): pr = cProfile.Profile() pr.enable() result = f(*rgs, **kwargs) pr.disable() # save stats into file pr.dump_stats('profile_dump') return result return __profiling return _profiling # demonstration route with profiler @app.route('/test') @profiling() def test(): counter = func1() dict_data = func2() result = dict() for key, val in dict_data.items(): result[key] = val + counter return json.dumps(result) if __name__ == '__main__': app.run(debug=True, port=8083) example package - let's imagine that this is some kind of application logic. # example.mod1 def func1(): counter = 0 for i in range(100000): counter += i return counter # example.mod2 def func2(): res = dict() for i in range(300000): res['key_' + str(i)] = i return res Now let's run server(python…
upvote count: 42
answers question: http://stackoverflow.com/q/51536411
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51536411

http://stackoverflow.com/comment/90196761
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51615332
has text: I think you misunderstand the question

http://stackoverflow.com/comment/90130371
score: 0
type: Comment
type: AnswerComment
has text: Thanks so much. I realized the loss function was dealing with classification so it wasn't compatible. I was looking for the right loss function to deal with regression. Thanks so much!
comment on: http://stackoverflow.com/a/51578138

http://stackoverflow.com/a/51653132
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51638963
upvote count: 2
has body: Try to close Details modal popup on each iteration: wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.CngMb g-raised-button.bZEQvc"))).click() for item in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".VkpGBb .dbg0pd div"))): item.click() name = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,"div.xpdopen div.SPZz6b span"))) print(name.text) close = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "QU77pf"))) driver.execute_script("arguments[0].click();", close)
accepted answer of: http://stackoverflow.com/q/51638963
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90124646
comment on: http://stackoverflow.com/q/51574060
score: 0
has text: The solutions provided are very complicated, I'm looking for something really simple. The comment has a word limitation, so I've updated the question again.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90237872
type: Comment
score: 0
has text: The main assumption is modern look. Examples from wxGlade looks like win98 style. As I said it will be large project with many options, buttons, real-time graphs. -> OR -> It is possible to create custom looks in wxGlade?
comment on: http://stackoverflow.com/a/51635584
type: AnswerComment

http://stackoverflow.com/comment/90106777
comment on: http://stackoverflow.com/q/51570220
score: 0
type: Comment
type: QuestionComment
has text: Did the `sudo` run without a password or `askpass`? If it did then the `python3` could be running under `root`, so an ordinary user won't be able to kill it.

http://stackoverflow.com/comment/90030870
type: Comment
type: QuestionComment
has text: a = input('Enter your name please: ')
comment on: http://stackoverflow.com/q/51531565
score: 0

http://stackoverflow.com/comment/89968380
type: Comment
type: QuestionComment
has text: Appending to a pre-existing file is trivial, there isn't a method built in `pandas` to do this using `to_csv`
comment on: http://stackoverflow.com/q/51499948
score: 0

http://stackoverflow.com/comment/89960218
type: AnswerComment
has text: Won't your code example break when trying to create the Child's `__init__` method because `arg2` will be appended to the base class' argument list, hence making a non-default argument follow a default argument (`opt_arg4`)?
type: Comment
comment on: http://stackoverflow.com/a/51495186
score: 1

http://stackoverflow.com/comment/90211153
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51606692
has text: Including removing the single-quotes in the assignment to `polygon`? If so, the next step is to add `set -x` to the beginning of the script, so that it prints commands as it runs them. Note that it may use unexpected quoting/escaping when it prints commands -- it prints *something equivalent to* what's being executed, and there are often many equivalent ways to quote/escape a command, and it may print a different one from what you expected. But if it prints something not equivalent to what you expected, then that's an indication of where the problem is.
type: Comment

http://stackoverflow.com/q/51630571
has comment: http://stackoverflow.com/comment/90225343
downvote count: 0
favorite count: 0
has body: I am trying to scrape a website in which the request headers are having some new (for me) attributes such as :authority, :method, :path, :scheme. {':authority':'xxxx',':method':'GET',':path':'/xxxx',':scheme':'https','accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8','accept-encoding':'gzip, deflate, br','accept-language':'en-US,en;q=0.9','cache-control':'max-age=0',GOOGLE_ABUSE_EXEMPTION=ID=0d5af55f1ada3f1e:TM=1533116294:C=r:IP=182.71.238.62-:S=APGng0u2o9IqL5wljH2o67S5Hp3hNcYIpw;1P_JAR=2018-8-1-9', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0(WindowsNT6.1;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/68.0.3440.84Safari/537.36', 'x-client-data': 'CJG2yQEIpbbJAQjEtskBCKmdygEI2J3KAQioo8oBCIKkygE=' } I tried passing them as headers with http request but ended up with error as shown below. ValueError: Invalid header name b':scheme' Any help would be appreciated on understanding and guidance on using them in passing request. EDIT: code added import requests url = 'https://www.google.co.in/search?q=some+text' headers = {':authority':'xxxx',':method':'GET',':path':'/xxxx',':scheme':'https','accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8','accept-encoding':'gzip, deflate, br','accept-language':'en-US,en;q=0.9','cache-control':'max-age=0','upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0(WindowsNT6.1;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/68.0.3440.84Safari/537.36', 'x-client-data': 'CJG2yQEIpbbJAQjEtskBCKmdygEI2J3KAQioo8oBCIKkygE=' } response = requests.get(url, headers=headers) print(response.text)
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51630703
has comment: http://stackoverflow.com/comment/90225589
upvote count: 2
possible better answer: http://stackoverflow.com/a/51630830
accepted answer: http://stackoverflow.com/a/51630703
answer count: 2
has answer: http://stackoverflow.com/a/51630830
tagged with: web-scraping
tagged with: python-requests
has comment: http://stackoverflow.com/comment/90225311
tagged with: http
has title: HTTP headers - Requests - Python
has comment: http://stackoverflow.com/comment/90225607
type: AnsweredQuestion
score: 2

http://stackoverflow.com/a/51611111
has body: Although already answered by others, the following might give you some more idea: dic={'a':1, 'b':2, 'c':3} print (dic.keys) Output &lt;built-in method keys of dict object .... print (dic.keys()) Output dict_keys(['a', 'b', 'c']) The same applies to the dic.values. Hope you got your answer.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51610932

http://stackoverflow.com/a/51540536
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51539056
has body: Instead of storing this complex json in redis, It needs to be stored as piece by piece using the redis data structure. While storing in this way keep in your mind the query which need to be executed at the time of retrieve data. This will bring you to the properly use of different redis data structure to minimise the query execution time.

http://stackoverflow.com/q/51622922
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/56501618
has comment: http://stackoverflow.com/comment/90216019
has comment: http://stackoverflow.com/comment/120521793
has comment: http://stackoverflow.com/comment/99621922
has title: Prediction of Failure using Time series data
type: Question
tagged with: time-series
has comment: http://stackoverflow.com/comment/99651373
has comment: http://stackoverflow.com/comment/90212080
has comment: http://stackoverflow.com/comment/99651290
has comment: http://stackoverflow.com/comment/90228229
has comment: http://stackoverflow.com/comment/99621915
has comment: http://stackoverflow.com/comment/90250053
score: 0
tagged with: pandas
tagged with: predictive
answer count: 1
has body: I am using Python and Pandas. I am working on a predictive maintenance project where my intention is to predict the probability of a failure which will occur in a given time period, say 4-6 hours. I have preprocessed the data and reduced it to the following: The dataset has 4 attributes, Start time, end time, duration of the event(Which is the difference in start and end time) and fourth attribute being event which is a fail or not fail. (1 being Fail and 0 Being not fail) Sample data is as follows: START_TIME END_TIME DURATION_MINUTES EVENT 2/15/2018 2:32 2/15/2018 2:32 0.566666667 0 2/15/2018 2:32 2/15/2018 2:33 0.916666667 0 2/15/2018 2:33 2/15/2018 2:33 0.116666667 1 2/15/2018 2:33 2/15/2018 2:35 1.283333333 0 2/15/2018 2:35 2/15/2018 2:35 0.083333333 0 2/15/2018 2:35 2/15/2018 2:35 0.166666667 0 2/15/2018 2:35 2/15/2018 2:35 0 0 I have about 120000 data instances. Can anybody let me know how I can visualize and predict at what probability a Failure (EVENT=1) will occur on any given day (Time frame of 4 hours)
type: UnansweredQuestion

http://stackoverflow.com/a/51590001
type: Answer
has body: As a solution for original execfile(), From this answer, if modify the one line: execfile(config_file_path) to execfile(config_file_path, globals()) then it will work as expected.
has comment: http://stackoverflow.com/comment/90145421
has comment: http://stackoverflow.com/comment/90147182
answers question: http://stackoverflow.com/q/51588879
score: 0

http://stackoverflow.com/comment/90234912
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51633987
has text: `not allowed by server configuration` either FB thinks this folder is not local, but a network shared one, or more probably you have to edit `firebird.conf` file and to enlist that folder as enable for databases // `host='0.0.0.0'` shouldn't it be localhost AKA 127.0.0.1 ? are "python module" and "firebird docker" on same PC or different ones?

linux-mint
type: Tag
tag name: linux-mint
tags question: http://stackoverflow.com/q/51578944

http://stackoverflow.com/a/51540691
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51540659
upvote count: 1
type: AcceptedAnswer
has body: new_df = df_copy['genres'].str.split(',',expand = True)
type: Answer
accepted answer of: http://stackoverflow.com/q/51540659

http://stackoverflow.com/comment/90140779
type: Comment
score: 0
type: AnswerComment
has text: @Thanks for the explanation but how do I fix it ?is there a way to add a workaround?I would like to see `>>>>>>>` in the mail body
comment on: http://stackoverflow.com/a/51587803

http://stackoverflow.com/q/51598961
has answer: http://stackoverflow.com/a/51599021
accepted answer: http://stackoverflow.com/a/51599021
type: Question
upvote count: 2
tagged with: function
has body: Please consider this function that accepts two arguments: series and categorical_values. Its goal is to get a series, make it categorical, and then print each element of the original series alongside the categorized corresponding element. However, if the categorical_values is already passed to the function as an input, the categorization stage is skipped and the function simply prints the pairs of the passed series and categorical_values. def my_function(series, categorical_values = None): if categorical_values: #meant to mean "if this argument is passed, just use it" categorical_values = categorical_values else: #meant to mean "if this argument is not passed, create it" categorical_values= pd.qcut(series, q = 5) for i,j in zip(series, categorical_values): print(i, j) However, passing categorical_values in the following: my_function(series, pd.qcut(series, q = 5)) leads to: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). The code line where this error results from is the very first line: if categorical_values: What is the proper way to check if a function argument has been passed or is not?
answer count: 1
tagged with: pandas
favorite count: 0
tagged with: python-3.x
downvote count: 0
tagged with: python
score: 2
has title: How to check if a function input is given or not?
type: AnsweredQuestion

http://stackoverflow.com/q/51580617
tagged with: docker
upvote count: 1
tagged with: tox
answer count: 1
has comment: http://stackoverflow.com/comment/90132009
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: jenkins
has body: I am trying to setup a Jenkins pipeline which runs tox inside a docker container. There is a known issue that shebang lines get very long inside Jenkins, and two solutions are proposed. The first is to use --workdir to select a shorter path. This option works in principle, but I loose the automatic unique path-names per project from Jenkins. I would thus prefer to use the second option, TOX_LIMITED_SHEBANG. Unfortunately, that seems to fail with the following error when the package under test is supposed to be installed: FileNotFoundError: [Errno 2] No such file or directory: "b'/bin/sh'": "b'/bin/sh'". I have verified that /bin/sh is in fact available in the docker container. The Jenkinsfile looks as follows: node("docker") { // burnpanck/tox-base contains tox and many python versions docker.image('burnpanck/tox-base').inside { checkout scm stage('Matrix-test using Tox') { // verify that /bin/sh exists sh 'ls -al /bin' // the following does not work sh 'TOX_LIMITED_SHEBANG=1 tox -vv' // the following works // sh 'tox --workdir=/var/jenkins_home/tox' } } } Tox is version 3.1.2 and runs under python 3.6 (the docker image is generated from this Dockerfile). What surprises me a little is the "b'/bin/sh'" coming from str-ing a bytes instance. Could it be that tox is in fact trying to run a program by the name sh' in the path b'/bin? The tox.ini in use simply calls pytest: [tox] envlist = py36 [testenv] recreate = True commands = pytest The full backtrace from tox (Jenkins console output) is the following: py36 create: /var/jenkins_home/workspace/_debug_jenkins-long-shebang-L7UHBNCVPSOBSTKZ7COPFJBJLWR5XZXFIAD7TBGC4WQLVDLZYVQQ/.tox/py36 py36 inst: /var/jenkins_home/workspace/_debug_jenkins-long-shebang-L7UHBNCVPSOBSTKZ7COPFJBJLWR5XZXFIAD7TBGC4WQLVDLZYVQQ/.tox/dist/test_model-0.dev20180717.zip ERROR: invocation failed (errno 2), args: [b'/bin/sh', '/var/jenkins_home/workspace/_debug_jenkins-long-shebang-L7UHBNCVPSOBSTKZ7COPFJBJLWR5XZXFIAD7TBGC4WQLVDLZYVQQ/.tox/py36/bin/pip…
has comment: http://stackoverflow.com/comment/90154363
has comment: http://stackoverflow.com/comment/90129631
has answer: http://stackoverflow.com/a/51921192
accepted answer: http://stackoverflow.com/a/51921192
has title: `/bin/sh` not found in tox within Jenkins inside docker
type: Question
score: 1

http://stackoverflow.com/q/51598111
has title: Print exactly as it is without escaping any characters
has body: I want to print {alias fmtime='find . -type f -printf "%T+\t%p\n" | sort'} exactly. I don't want to escape any characters. Is there a function that prints exactly anything we give it without having to escape any special characters?
score: 0
has answer: http://stackoverflow.com/a/51598165
has comment: http://stackoverflow.com/comment/90162220
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51598165
type: Question
answer count: 1

http://stackoverflow.com/a/51516763
score: 2
has comment: http://stackoverflow.com/comment/90002245
has comment: http://stackoverflow.com/comment/90002224
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: import re string = '100000|^104,500|^^0^0^0^0^0^0^0|^^^^^^^^^412824|103000|103000|103000|103000^^' answer = sum(map(int, re.search(r'\^{9}(.+)\^\^', string).group(1).split('|'))) answer: 824824
accepted answer of: http://stackoverflow.com/q/51516628
upvote count: 2
answers question: http://stackoverflow.com/q/51516628

http://stackoverflow.com/comment/90205867
score: 0
comment on: http://stackoverflow.com/q/51617857
type: Comment
type: QuestionComment
has text: I found the issue, it is happening because of `loss='sparse_categorical_crossentropy'`. Changing it to `loss='categorical_crossentropy'` fixed the issue.

http://stackoverflow.com/comment/90091844
type: QuestionComment
type: Comment
has text: @Aran-Fey That answer is *10 years old* and has a lot of Python 2 baggage that is irrelevant here.
comment on: http://stackoverflow.com/q/51562280
score: 0

http://stackoverflow.com/q/51581390
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90128104
has title: Appending to a non existing nested defaultdict entry
has answer: http://stackoverflow.com/a/60685097
has comment: http://stackoverflow.com/comment/90128007
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90128224
has comment: http://stackoverflow.com/comment/90128369
has comment: http://stackoverflow.com/comment/90128067
score: 0
has body: I'm creating a tiny logger package like so: from collections import defaultdict nested_dict = lambda: defaultdict(nested_dict) logger = nested_dict() I can then use it in any script to create nested entries like so: from utils.logger import logger logger["some"]["key"] = 1 However I want to be able to call the append method as well to then automatically create the keys and adding the first entry from utils.logger import logger logger["some"]["key"].append(1) This does not work and, obviously, throws the following error: AttributeError: 'collections.defaultdict' object has no attribute 'append' I'm not quite sure how to extend my logger in such a way to handle this feature without breaking the simple API/usage. Any ideas? In other words, I want my logger to infer that it needs to create a list as the value for that key.
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90128184

http://stackoverflow.com/comment/90216957
comment on: http://stackoverflow.com/a/51626068
type: Comment
has text: Got it, accessing the string starting from the 0th index to the 0th index gives a whitespace, but shouldn't a string in which string[0:0] is accessed, give a 'None' as the result?? Why the whitespace?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90016648
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51502808
type: Comment
has text: Yes, the xml is too large to show, hence i only showed the tags that were relevant.

pyqt5
tags question: http://stackoverflow.com/q/51522463
type: Tag
tags question: http://stackoverflow.com/q/51487893
tags question: http://stackoverflow.com/q/51566884
tags question: http://stackoverflow.com/q/51513102
tags question: http://stackoverflow.com/q/51549534
tags question: http://stackoverflow.com/q/51490917
tags question: http://stackoverflow.com/q/51544077
tags question: http://stackoverflow.com/q/51560196
tags question: http://stackoverflow.com/q/51495091
tags question: http://stackoverflow.com/q/51488701
tags question: http://stackoverflow.com/q/51559628
tags question: http://stackoverflow.com/q/51576848
tags question: http://stackoverflow.com/q/51535166
tags question: http://stackoverflow.com/q/51582044
tags question: http://stackoverflow.com/q/51578944
tags question: http://stackoverflow.com/q/51504087
tags question: http://stackoverflow.com/q/51526677
tags question: http://stackoverflow.com/q/51489933
tags question: http://stackoverflow.com/q/51633153
tags question: http://stackoverflow.com/q/51595337
tags question: http://stackoverflow.com/q/51557663
tags question: http://stackoverflow.com/q/51620130
tags question: http://stackoverflow.com/q/51553836
tags question: http://stackoverflow.com/q/51496728
tags question: http://stackoverflow.com/q/51635438
tags question: http://stackoverflow.com/q/51509798
tags question: http://stackoverflow.com/q/51529556
tags question: http://stackoverflow.com/q/51602562
tags question: http://stackoverflow.com/q/51637568
tags question: http://stackoverflow.com/q/51530112
tags question: http://stackoverflow.com/q/51554290
tags question: http://stackoverflow.com/q/51607038
tags question: http://stackoverflow.com/q/51588514
tags question: http://stackoverflow.com/q/51630968
tag name: pyqt5
tags question: http://stackoverflow.com/q/51613638
tags question: http://stackoverflow.com/q/51527635
tags question: http://stackoverflow.com/q/51525417
tags question: http://stackoverflow.com/q/51487226
tags question: http://stackoverflow.com/q/51485073
tags question: http://stackoverflow.com/q/51545428
tags question: http://stackoverflow.com/q/51585300

http://stackoverflow.com/q/51637222
tagged with: numpy
has comment: http://stackoverflow.com/comment/90287555
answer count: 1
has body: I'm running Anaconda/Spyder and I keep getting the Intel Math Library error shown in the picture: It seems like an entry point for mkl_blas_dgem2vu is missing (whatever that is). I was still able to run Spyder until I tried updating everything. After updating Spyder doesn't start after receiving this error. I stuck and can't do anything right now. Thanks.
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90240995
type: UnansweredQuestion
tagged with: spyder
tagged with: python
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/96478122
type: Question
has answer: http://stackoverflow.com/a/51662235
tagged with: anaconda
has title: entry point mkl_blas_dgem2vu could not be located

http://stackoverflow.com/q/51555889
accepted answer: http://stackoverflow.com/a/51555996
possible better answer: http://stackoverflow.com/a/51556064
type: Question
answer count: 2
downvote count: 5
has comment: http://stackoverflow.com/comment/90078481
has comment: http://stackoverflow.com/comment/90078719
has answer: http://stackoverflow.com/a/51555996
has body: I am newbie to python. I want to run this code but getting syntax error, I don't know how to fix it. I am running it on http://mathcs.holycross.edu/~kwalsh/python/ names=['A','B','C'] cars=['mercedes','porshe','hyundai'] numbers=[1,2,3] for name in names: file_name=names+".txt" text_file = open(file_name, "w") for car in cars: print(cars) for number in numbers: txt2write=name+" has "+str(number)+" "+car print(name+" has "+str(number)+" "+car) text_file.write("%s \n" %(txt2write)) text_file.close() print("That's all.") Any idea? Again said, its my first code.. (as said i am totally new to Python and know nothing about nested loop)
favorite count: 0
has title: python, writing nested for loop
upvote count: 2
has comment: http://stackoverflow.com/comment/90079289
has comment: http://stackoverflow.com/comment/90078564
score: -3
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51556064
has comment: http://stackoverflow.com/comment/90078477
linked to: http://stackoverflow.com/q/5532549

http://stackoverflow.com/q/51546028
has title: Most efficient way of doing column wise subtraction in pySpark
accepted answer: http://stackoverflow.com/a/51546345
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: apache-spark-sql
tagged with: pyspark
has answer: http://stackoverflow.com/a/51546345
score: 0
tagged with: apache-spark
answer count: 1
has body: I have a huge DataFrame in Spark that looks like this on (except of fact, that it have much more Value# columns): Group Type Value#1 Value#2 Value#3 G1 Revenue 11 22 33 G2 Revenue 12 23 34 G3 Revenue 13 24 35 G4 Revenue 14 25 36 G5 Revenue 15 26 37 G1 Costs 1 1 1 G2 Costs 2 2 2 G3 Costs 3 3 3 G4 Costs 4 4 4 G5 Costs 5 5 5 Again, actual dataframe contains 120 Value# columns. What I need is for every Group type in Rows and Value# in Columns calculate Revenue - Costs. Output should look like next one: Group Type Value#1 Value#2 Value#3 G1 Profit 10 11 22 G2 Profit 10 11 22 G3 Profit 10 11 22 G4 Profit 10 11 22 G5 Profit 10 11 22 P.S. I'm using Spark 2.1 from Python. Thank you!

http://stackoverflow.com/comment/90228083
has text: The last two (3 and 4) are used to set label text to ''
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51628885

http://stackoverflow.com/comment/89943498
type: QuestionComment
comment on: http://stackoverflow.com/q/51486730
has text: Oh sorry for that! I'm new to this! Will provide more details next time! Thank you for your time.
score: 0
type: Comment

http://stackoverflow.com/comment/90061430
score: 0
has text: @JonClements I'm testing random.choice and I'm only getting on value when I print it out. import random NAMES = ["Ryu", "Bruce Lee", "Jet Li", "Steven Segal", "Batman", "The Flash", "Chuck Norris", "Frieza", "Cell", "Wonder Woman", "Goku", "Vegeta"] fighter_name = random.choice(NAMES) print(fighter_name) It's not randomizing the output so, I take it I'm not testing it right.
type: QuestionComment
comment on: http://stackoverflow.com/q/51543298
type: Comment

http://stackoverflow.com/a/51624802
has body: y.replace returns a value. You have to assign it back y = y.replace("[]", "o")
score: 1
accepted answer of: http://stackoverflow.com/q/51624790
answers question: http://stackoverflow.com/q/51624790
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90236055
type: Comment
score: 0
type: AnswerComment
has text: Oh ok thanks for accepting and hope you get to take a look back at dask at some point - it's a really nice tool!
comment on: http://stackoverflow.com/a/51600921

http://stackoverflow.com/a/51576091
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90117852
has body: Can also use numpy.core.defchararray.replace() &gt;&gt;&gt; numpy.core.defchararray.replace(arr, ',','').astype(np.float) array([4364541., 2330200., 2107648., 1525711., 1485231., 1257500., 1098200., 1065106., 962100., 920200., 124204., 122320., 119742., 116627., 115900., 108400., 108400., 108000., 103795., 102900., 101845., 100900., 100626.]) Or np.char.replace as noted in comments by Cold. Naturally, this package provides is built for arrays of type numpy.string_ or numpy.unicode_ If object type, replace(a.astype(np.unicode_), ',','').astype(np.float)
answers question: http://stackoverflow.com/q/51576008
upvote count: 1
has comment: http://stackoverflow.com/comment/90117818

http://stackoverflow.com/comment/90106748
has text: In fact, my lists are more complicated than my lists in this post. I simplified my descriptions too much. Anyway, it keeps on creating a parenthesis for certain elements using omg's approach.
comment on: http://stackoverflow.com/q/51570012
score: 0
type: Comment
type: QuestionComment

header
type: Tag
tag name: header
tags question: http://stackoverflow.com/q/51520482

http://stackoverflow.com/comment/90105467
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51569414
has text: And I will really appreciate if people can be a little patient and stop hitting the down arrow on the question for nothing

http://stackoverflow.com/comment/89977938
type: QuestionComment
has text: let me know if it works
comment on: http://stackoverflow.com/q/51502263
score: 0
type: Comment

http://stackoverflow.com/q/51546340
has title: How to enlarge XGBClassifier plot_importance size in Jupyter?
type: AnsweredQuestion
tagged with: python
score: 1
accepted answer: http://stackoverflow.com/a/51698475
favorite count: 0
type: Question
answer count: 2
upvote count: 1
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/51560079
has answer: http://stackoverflow.com/a/51698475
has answer: http://stackoverflow.com/a/51560079
has body: In my Jupyter notebook, I have: from xgbost import plot_importance plot_importance(model) pyplot.show() Since the model has a lot of features, the output chart is unreadable. How do I make the chart larger?
downvote count: 0
tagged with: xgboost

http://stackoverflow.com/comment/90031967
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51531532
has text: I could not spot any mistake in your code. The only thing that may be wrong is the `test_dir` path or names of the directories in train and test dirs may be different or the train and test images are very different. Nothing else comes to my mind.
score: 0

http://stackoverflow.com/a/52130135
answers question: http://stackoverflow.com/q/51584223
type: Answer
has body: This is a classic Stars and bars problem, and Python's itertools module does indeed provide a solution that's both simple and efficient, without any additional filtering needed. Some explanation first: you want to divide 100 "points" between 3 stocks in all possible ways. For illustration purposes, let's reduce to 10 points instead of 100, with each one worth 10% instead of 1%. Imagine writing those points as a string of ten * characters: ********** These are the "stars" of "stars and bars". Now to divide the ten stars amongst the 3 stocks, we insert two | divider characters (the "bars" of "stars and bars"). For example, one such division might look like this:: **|*******|* This particular combination of stars and bars would correspond to the division 20% AAPL, 70% GOOGL, 10% IBM. Another division might look like: ******||**** which would correspond to 60% AAPL, 0% GOOGL, 40% IBM. It's easy to convince yourself that every string consisting of ten * characters and two | characters corresponds to exactly one possible division of the ten points amongst the three stocks. So to solve your problem, all we need to do is generate all possible strings containing ten * star characters and two | bar characters. Or, to think of this another way, we want to find all possible pairs of positions that we can place the two bar characters, in a string of total length twelve. Python's itertools.combinations function can be used to give us those possible positions, (for example with itertools.combinations(range(12), 2)) and then it's simple to translate each pair of positions back to a division of range(10) into three pieces: insert an extra imaginary divider character at the start and end of the string, then find the number of stars between each pair of dividers. That number of stars is simply one less than the distance between the two dividers. Here's the code: import itertools def all_partitions(n, k): """ Generate all partitions of range(n) into k pieces. """ for c in itertools.com…
score: 0

http://stackoverflow.com/q/51505187
upvote count: 3
has comment: http://stackoverflow.com/comment/89979495
tagged with: binning
tagged with: dataframe
has answer: http://stackoverflow.com/a/51505302
answer count: 4
has title: Applying my custom function to a data frame python
tagged with: pandas
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51505302
score: 3
has comment: http://stackoverflow.com/comment/89979349
downvote count: 0
has comment: http://stackoverflow.com/comment/89979438
possible better answer: http://stackoverflow.com/a/51505290
favorite count: 0
has body: I have a dataframe with a column called Signal. I want to add a new column to that dataframe and apply a custom function i've built. I'm very new at this and I seem to be having trouble when it comes to passing values that I'm getting out of a data frame column into a function so any help as to my syntax errors or reasoningg would be greatly appreciated! Signal 3.98 3.78 -6.67 -17.6 -18.05 -14.48 -12.25 -13.9 -16.89 -13.3 -13.19 -18.63 -26.36 -26.23 -22.94 -23.23 -15.7 This is my simple function def slope_test(x): if x &gt;0 and x&lt;20: return 'Long' elif x&lt;0 and x&gt;-20: return 'Short' else: return 'Flat' I keep getting this error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Here is the code i've tried: data['Position'] = data.apply(slope_test(data['Signal'])) and also: data['Position'] = data['Signal'].apply(slope_test(data['Signal']))
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51505290
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51505259
has answer: http://stackoverflow.com/a/51505279
has comment: http://stackoverflow.com/comment/89979406

http://stackoverflow.com/comment/129908744
has text: from IPython.display import HTML
comment on: http://stackoverflow.com/a/71262575
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51591849
downvote count: 1
has answer: http://stackoverflow.com/a/51591982
score: 2
has title: scraping javascript:void(0) content using python
upvote count: 3
tagged with: web-scraping
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51591981
has body: I am making a program, in which I am scrapping a web page and the content is hidden from the original page and use to display itself using herf = javascript:void(0) link and the text is in and then tags. Here is my code: import requests, re from bs4 import BeautifulSoup page = requests.get('https://www.naukri.com/job-listings-Python-Developer- Cloud-Analogy-Softech-Pvt-Ltd-Noida-Sector-63-Noida-1-to-2-years- 250718003152?src=rcntSrchWithoutCount&sid=15327965116011&xp=1&px=1&qp=python%20developer&srcP% 20ge=s').text soup = BeautifulSoup(page, 'html.parser') link = soup.find('div', {'class':'jDisc viewContact'}).find_all(re.compile('p|em|span')) results = [i.text for i in link] print(results) and the HTML page is here: View Contact Details After clicking on the link "view contact detail" it will show all the hidden content. Can you please help me to solve this?
tagged with: javascript
has comment: http://stackoverflow.com/comment/90149176
has comment: http://stackoverflow.com/comment/90149303
has comment: http://stackoverflow.com/comment/90149147
favorite count: 0
has comment: http://stackoverflow.com/comment/90149063
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51558083
has comment: http://stackoverflow.com/comment/90083150
has answer: http://stackoverflow.com/a/51558154
tagged with: python
has comment: http://stackoverflow.com/comment/90083073
type: AnsweredQuestion
has body: I have a static base class, which I want to encapsulate child classes. I cannot find the syntax to create the inner classes from within a static outer class. Here's an example of what I want: class Farm: my_pet_cat = Animal("Meeeeooowww", "Fluffy") class Animal: def __init__(self, sound, fur): self.sound = sound self.fur = fur def speak(self): print(self.sound) def pet(self): return self.fur NameError: name 'Animal' is not defined I tried accessing Animal with self.Animal(...) but this didn't work, as obviously Farm doesn't have a self, being a static class and all. I also successfully accessed Animal if it is placed outside of Farm, but I want to encapsulate the Animal class within the Farm class. Can this be done??
type: Question
linked to: http://stackoverflow.com/q/31875
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51558154
possible better answer: http://stackoverflow.com/a/51558266
has title: How to construct inner class from within static outer class
has comment: http://stackoverflow.com/comment/90083374
has answer: http://stackoverflow.com/a/51558266

http://stackoverflow.com/comment/89951919
type: Comment
type: QuestionComment
has text: If you want to see `test.test = {}` in the output, then you'll have to remove `test['a'] = 1` and `test['b'] = 2`. But why do you want to document a specific instance of a class in the first place?
comment on: http://stackoverflow.com/q/51487209
score: 0

http://stackoverflow.com/q/51583908
linked to: http://stackoverflow.com/q/50586146
upvote count: 2
tagged with: pandas
answer count: 1
has title: Identify first non-zero element within a group in pandas
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
has body: I have a dataframe that looks like the following. The rightmost column is my desired column: Group Value Target_Column 1 0 0 1 0 0 1 1 1 1 2 0 2 0 0 2 1 1 2 0 0 2 1 0 How do I identify the first non-zero value in a group(Group) and then create a column that retains the first non-zero value and show all else as zeroes? I have been trying to leverage idxmax for this as stated in this solution: Find first non-zero value in each column of pandas DataFrame import pandas as pd df = pd.DataFrame({'Group': [1,1,1,1,2,2,2,2], 'Value': [0,0,1,1,0,1,0,1]}) df.ne(0).idxmax() g = df.groupby('Group').Value g.ne(0).idxmax()
has answer: http://stackoverflow.com/a/51583925
accepted answer: http://stackoverflow.com/a/51583925
type: Question
tagged with: numpy

http://stackoverflow.com/q/51608355
tagged with: airflow
has title: Need to access schedule time in DockerOperator in Airflow
tagged with: docker
answer count: 3
has answer: http://stackoverflow.com/a/51615842
favorite count: 0
possible better answer: http://stackoverflow.com/a/51625304
has answer: http://stackoverflow.com/a/51625304
tagged with: python
linked to: http://stackoverflow.com/q/44855949
tagged with: airflow-scheduler
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51615842
has body: Need to access schedule time in airflow's docker operator. For example t1 = DockerOperator( task_id="task", dag=dag, image="test-runner:1.0", docker_url="xxx.xxx.xxx.xxx:2376", environment={"FROM": "{{(execution_date + macros.timedelta(hours=6,minutes=(30))).isoformat()}}"}) Basically, I need to populate schedule time as docker environment.
has comment: http://stackoverflow.com/comment/90187985
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/55737023
downvote count: 1
type: Question

http://stackoverflow.com/a/51629512
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51628776
has body: There are some strange things here: you make a POST request, but the view has no side-effects, nor does the POST transfers any data. In that case a GET makes more sense; based on the success handle, it looks like the result should be a dictionary with a key onct; and The url in urls.py does not contain the door_id parameter. By using .values_list(..) in the query, we can also save a bit on database bandwidth, and furthermore make the view more elegant: def get_not_compat_options(request, door_id): door = get_object_or_404(Door, id=door_id) not_compat_options = door.not_comp_options data = {'onct': list(not_comp_options.all().values_list('name', flat=True))} return JsonResponse(data) and the AJAX request then could look like: $.ajax({ type: "GET", url: "/get_not_compat_options/" + door_id, data: "", dataType: 'json', success: function() { console.log(data.onct) } }) Furthermore the urls.py shoudl probably look like: urlpatterns = [ # Other url patterns path('get_not_compat_options/&lt;int:door_id&gt;', views.get_not_compat_options, name="get_not_compat_options") ] Since otherwise this path(..) can not accept an door_id.

http://stackoverflow.com/comment/90022121
has text: There's already a solution: https://stackoverflow.com/questions/3269434/whats-the-most-efficient-way-to-test-two-integer-ranges-for-overlap
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51526282
score: 0

http://stackoverflow.com/comment/89981382
score: 2
type: Comment
comment on: http://stackoverflow.com/q/51506175
type: QuestionComment
has text: The line `C = [[0 for i in range(n)] for j in range(n)]` creates an n by n matrix filled with zeros. This is needed, since in the line `C[i][j] += A[i][k] * B[k][j]` the elements of `C` are accessed. If the matrix would not have been initialized, you would get an error here. By the way: please have a look at `numpy` and please do look into your code again. It seems unnecessary complex.

http://stackoverflow.com/q/51507299
answer count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/89984664
type: Question
score: 4
has comment: http://stackoverflow.com/comment/89990113
upvote count: 4
has comment: http://stackoverflow.com/comment/89983838
downvote count: 0
has title: Selenium :TypeError: __init__() got an unexpected keyword argument 'executable_path'
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90005896
tagged with: python
tagged with: selenium-webdriver
has body: I'm trying to run selenium chromedriver on heroku with: def create_chromedriver(ua=False): options = webdriver.ChromeOptions() CHROMEDRIVER_PATH = os.getenv('$HOME') or basedir+'/chromedriver.exe' FLASK_CONFIG = os.getenv('FLASK_CONFIG') if FLASK_CONFIG and FLASK_CONFIG == "production": CHROMEDRIVER_PATH = '/app/.chromedriver/bin/chromedriver' GOOGLE_CHROME_SHIM = os.getenv('$GOOGLE_CHROME_SHIM') or 'no path found' options.binary_location = '/app/.apt/usr/bin/google-chrome' options.add_argument("--start-maximized") options.add_argument("--disable-infobars") options.add_argument("--disable-extensions") options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") if ua: mobile_emulation = {"deviceName": "Nexus 5"} options.add_experimental_option("mobileEmulation", mobile_emulation) options.add_argument("--headless") options.add_argument("--disable-gpu") capabilities = options.to_capabilities() return webdriver.Remote(executable_path=CHROMEDRIVER_PATH, command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=options.to_capabilities()) when I run: def some_long_calculation(): driver = create_chromedriver('test') # driver = create_chromedriver() print(driver.capabilities['version']) driver.get("https://www.yahoo.com/") I get the screenshot. The error log gives: 2018-07-24T20:20:58.078553+00:00 app[web.1]: TypeError: __init__() got an unexpected keyword argument 'executable_path' How can I set the path to chromedriver here?

http://stackoverflow.com/a/51578378
has comment: http://stackoverflow.com/comment/90122128
has body: The equivalence semantics between (frozen)sets are that if they contain equivalent items they are equivalent. Sets do not have order. But, since lists have order, the cast to list can potentially cause them to not be equivalent (depends on the order of iteration over the (frozen)set - which is an implementation detail). Here is an example of a collision in the internal implementation that causes a different iteration order due to the instertion order (this is in CPython implementation): &gt;&gt;&gt; a = list(frozenset([1, 9])) &gt;&gt;&gt; b = list(frozenset([9, 1])) &gt;&gt;&gt; a == b False Example with strings: First we need to find a collision (I will not go into details): &gt;&gt;&gt; hash('1') % 8 0 &gt;&gt;&gt; hash('2') % 8 5 &gt;&gt;&gt; hash('3') % 8 2 &gt;&gt;&gt; hash('4') % 8 3 &gt;&gt;&gt; hash('5') % 8 1 &gt;&gt;&gt; hash('6') % 8 4 &gt;&gt;&gt; hash('7') % 8 5 # same as '2' ! Found! Now we need to add in different order to the set to cause a re-hash (again, not going into details): &gt;&gt;&gt; s1, s2 = '2', '7' &gt;&gt;&gt; a = list(frozenset([s1, s2])) &gt;&gt;&gt; b = list(frozenset([s2, s1])) &gt;&gt;&gt; a == b False
score: 3
accepted answer of: http://stackoverflow.com/q/51578335
answers question: http://stackoverflow.com/q/51578335
type: AcceptedAnswer
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/90122205
downvote count: 0

http://stackoverflow.com/comment/90018274
score: 0
type: Comment
has text: I'm sorry, I created a new dataframe and used your solutions, both worked. It seems my original data has been augmented by another party and the data not de-duping as expected is because the data is no longer the same. That is my fault.
type: AnswerComment
comment on: http://stackoverflow.com/a/51522901

http://stackoverflow.com/q/51530054
has title: Using Python how can I merge two columns and overwrite data from one column only if data in other column exists?
has comment: http://stackoverflow.com/comment/90028319
possible better answer: http://stackoverflow.com/a/51530265
favorite count: 0
has answer: http://stackoverflow.com/a/51530265
has answer: http://stackoverflow.com/a/51530245
tagged with: python
type: AnsweredQuestion
upvote count: 3
type: Question
has body: I am trying to merge some data and have been unable to get the results I've been looking for. I have two data frames with two columns each: CID and Notional. DF1 has every CID and DF2 has just some of the CIDs. I want to take DF2's data and merge it with DF1 so that IF DF2's data exists it will overwrite DF1, and if not DF1 will retain it's data. I have tried using pd.merge and I end up with a DataFrame that has columns CID, Notional_X, Notional_Y; I have tried 'update' but it just replaces all old DataFrame data. Here's an example of what I'm looking for: #Example of Data (couldn't find a better way to explain this) df1 = pd.DataFrame({'CID':[1,25,100], 'Notional': [1000, 2500, 5500]}) df2 = pd.DataFrame({'CID':[25], 'Notional': [0]}) the output would return a DataFrame that looks like this: pd.DataFrame({'CID': [1,25,100], 'Notional': [1000,0,5500]}) (not that the merge reduced CID 25 to 0 which is found in df2 without changing anything else) The documentation suggests that 'merge' should accomplish it but it just... doesn't. test = df1.merge(df1, df2, how = 'left', on = 'CID') This seems to merge the dataframes without merging the data (it just appends a column on the end) Any help would be greatly appreciated. Thank you.
accepted answer: http://stackoverflow.com/a/51530245
score: 3
answer count: 2
tagged with: pandas
downvote count: 0

parallel-processing
tags question: http://stackoverflow.com/q/51558415
tags question: http://stackoverflow.com/q/51566928
tags question: http://stackoverflow.com/q/51625513
tags question: http://stackoverflow.com/q/51578641
tags question: http://stackoverflow.com/q/51566575
tags question: http://stackoverflow.com/q/51598399
tags question: http://stackoverflow.com/q/51537589
type: Tag
tag name: parallel-processing
tags question: http://stackoverflow.com/q/51548722
tags question: http://stackoverflow.com/q/51611735

http://stackoverflow.com/comment/90131552
comment on: http://stackoverflow.com/q/51582289
score: 0
has text: @hpaulj Thanks. I thought that's a bit too magical. Just to clarify, numpy didn't apply the scalar function on the array. Instead, it applied an element-wise array function in that example??
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90175937
score: 0
type: AnswerComment
has text: @Khan11 weird training and val loss.
type: Comment
comment on: http://stackoverflow.com/a/51605215

http://stackoverflow.com/comment/90227813
type: AnswerComment
comment on: http://stackoverflow.com/a/51631731
score: 0
type: Comment
has text: Listing attributes as class properties is useful because of two reasons: 1. it becomes clear what's used in the class so you don't need to read through the methods 2. you won't get attribute error, thus, going forward, you can check your attrs like `if self.prev_text is not None` rather than `hasattr(self, 'prev_text')` which is much cleaner.

http://stackoverflow.com/comment/89945544
type: Comment
type: QuestionComment
has text: Why are you doing `pip3 install requests`? `urllib.request` and `requests` have nothing to do with each other. Just because two things have kind of similar names doesn't mean they're the same thing. Does `main.py` really import both of them? If so, you probably need to show us that code, because that's a pretty weird thing to do.
comment on: http://stackoverflow.com/q/51487798
score: 0

http://stackoverflow.com/comment/90130573
has text: Can you explain the `periods_offsets` please?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51581442

http://stackoverflow.com/q/51523635
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/92702189
answer count: 2
has comment: http://stackoverflow.com/comment/90016576
tagged with: pandas
has comment: http://stackoverflow.com/comment/90016730
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/34685577
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51524106
score: 1
upvote count: 1
has title: fastest way to load data to a pd.DataFrame using different formats (csv, json, avro)
has answer: http://stackoverflow.com/a/51524464
type: Question
tagged with: avro
has body: We are loading big amounts of data from google bigquery to pandas dataframe (to be consumed directly as a pandas and also to be consumed as a xgbMatrix). BQ export formats are CSV, JSON and AVRO, our data has dates, integers, floats and strings, and is usually "wide" (many columns). Our first approach was import the data as CSV, but the parsing time is huge: (32 GB,126 files,CSV) -&gt; 25 min parsing code: def load_table_files_to_pandas(all_files, table_ref): # load files to pandas dict_dtype = {} date_cols = [] client = bigquery.Client() # create a bq client table = client.get_table(table_ref) for field in table.schema: pd_dtypes = {'string':'object', 'date':'object', 'float':'float64', 'integer':'float64' } dict_dtype[field.name] = pd_dtypes[field.field_type.lower()] if field.field_type.lower()== 'date': date_cols.append(field.name) print('start reading data') df_from_each_file = [] for f in all_files: # looping over files df_from_each_file.append(pd.read_csv(f, dtype = dict_dtype, parse_dates = date_cols)) print('memory in use = {}'.format(psutil.virtual_memory().percent)) df = pd.concat(df_from_each_file, ignore_index=True) print('end reading data') return df Which format is a faster for parsing in pandas? [Avro,CSV,JSON]? Is there maybe a third one not considered? additional we also tried with dask|csv directly from storage and from local disk, but the parsing time was almost the same.

http://stackoverflow.com/comment/90231817
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51633655
score: 0
has text: @jezrael because it needs to only return rows with non zero values

http://stackoverflow.com/a/51686446
type: AcceptedAnswer
has body: Switching to the frame before finding element solved the issue. driver.switch_to_frame(0) agency = driver.find_element_by_id("servProvCode") References: in selenium web driver how to choose the correct iframe
type: Answer
answers question: http://stackoverflow.com/q/51548202
accepted answer of: http://stackoverflow.com/q/51548202
score: 0

http://stackoverflow.com/comment/90171411
type: Comment
type: QuestionComment
has text: XLSX file? It's compressed. You can decompress it with 7Zip or rename to .ZIP and then unzip it. How large is the result?
score: 0
comment on: http://stackoverflow.com/q/51602694

http://stackoverflow.com/a/51495624
score: 2
has comment: http://stackoverflow.com/comment/89959721
has comment: http://stackoverflow.com/comment/89959950
has comment: http://stackoverflow.com/comment/89959657
has body: You would first need to import the file (depending on your directory structure) into your current script, create an instance of the class and then call the method within that class; #Import your other file import other_file #Create an instance of the object where your method is my_obj = NewClass() #Call the method directly my_obj.some_method() You could also try adding a @staticmethod to the method to make it directly callable: class NewClass: @staticmethod def some_method(): print 'Hello' #call staticmethod add directly #without declaring instance and accessing class variables NewClass.some_method()
has comment: http://stackoverflow.com/comment/89959886
downvote count: 0
has comment: http://stackoverflow.com/comment/89959877
upvote count: 2
answers question: http://stackoverflow.com/q/51495132
type: Answer
has comment: http://stackoverflow.com/comment/89959778

http://stackoverflow.com/a/51530329
type: Answer
has comment: http://stackoverflow.com/comment/90028915
answers question: http://stackoverflow.com/q/51530216
score: 0
has body: You can just use the special attribute __dict__ of you class: class A(): def __init__(self,b,c): self.b = 1 self.c = 2 Output: a = A(3,4) print(a.__dict__) {'b': 3, 'c': 4}

http://stackoverflow.com/comment/89948480
has text: It's a format string, introduced in Python 3.6
type: Comment
comment on: http://stackoverflow.com/q/51489881
type: QuestionComment
score: 0

http://stackoverflow.com/a/51517684
answers question: http://stackoverflow.com/q/51517429
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51517429
type: Answer
has comment: http://stackoverflow.com/comment/90080698
upvote count: 2
has body: You can use time module of python. If i understood your question properly, Something like this can be done: import time initial_time = time.monotonic() def move(): #code here time_gap = time.monotonic() - initial_time print(time_gap) initial_time = time.monotonic() turn.reverse()
score: 2
has comment: http://stackoverflow.com/comment/90085855
has comment: http://stackoverflow.com/comment/90131695

http://stackoverflow.com/comment/89977633
type: QuestionComment
has text: After reformatting your `kv` file, it seems to work fine for me. Can you add a screenshot to show what the problem is?
comment on: http://stackoverflow.com/q/51503288
score: 0
type: Comment

http://stackoverflow.com/comment/90205984
comment on: http://stackoverflow.com/q/51617624
score: 0
type: Comment
type: QuestionComment
has text: @wwii I want to delete those items from the list. The order of the list should be the same besides that

http://stackoverflow.com/comment/90023384
has text: BTW, the `0.4` is in the wrong place in the list if I follow your pattern. I think you want index `0` to be `0.2` and index `9` to be `0.4`
comment on: http://stackoverflow.com/q/51527379
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/a/51634193
has comment: http://stackoverflow.com/comment/90240661
score: 0
has comment: http://stackoverflow.com/comment/90236397
has body: Will this work? def find_nonzeros(): for i, col in enumerate(["Opt1", "Opt2", "Opt3"]): if df[col].nonzero(): #if there are any nonzero values return df.iloc[df[col].nonzero()[0], list(range(6)) + [6 + i]] return df.iloc[0, list(range(6)) + [len(df.columns)-1]]
has comment: http://stackoverflow.com/comment/90243148
type: Answer
has comment: http://stackoverflow.com/comment/90233142
answers question: http://stackoverflow.com/q/51633655
has comment: http://stackoverflow.com/comment/90232842

http://stackoverflow.com/a/51547350
score: 2
accepted answer of: http://stackoverflow.com/q/51545745
upvote count: 2
has body: You can eliminate the loop, and instead create an array with the value 1 at each center and then apply gaussian_filter once to this array. All the steps can be vectorized. Here's an example. I made sigma smaller so it was easier to distinguish the centers, and I increased the width to 800 (for no particular reason :). import numpy as np from scipy.ndimage import gaussian_filter import matplotlib.pyplot as plt num_centers = 10 sigma = 25 size = (600, 800) impulses = np.zeros(size) # rows and cols are the row and column indices of the centers # of the gaussian peaks. np.random.seed(123456) rows, cols = np.unravel_index(np.random.choice(impulses.size, replace=False, size=num_centers), impulses.shape) impulses[rows, cols] = 1 # or use this if you want duplicates to sum: # np.add.at(impulses, (rows, cols), 1) # Filter impulses to create the result. result = gaussian_filter(impulses, sigma, mode='nearest') plt.imshow(result) plt.show() Here's the plot: You can experiment with the mode argument of gaussian_filter to see which mode works best for you.
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51545745
has comment: http://stackoverflow.com/comment/90063643
has comment: http://stackoverflow.com/comment/90063906

http://stackoverflow.com/comment/90325063
comment on: http://stackoverflow.com/a/51661344
has text: Not a problem. the reason it is never at 100% is because new blocks are mined every second, sometimes multiple a second, so it is always downloading blocks. Also, if you think my answer was helpful, please upvote it and mark it as the correct answer.
type: Comment
type: AnswerComment
score: 0

math
tags question: http://stackoverflow.com/q/51487174
tags question: http://stackoverflow.com/q/51639553
type: Tag
tags question: http://stackoverflow.com/q/51553722
tags question: http://stackoverflow.com/q/51487046
tags question: http://stackoverflow.com/q/51496051
tags question: http://stackoverflow.com/q/51483920
tags question: http://stackoverflow.com/q/51618239
tags question: http://stackoverflow.com/q/51599586
tag name: math
tags question: http://stackoverflow.com/q/51509371
tags question: http://stackoverflow.com/q/51507598
tags question: http://stackoverflow.com/q/51506639

http://stackoverflow.com/comment/89974282
type: Comment
has text: It is really strange that you get an array. I just ran it with numpy 1.14.0 and python 3.6.5 and `np.int64(42) == ("A", "B")` returns `False`. I don't see how this is possible. Are you using python 3.7 ?
comment on: http://stackoverflow.com/a/51501842
type: AnswerComment
score: 0

http://stackoverflow.com/a/51490086
type: Answer
answers question: http://stackoverflow.com/q/51489990
score: 1
upvote count: 1
has body: You can pass it inside a hidden input, such as: &lt;form ...&gt; ... &lt;input type="hidden" name="id" value="{{ entry.id }}"&gt; &lt;button ...&gt; &lt;/form&gt; and access to it in your view: def upvote(request): entry_id = int(request.GET.get("id")) ...
downvote count: 0

pose-estimation
tag name: pose-estimation
tags question: http://stackoverflow.com/q/51584562
type: Tag

http://stackoverflow.com/q/51560515
tagged with: authorization
score: 0
has answer: http://stackoverflow.com/a/51571794
answer count: 1
accepted answer: http://stackoverflow.com/a/51571794
tagged with: access-token
tagged with: python
tagged with: python-requests
type: AnsweredQuestion
has body: I've been trying to connect to the EPO OPS API using the requests package in python - without success. The dev guide (page 34) states that Step 1 is to convert Consumer key and Consumer secret to Base64Encode(Consumer key:Consumer secret). Step 2 is to request an access token using Basic Authentication, supplying its Consumer key and Consumer secret with base64Encoding over encrypted HTTPS connection as follows: Below is the code I've used but I get an error 400 status. import requests import base64 url_token = "https://ops.epo.org/3.2/auth/accesstoken" key = "Basic %s" %base64.b64encode("myconsumerkey:mysecretkey") headers = ({"Authorization": key, 'Content-Type': 'application/x-www-form-urlencoded'}) resp = requests.post(url_token, headers=headers) print(resp.status_code) Anyone knows how to make the access_token request work? I'd like the script to extract the XML content of this link: "http://ops.epo.org/3.2/rest-services/published-data/search?q=automation" Thanks!
has title: Python get access_token from OPS API
type: Question
tagged with: api

http://stackoverflow.com/comment/90171285
has text: you can always do `.replace("", np.nan)` or `map({'':np.nan, 0: np.nan})` and *then* `.dropna()`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51602575

http://stackoverflow.com/q/51539735
has title: Drop specific rows from pandas dataframe according to condition
score: 1
type: Question
has answer: http://stackoverflow.com/a/51539819
downvote count: 0
tagged with: pandas
answer count: 1
tagged with: python
favorite count: 0
has body: I have a dataframe with several columns [A, B, C, ..., Z]. I want to delete all rows from the dataframe which have the property that their values in columns [B, C, ..., Z] are equal to 0 (integer zero). Example df: A B C ... Z 0 3 0 0 ... 0 1 1 0 0 ... 0 2 2 1 2 ... 3 &lt;-- keep only this as it has values other than zero I tried to do this like so: df = df[(df.columns[1:] != 0).all()] I can't get it to work. I am not too experienced with conditions in indexers. I wanted to avoid a solution that chains a zero test for every column. I am sure that there is a more elegant solution to this. Thanks! EDIT: The solution worked for an artificially created dataframe, but when I used it on my df that I got from reading a csv, it failed. The file looks like this: A;B;C;D;E;F;G;H;I;J;K;L;M;N;O;P;Q;R;S;T;U;V;W;X;Y;Z 0;25310;169;81;0;0;0;12291181;31442;246;0;0;0;0;0;0;0;0;0;251;31696;0;0;329;0;0 1;6252727;20480;82;0;0;0;31088;85;245;0;0;0;0;0;0;0;0;0;20567;331;0;0;329;0;0 2;6032184;10961;82;0;0;0;31024;84;245;0;0;0;0;0;0;0;0;0;11046;330;0;0;329;0;0 3;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 4;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;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 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 7;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 8;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 9;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 10;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 I read it using the following commands: import pandas as pd # retrieve csv file as dataframe df = pd.read_csv('PATH/TO/FILE'), decimal=',', sep=';') df[list(df)] = df[list(df)].astype('int') print(df) df = df[(df.iloc[:, 1:] != 0).all(axis=1)] print(df) The first print statement shows that the frame is read correctly, but the second print gives me an empty dataframe. How can this be?
accepted answer: http://stackoverflow.com/a/51539819
upvote count: 1
tagged with: indexing
type: AnsweredQuestion

http://stackoverflow.com/a/51544730
score: 1
upvote count: 1
has body: It is not an issue. According to the theory, an object can not have two members with a similar name. then as Python is interpreted it gives you an error when you get to the line where you declare the function. If it were C # or java, I would have given you an error when compiling. So it has to be a conceptual theme. the same error gives you in any language that supports the paradigm to objects.
answers question: http://stackoverflow.com/q/51544505
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90058355

http://stackoverflow.com/comment/90032049
comment on: http://stackoverflow.com/q/51532012
has text: on cmd check : `python3 -c 'import matplotlib; print(matplotlib.__version__, matplotlib.__file__)'`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51593679
answers question: http://stackoverflow.com/q/51593595
downvote count: 0
has comment: http://stackoverflow.com/comment/90153833
score: 17
has body: You can cleanup after the fixture is done like: @pytest.fixture(scope='module') def project_file(self, tmpdir_factory): my_tmpdir = tmpdir_factory.mktemp("data") yield my_tmpdir shutil.rmtree(str(my_tmpdir))
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90157756
has comment: http://stackoverflow.com/comment/90158283
type: Answer
upvote count: 17
has comment: http://stackoverflow.com/comment/90155746
accepted answer of: http://stackoverflow.com/q/51593595
has comment: http://stackoverflow.com/comment/90157779

http://stackoverflow.com/q/51546787
type: UnansweredQuestion
has title: Any way to take multiple snapshots (sequentially) with different exposure times in openCV?
upvote count: 1
tagged with: python
tagged with: opencv
answer count: 0
score: 1
type: Question
downvote count: 0
has body: I'm attempting to take multiple snapshots squentially with different exposure times from an attached USB camera. However, upon changing the exposure time before each aquisition, the exposure time remains the same as that for the first snapshot as can been seen by looking at the image (even though cap.get() still returns the new exposure time). Furthermore, the camera doesn't turn off when using .release(). Perhaps a driver issue? The result is the same with the attached webcam on my Dell. openCV v3.4.2 on Python v3.7.0 import numpy as np import cv2 from matplotlib import pyplot as plt cap = cv2.VideoCapture(1) exp = cap.get(15) width = cap.get(3) height = cap.get(4) print(f'original exporsure {exp:1}') cap.set(15,-5) #set first exposure ret, frame = cap.read() #get a single frame print(f'exposure 1 {cap.get(15):1}') cv2.imshow('1',frame) cv2.waitKey(0) cv2.destroyAllWindows() cap.set(15,-10) #set second exposure ret2, frame2 = cap.read() print(f'exposure 2 {cap.get(15):1}') cv2.imshow('2',frame2) cv2.waitKey(0) cap.release() cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/90061913
favorite count: 0

http://stackoverflow.com/a/51558602
answers question: http://stackoverflow.com/q/51558469
has body: You can use the np.random.randint to create a full array of random values, f-strings (Python 3.6+) with a list comprehension for column naming, and pd.DataFrame.assign with np.arange for defining "id_col": import pandas as pd, numpy as np rows = 10 cols = 5 minval, maxval = 0, 10 df = pd.DataFrame(np.random.randint(minval, maxval, (rows, cols)), columns=[f'c{i}' for i in range(1, cols+1)])\ .assign(id_col=np.arange(1, num_rows+1)) print(df) c1 c2 c3 c4 c5 id_col 0 8 4 6 0 8 1 1 8 3 5 9 0 2 2 1 3 3 6 2 3 3 6 4 1 1 7 4 4 3 7 0 9 5 5 5 4 6 8 8 6 6 6 0 3 9 9 7 7 7 0 6 1 2 4 8 8 3 7 1 2 0 9 9 6 6 0 5 8 10
score: 0
type: Answer

http://stackoverflow.com/comment/89937792
type: QuestionComment
type: Comment
has text: pandas 0.23.1 py36h830ac7b_0 no local file named: pandas.py
comment on: http://stackoverflow.com/q/51484371
score: 0

http://stackoverflow.com/a/51509221
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/89987491
has body: Data from Raf x[np.where(x[:,0]==5)[0][0]:np.where(x[:,0]==9)[0][0]+1,:] Out[341]: array([[ 5, 6, 7, 8], [ 9, 10, 11, 12]]) Notice only using greater and less than for that can not fully replace the .loc, the back end of .loc is index position not value range For example df Out[348]: 0 1 2 3 0 1 2 3 4 1 5 6 7 8 4444 9 10 11 12 3 13 14 15 16 df.loc[1:3] Out[347]: 0 1 2 3 1 5 6 7 8 4444 9 10 11 12 3 13 14 15 16
has comment: http://stackoverflow.com/comment/89987551
answers question: http://stackoverflow.com/q/51508682
downvote count: 0

http://stackoverflow.com/comment/89945355
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51487279
has text: Really great answer, many thanks @user6655984! A little benchmark [here](https://stackoverflow.com/a/51488210/1422096), I didn't expect a so great speed improvement :)
type: AnswerComment

http://stackoverflow.com/a/51599595
has body: The easiest way to do this is to concat them as strings, and then parse it back into a number. x = str(1) + str(4) + str(5) print(int(x)) or int(str(1) + str(4) + str(5))
score: 0
answers question: http://stackoverflow.com/q/51599586
type: Answer

http://stackoverflow.com/comment/89947463
has text: also `repr(i)` more efficient than `"'" + i + "'"`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51489314
type: AnswerComment

http://stackoverflow.com/q/51576407
accepted answer: http://stackoverflow.com/a/51576717
type: Question
tagged with: python-2.7
score: 0
tagged with: pydoc
answer count: 1
has title: When I call /usr/bin/pydoc, /usr/bin/pydoc2.7 called indeed
tagged with: python
has body: when I run the command /usr/bin/pydoc, it prints durd@FelixDu bin$ /usr/bin/pydoc pydoc - the Python documentation tool pydoc &lt;name&gt; ... Show text documentation on something. &lt;name&gt; may be the name of a Python keyword, topic, function, module, or package, or a dotted reference to a class or function within a module or module in a package. If &lt;name&gt; contains a '/', it is used as the path to a Python source file to document. If name is 'keywords', 'topics', or 'modules', a listing of these things is displayed. pydoc -k &lt;keyword&gt; Search for a keyword in the synopsis lines of all available modules. pydoc -p &lt;port&gt; Start an HTTP server on the given port on the local machine. Port number 0 can be used to get an arbitrary unused port. pydoc -g Pop up a graphical interface for finding and serving documentation. pydoc -w &lt;name&gt; ... Write out the HTML documentation for a module to a file in the current directory. If &lt;name&gt; contains a '/', it is treated as a filename; if it names a directory, documentation is written for all the contents. but I checked the code of /usr/bin/pydoc, it shows durd@FelixDu bin$ cat /usr/bin/pydoc #!/usr/bin/python import sys, os import glob, re partA = """\ python version %d.%d.%d can't run %s. Try the alternative(s): """ partB = """ Run "man python" for more information about multiple version support in Mac OS X. """ sys.stderr.write(partA % (sys.version_info[:3] + (sys.argv[0],))) dir, base = os.path.split(sys.argv[0]) specialcase = (base == 'python-config') if specialcase: pat = "python*-config" else: pat = base + '*' g = glob.glob(os.path.join(dir, pat)) # match a single digit, dot and possibly multiple digits, because we might # have 2to32.6, where the program is 2to3 and the version is 2.6. vpat = re.compile("\d\.\d+") n = 0 for i in g: vers = vpat.search(i) if vers is None: continue sys.stderr.write("%s (uses python %s)\n" % (i, i[vers.start():vers.end()])) n = 1 if n == 0: sys.stderr.write("(Error: …
tagged with: command-line
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51576717

http://stackoverflow.com/a/51602461
downvote count: 0
has body: Sorry for the trouble, but I think I found the answer that I was looking for. I can use numpy.pad to create an arbitrary number of filler zeros at the end of my original array. There is also a function called numpy.roll which can then be used to shift all array elements along a given axis by a set number of positions down the column. After a quick test, it looks like this is extendable for an arbitrary number of matrix elements and allows a unique offset along each column. Thanks to everyone for their responses to this question!
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51597849

http://stackoverflow.com/comment/89961227
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51494864
score: 1
has text: @user3473823 In my example, `getGroup(x)` would just return the `len` of the string. It's difficult to say if such a key-function exists in your case, though. Think of it as some kind of hashing function where the hash is the same for each element in any of the groups.

http://stackoverflow.com/q/51556323
score: 0
has comment: http://stackoverflow.com/comment/90079328
has answer: http://stackoverflow.com/a/51556394
has body: I am firing a SPH simulation using a Dual SPH executables. It has four consecutive subprocess commands that progresses to produce the vtk files of the simulation. The problem is that assuming particle distance in SPH is very sensitive and there is no proper way to calculate it. If the particle distance is too high then it will fail to run the first command and it will give an error. I want to write a code which could read the error given by the first subprocess so that i can optimize over particle distance. Is there any way I can read the error given by the first subprocess? Gen = subprocess.Popen(args = sph_location+"\\"+"GenCase4_win64"+" "+def_out+" "+out+"\\"+r"z -save:all", shell='TRUE') Gen.communicate() Dual = subprocess.Popen(args= sph_location+"\\"+"DualSPHysics4.2_win64"+" "+out+"\\"+r"z -svres -cpu", shell='TRUE') Dual.communicate() Vtk = subrocess.Popen(args= sphlocation+"\\"+"PartVTK4_win64"+" -savevtk "+out+"\\"+r"zPartFluid -onlytype:-all,+fluid -vars:+vol", shell='TRUE') Surface = subprocess.Popen(args= sph_location+"\\"+"IsoSurface4_win64"+" "+r"-onlytype:+fluid -vars:+vol -saveiso surface" ,shell='TRUE') Surface.communicate()
type: Question
accepted answer: http://stackoverflow.com/a/51556394
type: AnsweredQuestion
tagged with: particles
tagged with: python
answer count: 1
has title: Command Line error stored in a file
tagged with: subprocess

http://stackoverflow.com/q/51635255
type: AnsweredQuestion
score: -1
has answer: http://stackoverflow.com/a/51635584
type: Question
answer count: 1
tagged with: window
has body: I just have general question. I need to start with project where will be placed some real time graphs, graphics etc. What should I use? I heard about pyqt and tkinter only. It will be large project.
downvote count: 1
tagged with: python
has title: Python window application
favorite count: 0
upvote count: 0
accepted answer: http://stackoverflow.com/a/51635584

http://stackoverflow.com/a/51549745
score: 0
answers question: http://stackoverflow.com/q/51547207
type: Answer
has body: First off, you need to be a bit more careful with your terminology. A "matrix" is a 2-Dimensional array of numbers. So you are really talking about an array. Numpy, or better yet Scipy, has an data type called an ndarray. You need to be very careful manipulating them, because although they are sometimes used to represent matrices, there are operations that can be performed on 2-D arrays that are not mathematically legal for matrices. I strongly recommend you use @ and not * to perform multiplication of 1- or 2-D matrices, and be sure to add code to check that the operations you are doing are legal mathematically. As a trivial example, Python lets you add a 1 x n or an n x 1 vector to an n x n matrix, even though that is not mathematically correct. The reason it allows it is, as intimated above, because there is no true matrix type in Python. It very well may be that you can reformulate your problem to use a 3-D array, and by experimentation find the particular operation you are trying to perform. Just keep in mind that the rules of linear algebra are only casually applied in Python.

http://stackoverflow.com/comment/126904275
comment on: http://stackoverflow.com/a/51542306
has text: Why do we have to use @functools.wraps(method)?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90098057
comment on: http://stackoverflow.com/a/51565604
score: 0
type: AnswerComment
has text: Interesting. I did not know how to put it in those terms
type: Comment

http://stackoverflow.com/q/51604425
has comment: http://stackoverflow.com/comment/90184842
type: Question
tagged with: datareader
downvote count: 0
tagged with: stock
tagged with: pandas
tagged with: symbols
has comment: http://stackoverflow.com/comment/90174607
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has body: I'm a beginner in python working with stock data. This morning I was able to extract stock data from the morningstar website fine, however when I try to do so now I receive the following error message shown below. What could be causing this issue and what can I do to fix it? Thanks Exception Traceback (most recent call last) in () 63 ''' 64 ---&gt; 65 df=web.DataReader('MMM','morningstar', start, end) 66 print(df) 67 stockname=df.to_csv('mmm.csv') ~\Documents\New folder (2)\lib\site-packages\pandas_datareader\data.py in DataReader(name, data_source, start, end, retry_count, pause, session, access_key) 389 return MorningstarDailyReader(symbols=name, start=start, end=end, 390 retry_count=retry_count, pause=pause, --&gt; 391 session=session, interval="d").read() 392 elif data_source == 'robinhood': 393 return RobinhoodHistoricalReader(symbols=name, start=start, end=end, ~\Documents\New folder (2)\lib\site-packages\pandas_datareader\mstar\daily.py in read(self) 217 "type %s" % type(self.symbols)) 218 --&gt; 219 df = self._dl_mult_symbols(symbols=symbols) 220 if len(df.index.levels[0]) == 0: 221 raise ValueError("None of the provided symbols were valid") ~\Documents\New folder (2)\lib\site-packages\pandas_datareader\mstar\daily.py in _dl_mult_symbols(self, symbols) 128 else: 129 raise Exception("Request Error!: %s : %s" % ( --&gt; 130 resp.status_code, resp.reason)) 131 132 time.sleep(self.pause) Exception: Request Error!: 404 : Not Found
tagged with: python
has title: Python Datareader cannot extract stock data from Morningstar
has answer: http://stackoverflow.com/a/51618588
score: 2

http://stackoverflow.com/a/51564176
has comment: http://stackoverflow.com/comment/90149752
has comment: http://stackoverflow.com/comment/90138285
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90158775
has body: I guess the errors you got are because your spec file didn't include all necessary CEF binary files. There is an official pyinstaller example that you can use and modify to use --onefile option: https://github.com/cztomczak/cefpython/blob/master/examples/pyinstaller/README-pyinstaller.md
type: Answer
has comment: http://stackoverflow.com/comment/90138269
has comment: http://stackoverflow.com/comment/90147586
accepted answer of: http://stackoverflow.com/q/51558349
has comment: http://stackoverflow.com/comment/90135970
score: 1
answers question: http://stackoverflow.com/q/51558349
has comment: http://stackoverflow.com/comment/90150216
has comment: http://stackoverflow.com/comment/90181983
has comment: http://stackoverflow.com/comment/90159266
has comment: http://stackoverflow.com/comment/90148878
has comment: http://stackoverflow.com/comment/90191498

http://stackoverflow.com/a/51520814
has comment: http://stackoverflow.com/comment/90036103
type: AcceptedAnswer
downvote count: 0
has body: Usestr.split with stack, also for remove NaNs is used DataFrame.dropna. EDIT: By OP comment was removed duplicated in the end with sorting values: df2 = (df.dropna(subset=['id2']) .set_index('id1')['id2'] .str.split('|', expand=True) .stack() .reset_index(level=1, drop=True) .reset_index(name='id2') .sort_values(by=['col1', 'col2']) .drop_duplicates(['col1','col2'])) print (df2) id1 id2 0 g1 ID:05434 2 g1 ID:38720 3 g1 ID:33345
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51520746
answers question: http://stackoverflow.com/q/51520746

http://stackoverflow.com/q/51489400
accepted answer: http://stackoverflow.com/a/51498273
type: Question
has comment: http://stackoverflow.com/comment/89962923
has body: I may be making this a lot harder than it has to be. data frame looks like this: CHROMOSOME START END CHR1 100 200 CHR2 300 400 my goal is to make a data frame from this with 4 rows that looks like this. CHROMOSOME START END LABEL CHR1 150 250 ROW_1_A CHR1 170 270 ROW_1_B CHR2 350 300 ROW_2_A CHR2 370 400 ROW_2_B So I need to take each row, split it into A and B, and modify start and end, and then label the row A or B and rebuild this back into a data frame. Here is my function to split, modify, and label a single row. def getcoordinates(df, awindow = 500, bwindow = 500): index = df[0] chromosome = df[1] start = df[2] end = df[3] sv_length = df[8] track = {'CHROMOSOME': chromosome, 'START': start, 'END': end} track = pd.DataFrame(data=track, index=[0]) trackA = track.copy() trackB = track.copy() trackA = trackA.assign(LABEL = ("AVN_DEL_" + str(index) + "_A")) trackB = trackB.assign(LABEL = ("AVN_DEL_" + str(index) + "_B")) trackA = trackA.assign(END = trackA["START"]) trackA = trackA.assign(START = trackA["START"] - awindow) trackB = trackB.assign(START = trackB["END"]) trackB = trackB.assign(END = trackB["END"] + bwindow) return trackA.append(trackB) here is my for loop to perform this on each row in the dataframe and reassemble. appended_data = [] for row in SV.itertuples(): print(row) out = getcoordinates(row) appended_data.append(out) appended_data = pd.concat(appended_data, axis=1) here is the actual code being run. appended_data = [] for row in SV.itertuples(): print(row) out = getcoordinates(row) appended_data.append(out) appended_data = pd.concat(appended_data, axis=1) Pandas(Index=0, CHROMOSOME=u'chr1', START=56365453, END=56369289, SV_TYPE=u'DEL', CALLERS=u'GROM;delly;manta;lumpy', LEFT_JUNCTION=u'L1M', RIGHT_JUNCTION=u'L1M', SV_LENGTH=3836, _9=u'DGV', FULL_INFO_ABOUT_ME=u'4_L1MC4_56365281_56365445_92_2.4;L1HS_56365452_56369282_101_2.63;L1HS_56365452_56369282_93_2.42;L1MC4_56369289_56369625_100_2.61') Pandas(Index=1, CHROMOSOME=u'chr1', START=75645801, END…
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/89962865
has title: pandas - Iterate dataframe rows, modify them, and rebuild a data frame in a for loop pandas
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51498273

http://stackoverflow.com/comment/90240598
comment on: http://stackoverflow.com/a/51636569
type: AnswerComment
score: 1
has text: @jezrael yes I see, I have a question about it because I copy and paste your code, and still find `np.select` faster (around 82ms) than `map` (around 154ms) for the lists of size 100. Do you know if it's because I use python 2.7 and not 3 like you probably. I read that `map`/`zip` are generator in python 3 which probably have an effect on speed? or it's something else?
type: Comment

http://stackoverflow.com/comment/90078859
comment on: http://stackoverflow.com/a/51551212
type: AnswerComment
has text: @anky_91 - I get one idea, please check edited answer.
score: 0
type: Comment

http://stackoverflow.com/a/51646448
type: Answer
answers question: http://stackoverflow.com/q/51572868
has body: Try to use FSM. Some libraries (for example aiogram) has built-in instruments and examples of usage. But if your library don't have FSM - you can make your own simple state machine. Just save user step to the dictionary. states = {} # key - user_id, value - state def abstract_handler(...): if not states.get(user_id): # ask user about his first name here states[user_id] = 'first name' return if states.get(user_id) == 'first name': first_name = message.text # ask about second name here states[user_id] = 'second name' return if states.get(user_id) == 'second name': second_name = message.text # etc P.S.: it's just simple explanation of process. You can split this code to several handlers. And don't forget to save user data. P.P.S: don't call variables with CamelCase :)
score: 0

http://stackoverflow.com/q/51634658
has answer: http://stackoverflow.com/a/70537552
score: 2
downvote count: 0
type: UnansweredQuestion
tagged with: scrapy
type: Question
has body: I am trying to get the cookies from a splash request, but I keep getting an error. Here is the code I am using: class P2PEye(scrapy.Spider): name = 'p2peyeSpider' allowed_domains = ['p2peye.com'] start_urls = ['https://www.p2peye.com/platform/h9/'] def start_requests(self): script = ''' function main(splash) local url = splash.args.url assert(splash:go(url)) assert(splash:wait(0.5)) return { cookies = splash:get_cookies(), } end ''' for url in self.start_urls: yield SplashRequest(url, callback=self.parse, endpoint='render.html',args={'wait': 1, 'lua_source': script}) def parse(self, response): print(response.request.headers.getlist('Set-Cookie')) print(response.cookiejar) This is my settings.py SPLASH_URL = 'http://127.0.0.1:8050' CRAWLERA_ENABLED= False DOWNLOADER_MIDDLEWARES = { 'scrapy_splash.SplashCookiesMiddleware': 723, 'scrapy_splash.SplashMiddleware': 725, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, } SPIDER_MIDDLEWARES = {'scrapy_splash.SplashDeduplicateArgsMiddleware': 100 } DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter' HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage' COOKIES_ENABLED = True COOKIES_DEBUG = True SPLASH_COOKIES_DEBUG = True The result of response.request.headers.getlist('Set-Cookie') is [], and response.cookiejar got an error: AttributeError: 'SplashTextResponse' object has no attribute 'cookiejar'. So how can I get the cookies without causing an error?
upvote count: 2
has answer: http://stackoverflow.com/a/51654197
answer count: 2
tagged with: splash-screen
favorite count: 0
has title: Scrapy: How to get cookies from splash
tagged with: python

http://stackoverflow.com/comment/89976312
type: QuestionComment
score: 1
has text: The problem is that without knowing what your use case is, it’s next to impossible to guess what answer will satisfy you. The fact that you’re refusing to answer people’s questions doesn’t help.
comment on: http://stackoverflow.com/q/51503591
type: Comment

http://stackoverflow.com/q/51627909
has answer: http://stackoverflow.com/a/51647150
type: Question
score: 0
answer count: 1
tagged with: distutils
tagged with: wildcard
tagged with: packaging
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90234768
has title: distutils wildcard entry for include_dir
tagged with: python
has body: I am setting up a package using distutils. I need to allow access to a module that is built during the set-up process and is located in ./build/temp.linux-x86_64-3.6. I do this by including the include_dirs=["./build/temp.linux-x86_64-3.6"] when adding the extension to the distutils Configuration. My question is there a way of setting this using a wildcard such as: include_dirs=["./build/temp.linux*"] as when I try this it fails, citing error: Nonexistent include directory ‘build/temp.linux*’ [-Wmissing-include-dirs] The reason I want this is that the build folder will be named differently depending on the system. Alternatively if anyone knows a way of figuring out what this temp build folder will be called that would also work.

http://stackoverflow.com/q/51639687
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51639798
has body: I have this code: import sys import argparse import operator def main (argv): parser = argparse.ArgumentParser() parser.add_argument('infile', help='file to process') parser.add_argument('outfile', help='file to produce') args = parser.parse_args() with open(args.infile, "r") as f: with open(args.outfile,"w+") as of: seen=set() for line in f: line_lower = line.lower() if line_lower not in seen: of.write(line_lower) else: pass if __name__ == "__main__": main(sys.argv)` Example of an infile: M03972:51:000000000-BJVL8:1:1103:20083:5527 CATGTTCGGCTTGGCCTACTTCTCTATGCAGGGAGCGTGGGCGAGAGTCGTTGTCATCCTTCTGCTGGCCGCCGGGGTGGACGCGCGCACCCATACTGTTGGGGGTTCTGCCGCGCAGACCACCGGGCGCCTCACCAGCTTATTTGACATGGGCCCCAGGCAGAAAATCCAGCTCGTTAACACCAATGGCAGCTGGCACATCAACCGCACCGCCCTGAACTGCAATGACTCCTTGCACACCGGCTTTATCG Sometimes there are duplicated sequences. I would like to remove them but I my code doesn't seem to work. It just duplicates the file basically but doesnt throw any error. Does anyone know why? Thank you
type: Question
score: 0
has title: How to filter out duplicated fasta sequences from a file
answer count: 1
tagged with: fasta
accepted answer: http://stackoverflow.com/a/51639798

http://stackoverflow.com/a/51581520
score: 0
answers question: http://stackoverflow.com/q/51581393
type: Answer
has body: import matplotlib as mpl mpl.rcParams['axes.linewidth'] = 0.4 # or any other thickness you want The second question is already answered here: How can I remove the top and right axis in matplotlib? For the size of axis values (scale): ax = fig.add_subplot(111) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(8) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(8)

http://stackoverflow.com/comment/89995170
type: QuestionComment
comment on: http://stackoverflow.com/q/51513386
has text: Consider warning the user that if you had to cleanup in `__del__` then their program is actually broken...
type: Comment
score: 2

http://stackoverflow.com/a/64932753
has body: You can import: from bokeh.plotting import output_notebook And call output_notebook before your figures declaration, then you just show the figure using show. See the doc.
has comment: http://stackoverflow.com/comment/114802847
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51512907

http://stackoverflow.com/a/51520512
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/51520410
has body: I'm not sure about directly doing it with Pandas, but you can do this easily enough if you don't mind using numpy.diag() to build the diagonal data matrix for your series and then plugging that into a DataFrame: diag_data = np.diag(s) # don't need s.as_matrix(), turns out df = pd.DataFrame(diag_data, index=s.index, columns=s.index) a b c a 1 0 0 b 0 2 0 c 0 0 3 In one line: df = pd.DataFrame(np.diag(s), index=s.index, columns=s.index) Timing comparison with a Series made from a random array of 10000 elements: s = pd.Series(np.random.rand(10000), index=np.arange(10000)) df = pd.DataFrame(np.diag(s), ...) 173 ms ± 2.91 ms per loop (mean ± std. dev. of 7 runs, 20 loops each) df = pd.DataFrame(0, ...) np.fill_diagonal(df.values, s) 212 ms ± 909 µs per loop (mean ± std. dev. of 7 runs, 20 loops each) mat = np.zeros(...) np.fill_diagonal(mat, s) df = pd.DataFrame(mat, ...) 175 ms ± 3.72 ms per loop (mean ± std. dev. of 7 runs, 20 loops each) It looks like the first and third option shown here are essentially the same, while the middle option is the slowest.
score: 6
downvote count: 0

http://stackoverflow.com/comment/90095521
type: QuestionComment
has text: yeah thanks, I tried messing around with the indentation before that and as you say I would expect a different error from that.
type: Comment
comment on: http://stackoverflow.com/q/51564270
score: 0

http://stackoverflow.com/comment/89938277
type: Comment
type: QuestionComment
has text: Just curious, did you actually write this code yourself, or are you using someone else's code?
comment on: http://stackoverflow.com/q/51484630
score: 0

http://stackoverflow.com/a/51532440
upvote count: 0
score: -1
answers question: http://stackoverflow.com/q/51531713
has body: In many cases curpop[:]= iterable_value_as_tuple_string_dictionary_and_list_etc do the same thing as curpop=iterable_value_as_tuple_string_dictionary_and_list_etc of course assign a string first or at any step will remove the ability in the next steps to use [:] to assign something again note that curpop[:]= notiterable_value != curpop=notiterable_value as the first assign notiterable_value to each element of curpop and the second assign the value notiterable_value to curpop itself
type: Answer
downvote count: 1

http://stackoverflow.com/comment/90109807
has text: Have you tried `buildozer android deploy run logcat` to see the logcat output?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51569131

http://stackoverflow.com/a/51528060
has body: How do you get these realy slow timings? Code import numba as nb import numpy as np import time a1 = np.array(np.random.random(500000) * 1000) a2 = np.array(np.random.random(500000) * 5000) @nb.jit(nb.float64(nb.float64[:], nb.float64[:]),parallel=True,fastmath=True) def nb_max_min(s1, s2): return np.max(s1) - np.min(s2) def np_max_min(s1,s2): return np.max(s1) - np.min(s2) t1=time.time() for i in range(10000): res_1=np_max_min(a1, a2) print(str((time.time()-t1)/10)+ ' ms') t1=time.time() for i in range(10000): res_2=nb_max_min(a1, a2) print(str((time.time()-t1)/10)+ ' ms') np.allclose(res_1,res_2) Results Numpy: 0.298ms (=26.8 GB/s) Numba: 0.243ms (=33 GB/s) Discussion This simple operations are memory limited. The max. memory throughput of my Core i7-4th gen is 25,6GB/s. Numba even significantly exceeds the memory bandwith, because of cache-effects (The problems fits more or less in the L3-cache).The timings in real code may be lower because the input arrays may not be already in L3-cache.
accepted answer of: http://stackoverflow.com/q/51523034
has comment: http://stackoverflow.com/comment/90027580
type: Answer
answers question: http://stackoverflow.com/q/51523034
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/51495003
has comment: http://stackoverflow.com/comment/89958492
has comment: http://stackoverflow.com/comment/89958853
has comment: http://stackoverflow.com/comment/89959264
tagged with: http://stackoverflow.com/tag/xml
tagged with: xpath
has comment: http://stackoverflow.com/comment/89958812
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89959456
has body: sdfsdf mathsenglish <m>80</m><m>90</m><m>100</m> sdfsdf scienceenglish <m>70</m><m>90</m><m>100</m> sdfsdf computerenglish <m>40</m><m>90</m><m>100</m> Code: def getXmlElementData(xmlfilename, node, attr, name, element): collection = getXmlCollectionData(xmlfilename) nodes = collection.getElementsByTagName(node) for node in nodes: if node.hasAttribute(attr) and node.getAttribute(attr) == name: info = node.getElementsByTagName(element)[0] elementValue = info.childNodes[0].data return elementValue In this example I could access the info value by passing the node and attr name. But how can we access the sub and m elements by passing the xpath Thanks in advance
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/89959644
tagged with: dom
type: Question
has title: How to access the childnodes based on the name attribute in python
score: 0

http://stackoverflow.com/comment/96273748
type: Comment
has text: @eyllanesc: created is the empty `qim = QImage()` array and `return qimg` when `im` is zero won't work. So it should be `return qim` and not `qimg`. In all other cases it keeps loading `qimg = NumpyToQImage(img)` and won't stop.
type: AnswerComment
comment on: http://stackoverflow.com/a/51608230
score: 0

http://stackoverflow.com/q/51564143
type: Question
has comment: http://stackoverflow.com/comment/90095258
has title: Finding max with multiple criteria
tagged with: max
has comment: http://stackoverflow.com/comment/90095257
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51569069
tagged with: python
tagged with: nested-lists
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90095327
upvote count: 1
has body: I have a series of nested lists: list1=[[10,5],[8,2],[12,10],[5,7],[12,11],[7,2],[5,3],[11,12]] I need to return the max list, using the first element of each list as a key - if there are two or more elements that match this condition, I need to return the one with the larger second element - (i.e, [12,11], not [12,10]). I have used max(list1,key=lambda x:x[0])), but this only returns the first element that matches - [12,10].

http://stackoverflow.com/comment/90202488
score: 0
comment on: http://stackoverflow.com/q/51618435
type: Comment
has text: Possible duplicate of [Pygame window not responding after a few seconds](https://stackoverflow.com/questions/20165492/pygame-window-not-responding-after-a-few-seconds)
type: QuestionComment

http://stackoverflow.com/comment/89964827
score: 0
type: Comment
type: QuestionComment
has text: You should use new style classes in python 2: inherit from object: `class A(object):` or better yet, python 3... That said, you cannot do what you intend to do
comment on: http://stackoverflow.com/q/51498477

http://stackoverflow.com/comment/89984527
comment on: http://stackoverflow.com/a/51505385
type: AnswerComment
type: Comment
has text: @physlexic see my update. If you just want to grab all of the matches from the file, it's even easier!
score: 1

http://stackoverflow.com/a/51497161
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51494886
accepted answer of: http://stackoverflow.com/q/51494886
has body: Found the answer, well an answer. I overwrite the on_touch_up event and use the transform ObjectProperty of the Scatter widget with a matrix of 1,1,1 like so from kivy.graphics.transformation import Matrix def on_touch_up(self, touch): trans = Matrix().scale(1, 1, 1) self.ids['myScat'].transform=trans
type: Answer

pygame
tags question: http://stackoverflow.com/q/51624383
tags question: http://stackoverflow.com/q/51490059
tags question: http://stackoverflow.com/q/51618435
tags question: http://stackoverflow.com/q/51613686
tags question: http://stackoverflow.com/q/51572481
tags question: http://stackoverflow.com/q/51548874
tags question: http://stackoverflow.com/q/51585285
tags question: http://stackoverflow.com/q/51513935
tags question: http://stackoverflow.com/q/51567670
tags question: http://stackoverflow.com/q/51599746
tag name: pygame
tags question: http://stackoverflow.com/q/51639365
tags question: http://stackoverflow.com/q/51614481
tags question: http://stackoverflow.com/q/51604716
tags question: http://stackoverflow.com/q/51540505
tags question: http://stackoverflow.com/q/51627603
tags question: http://stackoverflow.com/q/51507113
tags question: http://stackoverflow.com/q/51569281
tags question: http://stackoverflow.com/q/51634008
tags question: http://stackoverflow.com/q/51580173
tags question: http://stackoverflow.com/q/51636030
tags question: http://stackoverflow.com/q/51490162
tags question: http://stackoverflow.com/q/51505363
tags question: http://stackoverflow.com/q/51620956
type: Tag

http://stackoverflow.com/q/51572868
has comment: http://stackoverflow.com/comment/90115344
type: UnansweredQuestion
tagged with: python
type: Question
has body: I've got a really simple message_handler thing in my code which I expect to work this way: If user says "YES" then bot asks for first name and then for a second name. However, I don't get to ask first name and second name. But instead, my output would be: First Name: YES Second Name: YES How can I fix this? @bot.message_handler(content_types=['text']) def handle_text(message): if message.text == 'YES': bot.send_message(message.from_user.id, "Your first Name") FirstName = message.text bot.send_message(message.from_user.id, "Your second Name") SecondName = message.text bot.send_message(message.from_user.id, "First Name: " + str(FirstName) + " Second Name: " + str(SecondName))
has answer: http://stackoverflow.com/a/51646448
score: 0
answer count: 1
tagged with: telegram
has title: Telegram message_handler Python

http://stackoverflow.com/comment/90119235
type: Comment
comment on: http://stackoverflow.com/a/51576883
score: 0
type: AnswerComment
has text: @calvin Both your attempt in the question and this answer works on my machine. I'm using Python 2.7.10 and macOS HighSierra. Maybe something to do with the encoding of Windows?

http://stackoverflow.com/q/51629194
has body: Context: I implemented tests which use docker-py to create docker networks and run docker containers. The test runner used to execute the tests is pytest. The test setup depends on Python (Python package on my dev machine), on my dev machines docker daemon and my dev machines static ip address. In my dev machine runtime context the tests run just fine (via plain invocation of the test runner pytest). Now I would like to migrate the tests into gitlab-ci. gitlab-ci runs the job in a docker container which accesses the CI servers docker daemon via /var/run/docker.sock mount. The ip address of the docker container which is uses by gitlab-ci to run the job in is not static like in my dev machine context. But for the creation of the docker networks in the test I need the ip address. Question: How can I get the appropriate ip address of the docker container the tests are executed in with Python?
tagged with: docker
has title: How can I get the host ip in a docker container using Python?
score: 2
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51630443
tagged with: python
tagged with: gitlab
tagged with: dockerpy
upvote count: 2
has comment: http://stackoverflow.com/comment/90225714
answer count: 1
has comment: http://stackoverflow.com/comment/90224527
type: UnansweredQuestion

http://stackoverflow.com/q/51626749
tagged with: image-processing
type: Question
accepted answer: http://stackoverflow.com/a/51627566
downvote count: 0
answer count: 1
favorite count: 0
has title: image Log transformation in python open cv
upvote count: 1
tagged with: python
has body: I am learning image processing and I've come across image log processing. I have googled about it, watched youtube videos but I am unable to correctly code it. I am using following code: img = cv2.imread('spectrum.jpg') img00=np.uint8(np.log1p(img)) _, img3 = cv2.threshold(img00, 55, 255, cv2.THRESH_BINARY) cv2.imshow('log',img3) cv2.waitKey(0) cv2.destroyAllWindows()
tagged with: opencv
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51627566

http://stackoverflow.com/comment/113777206
has text: Bokeh `Figure` objects do not have a `show` method.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/55855750

http://stackoverflow.com/comment/90157735
comment on: http://stackoverflow.com/q/51594990
has text: If I run that with IDLE 3.7 (32 bit) it works
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51567728
type: Question
accepted answer: http://stackoverflow.com/a/51620699
answer count: 2
possible better answer: http://stackoverflow.com/a/55111310
has body: I am using a pretrained model by TensorFlow , Attention ocr https://github.com/tensorflow/models/tree/master/research/attention_ocr While running eval.py the script always runs into an error File "C:\Users\DELL\Anaconda3\envs\python35DL\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 519, in __exit__ c_api.TF_GetCode(self.status.status)) tensorflow.python.framework.errors_impl.NotFoundError: NewRandomAccessFile failed to Create/Open: D:\Vision_Project\attention_ocr\python\data/fsns\charset_size=134.txt : The system cannot find the path specified. ; No such process I am unable to understand which path it cannot find , where and how do I fix this in the script . System Configurations (if it matters) : Windows 10 , 8gb RAM , Core i3 , 1 TB HDD Tensorflow Version : 1.8.0 Python Version : 3.5 running through VirtualEnv
downvote count: 0
tagged with: python
tagged with: ocr
favorite count: 0
tagged with: python-3.x
upvote count: 2
has title: NewRandomAccessFile failed to create/open ; Attention_OCR
tagged with: tensorflow
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/51620699
has answer: http://stackoverflow.com/a/55111310

http://stackoverflow.com/comment/90192479
comment on: http://stackoverflow.com/q/51612876
score: 1
has text: You are trying to print the entire list of objects. Instead, try to access the individual item in the list.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51507820
type: Question
score: 5
has answer: http://stackoverflow.com/a/55812426
upvote count: 5
answer count: 1
downvote count: 0
tagged with: optimization
has comment: http://stackoverflow.com/comment/90028307
has comment: http://stackoverflow.com/comment/89985441
linked to: http://stackoverflow.com/q/89228
has title: Optimizing svg using scour or any other optimizer in Python
tagged with: parsing
has comment: http://stackoverflow.com/comment/90031823
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
tagged with: http://stackoverflow.com/tag/svg
type: UnansweredQuestion
has body: I have been using scour and it works well. I would like to use it inside a Python app instead of a cli. I would like the output to be the same as when I run the following command on CMD: scour -i input.svg -o output.svgz --enable-viewboxing --enable-id-stripping \ --enable-comment-stripping --shorten-ids --indent=none Can't find any documentation how to call this function inside a python application
tagged with: python
has comment: http://stackoverflow.com/comment/90039767

http://stackoverflow.com/q/51625357
has title: I want to use tensorflow's metric(pearson correlation) in Keras
has answer: http://stackoverflow.com/a/54817610
upvote count: 1
answer count: 1
tagged with: keras
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I want to use tensorflow's metrics(streaming pearson correlation) in keras. I search and write this code. But this score which my code calculate doesn't match the score which numpy(corrcoef) calculated. def correlation_coefficient(y_true, y_pred): pearson_r, update_op = tf.contrib.metrics.streaming_pearson_correlation(y_pred, y_true) # find all variables created for this metric metric_vars = [i for i in tf.local_variables() if 'correlation_coefficient' in i.name.split('/')[1]] # Add metric variables to GLOBAL_VARIABLES collection. # They will be initialized for new session. for v in metric_vars: tf.add_to_collection(tf.GraphKeys.GLOBAL_VARIABLES, v) # force to update metric values with tf.control_dependencies([update_op]): pearson_r = tf.identity(pearson_r) return pearson_r
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90222176
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/51606837
score: -4
type: Question
tagged with: regex
has comment: http://stackoverflow.com/comment/90178881
favorite count: 0
downvote count: 6
tagged with: python-3.x
upvote count: 2
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/90178954
has answer: http://stackoverflow.com/a/51607046
has answer: http://stackoverflow.com/a/51607047
has title: Regex - replace space in string that has '.com Capital letter' with new line
has body: I have a string with a space that I need to replace. The pattern is .com followed by a space and then any capital letter. An example would be: ".com T" The space between the .com and T needs to be replaced by a new line.
has comment: http://stackoverflow.com/comment/90178995
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51607198

http://stackoverflow.com/comment/90205653
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51591897
has text: Actually I tried to save after all iterations have finished but still the ram was building up, so I iterated the save so that I could stop manually in between and restart the system to free the RAM and start from where I stopped. Could this be a problem with my computers RAM management?

http://stackoverflow.com/q/51530012
has title: How can I run an async function using the schedule library?
tagged with: python
has body: I'm writing a discord bot using discord.py rewrite, and I want to run a function every day at a certain time. I'm not experienced with async functions at all and I can't figure out how to run one without using "await." This is only a piece of my code which is why some things may not be defined. async def send_channel(): try: await active_channel.send('daily text here') except Exception: active_channel_id = None active_channel = None async def timer(): while True: schedule.run_pending() await asyncio.sleep(3) schedule.every().day.at("21:57").do(await send_channel()) @bot.event async def on_ready(): print("Logged in as") print(bot.user.name) print(bot.user.id) print("------") bot.loop.create_task(timer()) Using the schedule.every().day.at("00:00").do() function, I get this error when I put await send_channel() in the paramaters of .do(): self.job_func = functools.partial(job_func, *args, **kwargs) TypeError: the first argument must be callable But when I don't use await, and I just have send_channel() as parameters, I get this error: RuntimeWarning: coroutine 'send_channel' was never awaited I'm not super good at programming so if someone could try to dumb it down for me that would be awesome. Thanks
has answer: http://stackoverflow.com/a/54726962
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51530161
upvote count: 24
tagged with: discord.py
has answer: http://stackoverflow.com/a/61180222
has answer: http://stackoverflow.com/a/73656300
tagged with: async-await
score: 24
type: Question
downvote count: 0
answer count: 7
tagged with: schedule
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/61168314
has answer: http://stackoverflow.com/a/78087518
has answer: http://stackoverflow.com/a/61918209

http://stackoverflow.com/comment/139611708
comment on: http://stackoverflow.com/a/60745616
type: AnswerComment
has text: Wow you are an angel from up above.
type: Comment
score: 1

http://stackoverflow.com/comment/90063630
type: QuestionComment
has text: A DLL file as is stated in the error... open the file and see what module it's trying to import. Make sure you have that module installed.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51547826

http://stackoverflow.com/comment/90097176
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51559696
has text: Thanks, this I know. But how do I get the program to halt after plt.show(), let the user interact with the figure and proceed with print(slider.val) only after the figure closing?
score: 0

http://stackoverflow.com/comment/90012399
type: Comment
comment on: http://stackoverflow.com/a/51520929
has text: Thank you for your response! If I want to read in the .txt files as a loop to parse through the contents of each .txt file, how would I best do that?
type: AnswerComment
score: 0

http://stackoverflow.com/q/51624082
has answer: http://stackoverflow.com/a/51624473
has title: How to delete bot direct messages?
type: UnansweredQuestion
downvote count: 2
type: Question
tagged with: discord.py
score: -1
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: So, long story short I was making a bot that's supposed to send a direct message to a user after a command was executed, then wait a bunch of time before deleting it It works fine and all now, but for a bit of time it didn't, and while I did some testing, my dms with that bot have been flooded with test messages Is there any command I could add to delete every old messages that this bot sent to my dms ?
tagged with: python

http://stackoverflow.com/a/51489457
accepted answer of: http://stackoverflow.com/q/51487626
has body: Yes, the quantity called alpha in scipy.stats.rv_continuous.interval would be called 1-alpha in statistics textbooks. You are not missing anything. It's just a suboptimal name choice. The only discussion of the name of that parameter that I found concerned a different name collision: Sigh. Given that both interval and levy_stable are quite esoteric,[...]
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51487626
downvote count: 0
score: 1

sh
tags question: http://stackoverflow.com/q/51500403
type: Tag
tag name: sh

http://stackoverflow.com/comment/90129433
type: Comment
comment on: http://stackoverflow.com/a/51581837
has text: @Venice Did you assign in the left-hand side as `sec_pivot.loc[sec_pivot.index != 'Total', 1:]` = ?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90217182
type: Comment
type: QuestionComment
has text: You may want to check [this issue on github](https://github.com/tesseract-ocr/tesseract/issues/825). Looks like you cant use it from the command line but can still get the information from the API.
score: 0
comment on: http://stackoverflow.com/q/51626003

http://stackoverflow.com/a/51488793
has comment: http://stackoverflow.com/comment/89946535
has comment: http://stackoverflow.com/comment/89947014
has comment: http://stackoverflow.com/comment/89946915
has comment: http://stackoverflow.com/comment/89947223
upvote count: 1
answers question: http://stackoverflow.com/q/51488731
type: Answer
has comment: http://stackoverflow.com/comment/89946727
downvote count: 0
score: 1
has body: Try to do it in the constructor. class PersonForm(forms.ModelForm): class Meta: model = Person fields = '__all__' def __init__(self, *args, **kwargs): super(PersonForm, self ).__init__(*args, **kwargs) self.fields['extra_field'] = forms.FileInput() And since you are using the django admin, you need to change the form in the admin too.
has comment: http://stackoverflow.com/comment/89946790

http://stackoverflow.com/comment/90097807
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51565436
has text: *"Alas, the ouput byte object has a length of 4!"* I'm confused. The array `foo` contains one element of type `uint32` (i.e. an unsigned 32 bit integer). That's four bytes. Why are you disappointed that the length of `bar` is 4?
score: 0

http://stackoverflow.com/q/51594822
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51594870
has comment: http://stackoverflow.com/comment/90180466
has answer: http://stackoverflow.com/a/51594870
type: Question
tagged with: opencv
has body: I want to select the region where the Data Matrix is placed. import cv2 from matplotlib import pyplot as plt img1 = cv2.imread('C:\\Users\\MyAccount\\Desktop\\datamatrix.png') dmc = img1[300:588, 1225:1512] plt.imshow(dmc) plt.show() I only receive a slim white area, but not a single region of this matrix. The ROI-Formular is [y:y+h, x:x+w], but it is not working. The image has the size 1240 x 626. The matrix has the attributes: left=938, top=323, width=287, height=288.
accepted answer: http://stackoverflow.com/a/51607714
has title: Python: OpenCV - Selecting Region of an Image
has comment: http://stackoverflow.com/comment/90155462
score: 0
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/90178360
has answer: http://stackoverflow.com/a/51607714
has answer: http://stackoverflow.com/a/51608810

http://stackoverflow.com/q/51543276
has answer: http://stackoverflow.com/a/51543942
accepted answer: http://stackoverflow.com/a/51544038
tagged with: python
has body: I tried to import some data from an Excel file to a pandas DataFrame, convert it into a csv file and read it back in (need to do some further file based handling on that exported csv file later on, so that is a necessary step). For the sake of data integrity, exported and re-imported data should be the same. So, I compared the different DataFrames and encountered, that these are not the same, at least according to pandas' .equals() function. I thought this might be an issue related to string encoding when exporting and re-importing the data since I had to transfer char encoding etc. while file handling. However, I was able to reproduce similar behavior without any encoding-related issues as follows: import pandas as pd import numpy as np # https://stackoverflow.com/a/32752318 df1 = pd.DataFrame(np.random.randint(0, 10, size=(10, 4)), columns=list('ABCD')) df1.to_csv('foo.csv', index=False) df2 = pd.read_csv('foo.csv') df1.to_csv('bar.csv', index=True) df3 = pd.read_csv('bar.csv') print(df1.equals(df2), df1.equals(df3), df2.equals(df3)) print(all(df1 == df2)) Why does .equals() tell that the DataFrames differ, but all(df1 == df2) tells they are equal? According to the docs, .equals() even considers NaNs at same locations to be equal, whereas df1 == df2 should not. Due to this, comparing different DataFrames with .equals() is less strict than df1 == df2, but does not return the same result in the example I provided. Which criteria do df1 == df2 and df1.equals(df2) consider I am not aware of? I assume, that the implementation inside pandas is correct (did not look into the implementation inside the code itself, but export and re-import should be a standard interface test case). What am I doing wrong then?
type: AnsweredQuestion
score: 0
has title: Exported and imported DataFrames differ but should be the same
tagged with: dataframe
tagged with: import
type: Question
tagged with: export-to-csv
answer count: 2
has answer: http://stackoverflow.com/a/51544038
linked to: http://stackoverflow.com/q/32752292
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51543942

http://stackoverflow.com/a/51562757
type: Answer
answers question: http://stackoverflow.com/q/51541109
score: 1
has body: when I'm writing this data to excel using to_excel method it's just removing .00 from last value of "Active Time Spent" column. That is how Excel works. If you enter 14.00 in a cell it will display it as 14 (without a decimal place). If you want to display it as 14.00 you need to add a number format in Excel. Here is an example of how to do that with Pandas and XlsxWriter.
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/51621882
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51621823
answers question: http://stackoverflow.com/q/51621823
type: Answer
has body: Your numbers are not equal to 3 decimal places, as defined by assertAlmostEqual: Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero. The difference between your numbers, rounded to 3 decimal places, is 0.001.
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90209348
has comment: http://stackoverflow.com/comment/90209352
type: AcceptedAnswer

http://stackoverflow.com/q/51556500
possible better answer: http://stackoverflow.com/a/51556692
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90079662
answer count: 2
has title: Subprocess for loop fails with syntax error
favorite count: 0
score: 0
has body: I have a simple script in order to understand how one can run a shell for loop inside a subprocess call. I'm running it from GNU/Linux, inside a virtual enviroment and a BASH shell. The script: from subprocess import call shellCommand = ['for','c','in','$(seq 1 10)','do','echo','$c','done'] call(shellCommand, shell=True) And the error message: c: 1: c: Syntax error: Bad for loop variable What am I doing wrong here?
has answer: http://stackoverflow.com/a/51556651
tagged with: shell
has answer: http://stackoverflow.com/a/51556692
has comment: http://stackoverflow.com/comment/90079566
accepted answer: http://stackoverflow.com/a/51556651
tagged with: subprocess

http://stackoverflow.com/q/51533619
has comment: http://stackoverflow.com/comment/90034949
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/90060830
score: 1
has comment: http://stackoverflow.com/comment/90060977
type: Question
has body: I'm using BeautifulSoup to do some webscraping in Python, which involves accessing about 500 similar webpages for data to put in a .txt file. However, I'm having some problems: The CPU usage for my program (checked through task manager) randomly drops to 0% and stays that way. My command prompt itself becomes unresponsive as Ctrl + C won't kill the program. This has occurred at seemingly random times, anywhere between the 8th webpage and the 480th. def getAnime(): for index in range(2, 502): # gets anime statistics from HTML container = containers[index] ranking = container.td.text name = container.findAll('td', {'class', 't'}) link = 'https://www.animenewsnetwork.com' + name[0].a['href'] name = name[0].text statistics = container.findAll('td', {'class', 'r'}) rating = statistics[0].text numVotes = statistics[1].text # prints out anime stats to file currentAnime = Anime(name, ranking, rating, numVotes, link) animeFile.write('\nname: ' + name) animeFile.write('\nlink: ' + link) animeFile.write('\nranking: ' + ranking) animeFile.write('\nrating: ' + rating) animeFile.write('\nvotes: ' + numVotes) # Goes to the webpage for the current anime animeClient = uReq(link) animeHTML = animeClient.read() animeClient.close() pageSoup = soup(animeHTML, 'html.parser') # Genres of the current anime try: genreDiv = pageSoup.find(id='infotype-30') genres = genreDiv.findAll('span') genreList = [] for genre in genres: genreList.append(genre.a.text) currentAnime.genres = genreList except: currentAnime.genres = 'unknown' # Themes of the current anime try: themes = pageSoup.find(id='infotype-31').findAll('span') themeList = [] for theme in themes: themeList.append(theme.a.text) currentAnime.themes = themeList except: currentAnime.themes = 'unknown' # Premiere date of the current anime try: date = pageSoup.find(id='infotype-9').div.text currentAnime.premiereDate = date except: currentAnime.premiereDate = 'unknown' # Director of the current anime try: director = pageSoup.find('b', text='Dir…
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90062523
tagged with: beautifulsoup
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51546694
accepted answer: http://stackoverflow.com/a/51546694
has comment: http://stackoverflow.com/comment/90060919
downvote count: 2
has title: Python program randomly hangs up
tagged with: web-scraping
tagged with: python

http://stackoverflow.com/q/51536294
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1832940
tagged with: python
has body: I have a very simple case in which I want to run a script with python myscript.py: from models import Company c = Company(number="1234567890", name="Company name") models.py: from django.db import models class Company(models.Model): number = models.CharField("company number", max_length=20, unique=True) name = models.CharField("company name", max_length=30, unique=True) class Meta: verbose_name = "Company" verbose_name_plural = "Companies" I want to run python myscript.py or something like python manage.py execute_file myscript.py I know my question is trivial and I can import a python manage.py shell environment, but that's not the point. Can I run it in a much simple manner?
upvote count: 2
tagged with: django
answer count: 1
has answer: http://stackoverflow.com/a/51536416
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90040059
score: 2
downvote count: 0
has title: I want to start a python file that containing imports from django library in the OS shell

http://stackoverflow.com/a/51598483
answers question: http://stackoverflow.com/q/51597849
score: 0
has comment: http://stackoverflow.com/comment/90170438
type: Answer
has body: To my knowledge there is no such numpy function with those exact specific requirements, however what you can do is have your array: ` In [10]: arr = np.array([(1,2,3),(4,5,6),(7,8,9)]) In [11]: arr Out[11]: array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])` Then pad it: In [12]: arr = np.pad(arr, ((2,1),(0,0)), 'constant', constant_values=(0)) In [13]: arr Out[13]: array([[0, 0, 0], [0, 0, 0], [1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]]) Then you can randomize with shuffle (which I assume is what you want to do): But np.random.shuffle only shuffles rows if this is satisfactory for your needs then: In [14]: np.random.shuffle(arr) In [15]: arr Out[15]: array([[7, 8, 9], [4, 5, 6], [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 2, 3]]) If this is not satisfactory you can do this: First create a 1D array: In [16]: arr = np.arange(1,10) In [17]: arr Out[17]: array([1, 2, 3, 4, 5, 6, 7, 8, 9]) Then pad your array with zeros: In [18]: arr = np.pad(arr, (6,3), 'constant', constant_values = (0)) In [19]: arr Out[19]: array([0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0]) Then you shuffle the array: In [20]: np.random.shuffle(arr) In [21]: arr Out[21]: array([4, 0, 0, 5, 0, 0, 3, 0, 0, 0, 8, 0, 7, 2, 1, 6, 0, 9]) Finally you reshape to the desired format: In [22]: np.reshape(arr,[6,3]) Out[22]: array([[4, 0, 0], [5, 0, 0], [3, 0, 0], [0, 8, 0], [7, 2, 1], [6, 0, 9]]) Although this may seem lengthy this is much quicker for large data sets than it will be using for loops, or any other python control structures. When you say offsets if you want to change the amount of randomness you can choose to only shuffle portions of the 1D array then combine it to the rest of the data so that way the whole data set is not shuffled but a portion you want to be shuffled is. (If what you mean by offsets is different from my assumption above please clarify in a comment)
has comment: http://stackoverflow.com/comment/90164239
has comment: http://stackoverflow.com/comment/90170575

http://stackoverflow.com/q/51622185
downvote count: 1
has comment: http://stackoverflow.com/comment/90210067
has comment: http://stackoverflow.com/comment/90210120
score: 2
has comment: http://stackoverflow.com/comment/90210857
linked to: http://stackoverflow.com/q/2803852
has answer: http://stackoverflow.com/a/51622231
type: Question
duplicate of: http://stackoverflow.com/q/2803852
has title: Quick way to convert string to date in python
answer count: 1
favorite count: 0
has body: Is there a quick way to convert a string to a datetime object in Python WITHOUT having to specify the format? I know I can do: datetime.strptime('Sun 10 May 2015 13:54:36 -0700', '%a %d %b %Y %H:%M:%S %z') But since this is the default format, is there someway to get it to autoparse? Seems like I should be able to just create a new object from this without having to specify the format since it is the default system format.
upvote count: 3
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51538991
downvote count: 0
has comment: http://stackoverflow.com/comment/97857162
score: 1
has body: This seems to be an issue in requests_toolbelt which might be fixed in 0.7.1. Try to install newest version of it. https://github.com/mvantellingen/python-zeep/issues/413
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90045522
answers question: http://stackoverflow.com/q/51538779

http://stackoverflow.com/comment/90237974
type: Comment
has text: Why use `.*?$`? `.*$` will work fine in multi-line mode.
comment on: http://stackoverflow.com/a/51636720
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90117645
comment on: http://stackoverflow.com/q/51575997
score: 1
type: Comment
has text: You must have a local module that is able to be imported. That's a different concept of actually getting those modules to other machines. Since you're not using an external Spark Cluster scheduler, and only running locally where all modules are available to you, then there is no need for that argument
type: QuestionComment

http://stackoverflow.com/comment/90236415
type: QuestionComment
has text: Do you mind following up with us by emailing cloudml-feedback@google.com so we can help examine your logs?
comment on: http://stackoverflow.com/q/51581039
score: 0
type: Comment

http://stackoverflow.com/q/51494857
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/51496336
score: 2
type: AnsweredQuestion
tagged with: matplotlib
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/89959324
has answer: http://stackoverflow.com/a/51496336
has comment: http://stackoverflow.com/comment/89957963
tagged with: datetime
has title: HourLocator() on yaxis raising runtime error unexpectedly exceeding Locator.MAXTICK
answer count: 1
has body: I am trying to setup a simple figure with some horizontal lines. plt.figure() plt.axhline(datetime.time(12,0,0,0),color='blue',ls='--',lw=3) plt.axhline(datetime.time(18,0,0,0),color='red',ls='--',lw=3) This works fine and I get: which is correct. Then I would like my yticks to be on the rounded hourly values only. I am trying using HourLocator() from matplotlib.dates import HourLocator, DateFormatter, plt.gca().yaxis.set_major_locator(HourLocator()) # this fails plt.gca().yaxis.set_major_formatter(DateFormatter('%H:%M')) However, this generates this error. Why is it trying to generate 570241 ticks? RuntimeError: Locator attempting to generate 570241 ticks from 42120.0 to 65880.0: exceeds Locator.MAXTICKS
has comment: http://stackoverflow.com/comment/89957958
favorite count: 0

http://stackoverflow.com/comment/90150856
type: Comment
comment on: http://stackoverflow.com/a/51584269
has text: @Darius I added a note to my answer. In short: I am not sure where the difference comes from.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51568224
has comment: http://stackoverflow.com/comment/90107676
has comment: http://stackoverflow.com/comment/90102998
has comment: http://stackoverflow.com/comment/90112897
has comment: http://stackoverflow.com/comment/90110682
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90112028
type: Question
has title: Operation on a list of files failed after several rounds
linked to: http://stackoverflow.com/q/29771901
has comment: http://stackoverflow.com/comment/90110646
has answer: http://stackoverflow.com/a/51574564
has comment: http://stackoverflow.com/comment/90103172
has body: I'm currently trying to write a script to help me format simple txt of video script from sth like 1 00:00:00,000 --> 00:00:03,550 text1 2 00:00:03,550 --> 00:00:07,030 text2 to "text1 text2". I have more than 100 separate files and I am trying to write all of them together into one. So I wrote sth like: import re import os path = r'the full path of the directory' f = open("video_script.txt", 'w') for filename in os.listdir(path): text = open(filename).read() textblock = reduce(lambda x,y: x+y+' ', re.findall('([a-zA-z].*)\r', text)) newtext = textblock.replace('. ', '.\n') f.write ('*'+filename+'*') f.write ('\n') f.write(newtext) f.write('\n'*2) f.close() I got the code fun successfully for about 30 files then I got an error of: TypeError: reduce() of empty sequence with no initial value I run a separate test on that failed one and there was no error. Thanks for any help.
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51574564
has comment: http://stackoverflow.com/comment/90110575
favorite count: 0

http://stackoverflow.com/a/51585123
has comment: http://stackoverflow.com/comment/90136118
upvote count: 1
answers question: http://stackoverflow.com/q/51584994
downvote count: 0
has comment: http://stackoverflow.com/comment/90136170
has comment: http://stackoverflow.com/comment/90136222
type: Answer
has comment: http://stackoverflow.com/comment/90136048
score: 1
has body: You may not use [::-1] but you can multiply each range index by -1. t = [["111000"],["222999"]] def rev(x): return "".join(x[(i+1)*-1] for i in range(len(x))) &gt;&gt;&gt; [[rev(x) for x in z] for z in t] [['000111'], ['999222']] If you may use the step arg in range, can do AChampions suggestion: def rev(x): return ''.join(x[i-1] for i in range(0, -len(x), -1))

http://stackoverflow.com/q/51506845
tagged with: pandas
tagged with: function
answer count: 1
tagged with: python
type: AnsweredQuestion
has title: Function not recognizing libraries
has body: I have the simplest of questions, but this has never happened to me and can't find an answer. I have the following piece of code: import datalab as dl import pandas as pd Where datalab is a script I wrote, and between other things, it contains this very simple function: def fecha(vartime, df=df): return pd.to_datetime(df[vartiempo]) So, when I try to run the function, like this: dl.fecha('time_obtained') I get the following error: NameError: name 'pd' is not defined Even though I'm quite sure I imported pandas as pd. Is there something I'm missing when importing user functions? I'm a bit perplexed. Any help is appreciated Thanks in advance !
accepted answer: http://stackoverflow.com/a/51506877
type: Question
has answer: http://stackoverflow.com/a/51506877
score: 0

http://stackoverflow.com/comment/90131942
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51583287
type: Comment
has text: Oh! This string will be converted to integer!

http://stackoverflow.com/comment/90074414
type: QuestionComment
score: 1
has text: That doesn't do any sorting. What specifically do you not understand about its operation?
comment on: http://stackoverflow.com/q/51553693
type: Comment

http://stackoverflow.com/comment/90147945
type: Comment
type: QuestionComment
score: 1
has text: Why are you sending data in headers anyway? Content should be in the body of the POST.
comment on: http://stackoverflow.com/q/51591267

http://stackoverflow.com/a/51581890
score: 0
answers question: http://stackoverflow.com/q/51494555
type: Answer
has body: In Tornado, anything that is slow must be called in a coroutine with await. If predict does some I/O of its own, it should be made into a coroutine so it can do that I/O asynchronously. If it is pure computation, you should run it on a thread pool: async def post(self): in_data = json.loads(self.request.body.decode('utf-8')) res = await IOLoop.current().run_in_executor(None, predict, in_data)

http://stackoverflow.com/comment/90127155
comment on: http://stackoverflow.com/q/51580863
type: Comment
type: QuestionComment
has text: Just noticed the code works just OK from the CLI. The problem is when executing lab2.py.
score: 0

http://stackoverflow.com/comment/90017067
has text: Yes, it would open in any text editor
comment on: http://stackoverflow.com/q/51524151
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90047602
has text: @computerScience, It does change (in latest revision). I've kept things simple and use `df < 50` as in the description of your problem.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51539766

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/51562377
tags question: http://stackoverflow.com/q/51530276
tags question: http://stackoverflow.com/q/51639757

http://stackoverflow.com/q/51518601
has answer: http://stackoverflow.com/a/51519938
linked to: http://stackoverflow.com/q/42881650
has answer: http://stackoverflow.com/a/51601918
has comment: http://stackoverflow.com/comment/90188134
has comment: http://stackoverflow.com/comment/90158552
has answer: http://stackoverflow.com/a/51694804
favorite count: 0
has comment: http://stackoverflow.com/comment/90006166
has comment: http://stackoverflow.com/comment/90156892
has comment: http://stackoverflow.com/comment/90016176
accepted answer: http://stackoverflow.com/a/51518791
has comment: http://stackoverflow.com/comment/90187932
type: Question
has title: How to remove every occurrence of sub-list from list
has answer: http://stackoverflow.com/a/51600100
has comment: http://stackoverflow.com/comment/90187880
has answer: http://stackoverflow.com/a/51634552
tagged with: python
has comment: http://stackoverflow.com/comment/90015471
has comment: http://stackoverflow.com/comment/90150365
has comment: http://stackoverflow.com/comment/90150973
has answer: http://stackoverflow.com/a/51519294
answer count: 13
has answer: http://stackoverflow.com/a/51537342
has comment: http://stackoverflow.com/comment/90012370
has comment: http://stackoverflow.com/comment/90007851
has body: I have two lists: big_list = [2, 1, 2, 3, 1, 2, 4] sub_list = [1, 2] I want to remove all sub_list occurrences in big_list. result should be [2, 3, 4] For strings you could use this: '2123124'.replace('12', '') But AFAIK this does not work for lists. This is not a duplicate of Removing a sublist from a list since I want to remove all sub-lists from the big-list. In the other question the result should be [5,6,7,1,2,3,4]. Update: For simplicity I took integers in this example. But list items could be arbitrary objects. Update2: if big_list = [1, 2, 1, 2, 1] and sub_list = [1, 2, 1], I want the result to be [2, 1] (like '12121'.replace('121', '')) Update3: I don't like copy+pasting source code from StackOverflow into my code. That's why I created second question at software-recommendations: https://softwarerecs.stackexchange.com/questions/51273/library-to-remove-every-occurrence-of-sub-list-from-list-python Update4: if you know a library to make this one method call, please write it as answer, since this is my preferred solution. The test should pass this test: def test_remove_sub_list(self): self.assertEqual([1, 2, 3], remove_sub_list([1, 2, 3], [])) self.assertEqual([1, 2, 3], remove_sub_list([1, 2, 3], [4])) self.assertEqual([1, 3], remove_sub_list([1, 2, 3], [2])) self.assertEqual([1, 2], remove_sub_list([1, 1, 2, 2], [1, 2])) self.assertEquals([2, 1], remove_sub_list([1, 2, 1, 2, 1], [1, 2, 1])) self.assertEqual([], remove_sub_list([1, 2, 1, 2, 1, 2], [1, 2]))
score: 45
has comment: http://stackoverflow.com/comment/90014209
upvote count: 49
has answer: http://stackoverflow.com/a/51519237
has comment: http://stackoverflow.com/comment/90160646
has answer: http://stackoverflow.com/a/51518791
has answer: http://stackoverflow.com/a/51520573
tagged with: list-manipulation
has comment: http://stackoverflow.com/comment/90149993
has comment: http://stackoverflow.com/comment/90188045
has answer: http://stackoverflow.com/a/51522715
has answer: http://stackoverflow.com/a/51519498
has comment: http://stackoverflow.com/comment/90179034
has comment: http://stackoverflow.com/comment/90005949
downvote count: 4
possible better answer: http://stackoverflow.com/a/51519938
has comment: http://stackoverflow.com/comment/90188303
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51625432

http://stackoverflow.com/q/51497066
type: Question
has title: Python - Terminate a program from tkinter button click?
has body: I am trying to terminate a simple while loop from a tkinter window button but i am unable to do so here: Recorder.py from PIL import ImageGrab import numpy as np import cv2 import ctypes user32 = ctypes.windll.user32 screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1) def record_screen(): fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('ResultFile.avi', fourcc, 25.0, screensize) while True: try: img = ImageGrab.grab() img_np = np.array(img) frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB) out.write(frame) print('recording....') except KeyboardInterrupt: break out.release() cv2.destroyAllWindows() # uncomment when running as main #record_screen() and here's the tkinter code from tkinter import * import Recorder class Trial: def __init__(self, master): frame = Frame(master) frame.pack() # self.printButton = Button(frame, text="Print Message", command=self.printMessage) # self.printButton.pack(side=LEFT) self.recorderButton = Button(frame, text="Start Recording", command=Recorder.record_screen) self.recorderButton.pack(side=LEFT) self.quitButton = Button(frame, text="Quit Recording", command=root.destroy) self.quitButton.pack(side=LEFT) # same freezing problem with method approach # def quitFunction(self): # root.destroy() # def printMessage(self): # print("Hello .....") root = Tk() alpha = Trial(root) root.mainloop() The problem is that when i simply click the Quit button the tk code does as expected , however the very minute the recording starts it creates an infinite loop that i believe is preventing the Quit button to terminate the window
has comment: http://stackoverflow.com/comment/89963447
tagged with: while-loop
has comment: http://stackoverflow.com/comment/89963492
has comment: http://stackoverflow.com/comment/89963282
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89962932
tagged with: python
has comment: http://stackoverflow.com/comment/89963421
answer count: 0
score: 0

http://stackoverflow.com/comment/90106596
type: Comment
type: QuestionComment
has text: Your data structure is not clear, because you have not provided a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). How you arrived from your data table to the posted picture remains a mystery - the numbers don't match at all. So the question is also unclear, why your sorting didn't affect the plot.
comment on: http://stackoverflow.com/q/51569238
score: 0

http://stackoverflow.com/comment/90200487
score: 0
type: Comment
type: QuestionComment
has text: @a_guest At least for arguments with positive real part it's unambiguous: there are no poles of the integrand there, and the factor `exp(-t)` provides nice decay at infinity. On the left halfplane, analytic continuation works with a branch cut along the negative real axis.
comment on: http://stackoverflow.com/q/51609003

code-generation
tag name: code-generation
type: Tag
tags question: http://stackoverflow.com/q/51567447

http://stackoverflow.com/q/51574982
has comment: http://stackoverflow.com/comment/90115940
score: 0
tagged with: flask-restless
has comment: http://stackoverflow.com/comment/90115892
has comment: http://stackoverflow.com/comment/90116228
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90132696
has comment: http://stackoverflow.com/comment/90116842
answer count: 0
has title: Flask filter by url
tagged with: flask
has body: I'm using Flask-Restless and Flask-SQLAlchemy on my application. I can't remember when, but I did a example that I'm almost 100% it was with Flask-Restless to filter a query in the url like /example?id=1. Although the pagination plugin is ok, I can't replicate the filtering by attribute on the url. I've been searching like crazy on how to do that again but I can't find it. I'd appreciate if someone here has a way of doing that. PS.: With Flask-Restless, how do I make a GET request on a endpoint passing a parameter like GET /example {"id": 1}? PS2.: I know that if I put the id after the "/" I'll get the object, but I want to filter any field I want.
has comment: http://stackoverflow.com/comment/90129887
type: Question
tagged with: python

http://stackoverflow.com/a/51581073
has body: Compare the text and create the booleans, then do a groupby.sum - df.freeText.eq('no').groupby(df.country).sum() #country #Brazil 2.0 #China 2.0 #USA 0.0 #Name: freeText, dtype: float64 Or the common groupby.agg/apply syntax: df.groupby('country').freeText.agg(lambda g: g.eq('no').sum()) #country #Brazil 2 #China 2 #USA 0 #Name: freeText, dtype: int64
downvote count: 0
answers question: http://stackoverflow.com/q/51581024
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/90005274
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51516510
type: Comment
has text: @KeerthanBhat then you might have a chance to succeed ;-)

http://stackoverflow.com/a/51738735
accepted answer of: http://stackoverflow.com/q/51490371
score: 4
type: AcceptedAnswer
has body: the solution was to remove colon sign from the timestamp st = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y_%H-%M-%S') this solved the problem
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51490371

http://stackoverflow.com/comment/90157091
has text: You can move forwards (`k=5`) instead of backwards in case you have different levels, see update.
comment on: http://stackoverflow.com/a/51594855
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/127958233
comment on: http://stackoverflow.com/a/72402504
has text: I thought that it was self explanatory but I added as you stated.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/89987594
comment on: http://stackoverflow.com/a/51509293
has text: @RafaelC when I use np.where, i get error : ValueError: operands could not be broadcast together with shapes (2,28) (2,) ()
score: 0
type: AnswerComment
type: Comment

lemmatization
type: Tag
tags question: http://stackoverflow.com/q/51634328
tag name: lemmatization

http://stackoverflow.com/comment/90187477
type: AnswerComment
score: 0
type: Comment
has text: yes, thank you! I am well aware of the fact that element's existence and element visibility is needed for element_to_be_clickable but I am saying, it's not checking whether element is clickable, it's only make sure element exist and element visible, it's not really checking whether element is clickable, for an example, execute this statement `wait.until(ExpectedConditions.elementToBeClickable(By.id("ctl00_ContentView_LinkButtonNext1"))).click();`, this throws the error of ElementClickInterceptedError, this says to me that it's not checking whether element is clickable.
comment on: http://stackoverflow.com/a/51609960

http://stackoverflow.com/comment/90196889
type: Comment
has text: oh seems you outta luck (https://github.com/scrapinghub/splash/issues/605, https://github.com/scrapinghub/splash/issues/613), theres a hacky `_gc` call as a workaround, or you could try to make use of scrapy cache
comment on: http://stackoverflow.com/a/51483397
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89974605
score: 0
has text: I have to admit I feel like a complete idiot. I don't know why I was converting everything to an integer. Having it as a string is much simpler.
type: Comment
comment on: http://stackoverflow.com/q/51502947
type: QuestionComment

http://stackoverflow.com/comment/90071269
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51552104
has text: yes, there is a date column , and I am waiting for output
type: AnswerComment

http://stackoverflow.com/comment/132153164
score: 0
type: AnswerComment
type: Comment
has text: My `dataframe` already has numeric values, and i even still did the conversion, but it still gives the wrong value as max.
comment on: http://stackoverflow.com/a/51577232

audio
tags question: http://stackoverflow.com/q/51604921
type: Tag
tag name: audio
tags question: http://stackoverflow.com/q/51622865

http://stackoverflow.com/comment/90087418
score: 2
comment on: http://stackoverflow.com/q/51560126
has text: By the way, the `for` loop is missing a colon `:` at the end. Your code raises a `SyntaxError`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89936507
type: Comment
score: 1
has text: Which python are u using?
comment on: http://stackoverflow.com/q/51483792
type: QuestionComment

http://stackoverflow.com/q/51621354
type: Question
score: 1
has title: How to Access Changed Values of an Entry Box Created by a Loop [Tkinter, Python 3.7]
upvote count: 1
has comment: http://stackoverflow.com/comment/90208356
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90208467
has body: I am using IDLE to develop. In my program, I am using dictionaries and loops to create entry boxes. I want the user to be able to edit and save changes made in those boxes. I cannot seem to access a specific changed entry in any of the boxes due to them being created by a loop. The closest thing I found to my issue was this post: I can't seem to return a specific value from a list created by a loop of Entry boxes. However, it does not address my issue of accessing values after changing while it is still in the box. Here is my code for making the boxes: import tkinter as tk import sys import pickle from tkinter import messagebox #permanent maps wood_floors = {'''Red Oak''': 4.27} tile_floors = {'''Granite Tile''': 1.28} laminate_floors = {'''Spruce Laminate''':4.21} vinyl_floors = {'''White Oak Vinyl''': 2.36} carpet_floors = {'''Red Carpet''': 3.18} linearly_priced_items = {'''Quarter Round''': 1.50} miscelaneous_persqft = {'''Plastic Sheets''': 0.25} miscelaneous = {'''Nails''': 4.00} master_list = [wood_floors, tile_floors, laminate_floors, vinyl_floors, carpet_floors, miscelaneous_persqft, miscelaneous] #temporary maps temp_wood_floors = {} temp_tile_floors = {} temp_laminate_floors = {} temp_vinyl_floors = {} temp_carpet_floors = {} temp_linearly_priced_items = {} temp_miscelaneous_persqft = {} temp_miscelaneous = {} temp_master_list = [temp_wood_floors, temp_tile_floors, temp_laminate_floors, temp_vinyl_floors, temp_carpet_floors, temp_miscelaneous_persqft, temp_miscelaneous] def price_editor(): r = 0 editorWindow = tk.Tk() tk.Label(editorWindow, text = 'WOOD FLOORS').grid(row = r, column = 0) for wfloor in wood_floors: r = r+1 b1 = tk.Entry(editorWindow, width = 60) b1.insert(10,wfloor) b1.grid(row = r, column = 0) tk.Label(editorWindow, text = 'Retail Price Per Square Foot: $').grid(row = r, column = 1) b2 = tk.Entry(editorWindow) b2.insert(10,wood_floors[wfloor]) b2.grid(row = r, column = 2) temp_wood_floors[wfloor] = wood_floors[wfloor] r = r+1 tk.Label(edi…
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/49001710
tagged with: python
has comment: http://stackoverflow.com/comment/90210054
tagged with: tkinter
answer count: 0

http://stackoverflow.com/comment/90129300
score: 0
has text: Thanks. It works now. So I am now using the import builtins.
type: Comment
comment on: http://stackoverflow.com/a/51581838
type: AnswerComment

http://stackoverflow.com/comment/90206984
has text: Sorry, edited with my code.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51618762

http://stackoverflow.com/a/51724121
has comment: http://stackoverflow.com/comment/90426247
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90426571
type: Answer
accepted answer of: http://stackoverflow.com/q/51573298
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51573298
has body: Quandl is a pure Python distribution (containing only Python code), so when you get an access violation error on import quandl, it can either mean that: your Python installation is broken, which is not the case here as you mentioned other packages working, or that Quandl imports some broken dependency. In your case, it's pandas causing the issue. First of all, check what platform/ABI tags pip reports on your machine: pip&lt;10: $ python -c "import pip; print(pip.pep425tags.get_impl_tag())" $ python -c "import pip; print(pip.pep425tags.get_abi_tag())" $ python -c "import pip; print(pip.pep425tags.get_platform())" pip&gt;=10: $ python -c "import pip._internal as pip; print(pip.pep425tags.get_impl_tag())" $ python -c "import pip._internal as pip; print(pip.pep425tags.get_abi_tag())" $ python -c "import pip._internal as pip; print(pip.pep425tags.get_platform())" Be sure to use the correct Python version if you have multiple installed (version check with python --version); replace python with py -2 or py -3 if necessary. The impl tag is an abbreviation for your Python implementation, usually CPython; for example, cp35 means CPython of major version 3.5 etc. The ABI tag consists of three parts: Python implementation abbreviation, impl version (same as in Python tag) plus the ABI flags (for example, m if your Python impl was built with --with-pymalloc etc). You platform should be either win_amd64 for 64 bit Windows, or win32 for 32 bit one. Now check if there is a wheel with precompiled extensions available for your platform: go to https://pypi.org/project/pandas/#files and browse through the list of files. Look for a file pandas-0.23.4-{impl tag}-{ABI tag}-{platform tag}.whl. PyPI wheels If there is a wheel file suitable for your current platform, copy its link and run: $ pip uninstall -y pandas $ pip install https://copied-link-to-wheel-file If pip uninstall fails, run $ pip install --force-reinstall https://copied-link-to-wheel-file instead. third-party wheels If no whe…
has comment: http://stackoverflow.com/comment/90426383

http://stackoverflow.com/a/51563360
downvote count: 0
score: 1
has body: A little more detailed answer: When the matrix is not well-conditioned, that means it has some very small eigenvalues. Let's use Singular Value Decomposition, if your matrix is X=L @ S @ R.T, then the inverse is Xi=R @ np.sqrt(S) @ L.T. Now the middle part is inversing the eigenvalues and if there are some very small ones, the floating point error can have a huge difference in their inverse and thus the difference you are seeing there. But does it matter? No, if your matrix is not well-conditioned then the inverse you are calculating is not reliable, you can test this by multiplying it by your original matrix and see that not every element is close to identity matrix. What is the solution? 1. Use a preconditioner 2. If you see a big change in the eigenvalues of your original matrix, simply throw those unimportant eigenvalues and eigenvectors away, reconstruct your matrix and then your inverse should be the same regardless of the platform/package/OS you are using. Note that the first approach is basically doing the same thing as the second, just different math steps.
upvote count: 1
answers question: http://stackoverflow.com/q/51562302
type: Answer

http://stackoverflow.com/comment/110208050
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51528612
type: Comment
has text: Um, it is literally stated in the first sentence of the answer...

http://stackoverflow.com/comment/90150086
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51592247
has text: It's better to have a global approach. You could use tools like `Wireshark` that lets you sniff the packets sent/received by your machine. With that said, in python, you could overwrite some methods that you're suspicious about. For instance `post` and `put` methods from request. The idea is to rewrite them like this `request.post(args) = writeToLogs(args); request.post(args)`. You can do this for websockets as well.

http://stackoverflow.com/a/51621192
upvote count: 3
type: Answer
downvote count: 0
score: 3
has body: Rather than building the pagination yourself and dealing with the complexity you're running into, consider using DataTables. You can place multiple tables on a single view, and the pagination for each table is handled via javascript with no actual change in the URL. You can either insert the values into the table using standard django template tags, or you can build a simple API (using DRF or django's JSON libraries) to feed the tables via Ajax. This is a bit more advanced, but when you have a lot of data, it ensures you aren't sending it all to the user at once and hogging system memory.
answers question: http://stackoverflow.com/q/51546893

http://stackoverflow.com/a/51634510
has comment: http://stackoverflow.com/comment/90243129
accepted answer of: http://stackoverflow.com/q/51634368
answers question: http://stackoverflow.com/q/51634368
type: Answer
has comment: http://stackoverflow.com/comment/90267044
score: 1
has comment: http://stackoverflow.com/comment/113767248
upvote count: 1
has comment: http://stackoverflow.com/comment/90236589
has comment: http://stackoverflow.com/comment/90266958
has comment: http://stackoverflow.com/comment/90243002
has comment: http://stackoverflow.com/comment/90236635
type: AcceptedAnswer
has body: I believe need change columns names and add parameter fill_value: res = df.pivot_table(index="Plant Name", columns="Technology", values="Nameplate Capacity", aggfunc=np.sum, fill_value=0).reset_index() print (res) Technology Plant Name Conventional Steam Coal \ 0 Barry 1192.5 Technology Natural Gas Fired Combined Cycle Natural Gas Steam Turbine 0 390.4 306.2 First solution should be changed with specify column for aggreate sum and unstack for reshape: res = (df.groupby(['Plant Name', 'Technology'])['Nameplate Capacity'] .sum() .unstack(fill_value=0) .reset_index()) print (res) Technology Plant Name Conventional Steam Coal \ 0 Barry 1192.5 Technology Natural Gas Fired Combined Cycle Natural Gas Steam Turbine 0 390.4 306.2
downvote count: 0

http://stackoverflow.com/q/51508191
favorite count: 0
accepted answer: http://stackoverflow.com/a/51508239
score: -1
has body: diff = list(set(map(tuple, paths1)) - set(map(tuple, paths2))) Where paths1 and paths2 are list of list of pairs. Example: paths1 = [[(1,2),(2,3),(3,4)],[(1,3),(3,5)]] paths2 = [[(5,2),(2,3),(3,4)],[(1,3),(3,5)]] print(list(set(map(tuple, paths1)) - set(map(tuple, paths2)))) Should output [((1, 2), (2, 3), (3, 4))]. The inner list has to be converted to tuple first because this type of list couldn't be hashed into set. In the provided C++ code below, I tried using the set_difference function from the standard library: #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;utility&gt; #include &lt;algorithm&gt; int main () { std::vector &lt; std::pair &lt; int, int &gt;&gt;v1 = { std::make_pair (1, 2), std::make_pair (2, 3), std::make_pair (3, 4) }; std::vector &lt; std::pair &lt; int, int &gt;&gt;v2 = { std::make_pair (5, 2), std::make_pair (2, 3), std::make_pair (3, 4) }; std::vector &lt; std::pair &lt; int, int &gt;&gt;v3 = { std::make_pair (1, 3), std::make_pair (3, 5) }; std::vector &lt; std::vector &lt; std::pair &lt; int, int &gt;&gt;&gt;V1 = { v1, v3 }; std::vector &lt; std::vector &lt; std::pair &lt; int, int &gt;&gt;&gt;V2 = { v2, v3 }; std::vector &lt; std::vector &lt; std::pair &lt; int, int &gt;&gt;&gt;diff; std::set_difference (V1.begin (), V1.end (), V2.begin (), V2.end (), std::inserter (diff, diff.begin ())); std::cout &lt;&lt; "["; for (auto v : diff) { std::cout &lt;&lt; "["; for (auto p : v) std::cout &lt;&lt; "(" &lt;&lt; p.first &lt;&lt; "," &lt;&lt; p.second &lt;&lt; ")"; std::cout &lt;&lt; "]"; } std::cout &lt;&lt; "]\n"; } This code printed [[(1,2)(2,3)(3,4)][(1,3)(3,5)]]. Why is the 2nd inner list not removed when it should be?
linked to: http://stackoverflow.com/q/4650243
has comment: http://stackoverflow.com/comment/104205639
tagged with: python
tagged with: code-translation
tagged with: c++
type: AnsweredQuestion
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51508239
upvote count: 0
has title: Converting this python line to C++?
answer count: 1

http://stackoverflow.com/a/51488346
upvote count: 7
has comment: http://stackoverflow.com/comment/89947518
has comment: http://stackoverflow.com/comment/90664595
score: 7
has comment: http://stackoverflow.com/comment/89955720
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51487645
accepted answer of: http://stackoverflow.com/q/51487645
has body: I'm not sure what you mean by "get the absolute path of foo.py from bar.func()". However, it's possible for a function to determine whose calling it at runtime by using sys._getframe() to reach back through the call stack and examine the calling function's globals (the variable namespace in the code below). Here's an example showing how to do that: foo.py import bar bar.func() bar.py from pprint import pprint import sys def func(): namespace = sys._getframe(1).f_globals # caller's globals pprint(namespace) print("caller's path:", namespace['__file__']) Sample output: {'__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__cached__': None, '__doc__': None, '__file__': '\\Stack Overflow\\get-path-of-calling-script\\foo.py', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0085A7D0>, '__name__': '__main__', '__package__': None, '__spec__': None, 'bar': <module 'bar' from '\\Stack Overflow\\get-path-of-calling-script\\bar.py'>, 'sys': <module 'sys' (built-in)>} caller's path: \Stack Overflow\get-path-of-calling-script\foo.py See the '__file__' entry in the returned dictionary? It's the absolute path to the source file — foo.py — that contained the call made to bar.func().

http://stackoverflow.com/a/51537409
type: Answer
has body: Here: def base(request): # code here... if request.method == 'POST': # set form and valid r_form= forms.RegisterForms(request.POST) if r_form.is_valid(): # code here... return redirect(reverse('complete')) else: r_form = forms.RegisterForms(request.GET) # code here... return render(request,'landing/forma_reg.html',c) your first return statement is only executed if it's a POST request AND the form is valid, and your second return statement is only executed if i's a GET request, so if it's a POST request and the form is not valid, the function ends without an explicit return and so implicitely returns None The fix is quite easy actually: just de-indent your last return statement, so an invalid form will be redisplayed with it's error messages: def base(request): # code here... if request.method == 'POST': # set form and valid r_form= forms.RegisterForms(request.POST) if r_form.is_valid(): # code here... return redirect(reverse('complete')) else: r_form = forms.RegisterForms(request.GET) # code here... # make sure we ALWAYS return a response return render(request,'landing/forma_reg.html',c)
answers question: http://stackoverflow.com/q/51536732
score: 0

http://stackoverflow.com/comment/90133733
comment on: http://stackoverflow.com/q/51584171
score: 0
type: QuestionComment
type: Comment
has text: I also tried brew install mysql-connector-c followed by pip install MySQL-python and this gave me Command "python setup.py egg_info" failed with error code 1

http://stackoverflow.com/q/51528729
has answer: http://stackoverflow.com/a/51529223
upvote count: 2
has title: Transform Scale of Columns into a range from 1 to 10
type: Question
possible better answer: http://stackoverflow.com/a/51529218
has answer: http://stackoverflow.com/a/51529218
accepted answer: http://stackoverflow.com/a/51529223
tagged with: numpy
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/90026255
downvote count: 0
favorite count: 0
has body: I am trying to create a set of new columns that would be derived from an existing columns in a dataframe using a function. Here is sample code that produces errors and I wonder if there a better more efficient way to accomplish it than the loop import numpy as np import pandas as pd dates = pd.date_range('1/1/2000', periods=100, freq='M') long_df = pd.DataFrame(np.random.randn(100, 4),index=dates, columns=['Colorado', 'Texas', 'New York', 'Ohio']) mylist=['Colorado', 'Texas', 'New York', 'Ohio'] def trnsfrm_1_10 (a, b): b = (a-np.min(a))/(np.max(a)-np.min(a))*9+1 return b for a in mylist: b=a+"_T" long_df[b] = long_df.apply(lambda row: trnsfrm_1_10(row[a], row[b]), axis=1) To clarify above question, here is example of DataFrame that has input columns (Colorado, Texas, New York) and output variables (T_Colorado, T_Texas, T_New York). Let's assume that if for each input variable, below are minimum and maximum of each column then by applying equation: b = (a-min)/(max-min)*9+1 to each column, the output variables are T_Colorado T_Texas T_New York. I had to simulate this process in excel based on just 5 rows, but it would be great to compute minimum and maximum as part of the function because I would have a lot more rows in the real data. I am relatively new to Python and Pandas and I really appreciate your help. These are example min and max Colorado Texas New York min 0.03 -1.26 -1.04 max 1.17 0.37 0.86 This is example of a DataFrame Index Colorado Texas New York T_Colorado T_Texas T_New York 1/31/2000 0.03 0.37 0.09 1.00 10.00 6.35 2/29/2000 0.4 0.26 -1.04 3.92 9.39 1.00 3/31/2000 0.35 -0.06 -0.75 3.53 7.63 2.37 4/30/2000 1.17 -1.26 -0.61 10.00 1.00 3.04 5/31/2000 0.46 -0.79 0.86 4.39 3.60 10.00
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/51638306
score: 3
answers question: http://stackoverflow.com/q/51637989
has comment: http://stackoverflow.com/comment/90241171
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90241033
accepted answer of: http://stackoverflow.com/q/51637989
has body: As piRSquared already explained this only happens with categorical data. Starting from 0.23.0 groupby has a new "observed" argument which toggles this behavior. MCVE taken from piRSquared: &gt;&gt;&gt; df = pd.DataFrame(dict( State=list('CCCCFFFF'), District=list('WXWXYYZZ'), Value=range(1, 9) )) &gt;&gt;&gt; df.assign( District=pd.Categorical(df.District) ).query('State == "F"').groupby('District').Value.mean() District W NaN X NaN Y 5.5 Z 7.5 Name: Value, dtype: float64 &gt;&gt;&gt; df.assign( District=pd.Categorical(df.District) ).query('State == "F"').groupby('District', observed=True).Value.mean() District Y 5.5 Z 7.5 Name: Value, dtype: float64
type: Answer
upvote count: 3

http://stackoverflow.com/q/51503398
has comment: http://stackoverflow.com/comment/89976241
has comment: http://stackoverflow.com/comment/89975685
has comment: http://stackoverflow.com/comment/89976402
type: UnansweredQuestion
tagged with: python
tagged with: linear-programming
has comment: http://stackoverflow.com/comment/89976191
has comment: http://stackoverflow.com/comment/89976163
answer count: 0
has body: I was going through the documentation for scipy.optimize.linprog, and noticed that there are two methods built into the function: the simplex and interior-point methods. I also learned from experimentation that the simplex method fails due to bad handling of floating points, so I decided to use the interior-point method. However, when I run anything like the following: scipy.optimize.linprog(A_eq = A, b_eq = B, method='interior-point') I get an error message informing me that interior-point is not a valid string for the parameter method. I made sure to copy the text directly from the source code of the function, and it still didn't recognize it. Moreover, I tried to look at the source code for the interior-point method the function uses (which is here) but I only got more lost. Am I doing something wrong here? What should I be doing here? Edit As the comments noted, my scipy version was not updated enough to use interior-point. However, the python version I'm using is built into SQL as part of sp_execute_external_script, so I'm not sure whether I can update scipy. Do I have an alternative?
has comment: http://stackoverflow.com/comment/89975839
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/89976535
has title: Is interior-point not supported in scipy.optimize.linprog?
score: 0
has comment: http://stackoverflow.com/comment/89976361
has comment: http://stackoverflow.com/comment/89975649

http://stackoverflow.com/q/51617925
has comment: http://stackoverflow.com/comment/90201763
score: 0
has comment: http://stackoverflow.com/comment/90241935
tagged with: wagtail
has comment: http://stackoverflow.com/comment/90201820
has comment: http://stackoverflow.com/comment/90202886
has title: Pagination in a Wagtail project: Better way to separate pagination logic in model?
has body: I have here a snippet from a HomePage model in a Wagtail project that is acting as my blog index page. Since get_context() was getting a little lengthy while I was adding Django's pagination logic to it, I decided to try to put it in its own method and just have get_context() grab the paginated collection of Page objects from that. Here's how my code looked at first: class HomePage(RoutablePageMixin, Page): description = models.CharField(max_length=255, blank=True, null=True) content_panels = Page.content_panels + [ FieldPanel('description', classname='full') ] def get_context(self, request, *args, **kwargs): context = super(HomePage, self).get_context(request, *args, **kwargs) context['posts'], context['page_range'] = self.pagination(self.get_posts()) # End attempt context['home_page'] = self context['search_type'] = getattr(self, 'search_type', '') context['search_term'] = getattr(self, 'search_term', '') return context def get_posts(self): return BlogPage.objects.descendant_of(self).live().order_by('-date') def pagination(self, posts): paginator = Paginator(posts, 5) try: page = request.GET.get('page', '1') except: page = 1 try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) # Get a page_range index = posts.number - 1 max_index = len(paginator.page_range) start_index = index - 5 if index &gt;= 5 else 0 end_index = index + 5 if index &lt;= max_index - 5 else max_index page_range = paginator.page_range[start_index:end_index] print('\n', posts, '\n') return posts, page_range I didn't see the problem right away but of course noticed that no matter the page parameter in the URL, page 1 was being served. My quick and dirty solution was to just add request as an argument in pagination() and pass request to it up in get_context(). This solves the problem but I can't help but think there's a problem with this solution or that it's somehow not best practices. Can anyone tell me a…
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: django
type: Question

http://stackoverflow.com/comment/90106723
has text: probably you will have to do cleanup with atexit or win32api(windows)
type: Comment
comment on: http://stackoverflow.com/q/51570220
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90016776
comment on: http://stackoverflow.com/q/51522356
score: 0
type: Comment
type: QuestionComment
has text: @jeremysprofile I am using Redhat Server 5.3. Anyways, that's not what I am stuck at. Would you be able to help me with the original question I had?

http://stackoverflow.com/comment/90159584
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51596225
has text: can you clarify if the threads need concurrent access? Are they sharing session data? MySQL doesn't care if you use a pool or not. If you open/close connections frequently, you may have performance issues - which pooling helps with.
type: QuestionComment

http://stackoverflow.com/q/51548751
type: Question
has title: How to access files through SSH with Python script?
has body: I would like to run a Python script in my home directory that pulls data from various files. However, to access these files I need to log into an SSH and then navigate to a certain directory. Is there a way to do this while running my script in my home directory? I would just copy them over using scp, but there are thousands, so I don't think this would be very efficient (but is a last resort option). Thanks!
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51548815
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90065193
tagged with: ssh
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51548844

http://stackoverflow.com/comment/90196474
comment on: http://stackoverflow.com/a/51614450
score: 0
type: Comment
has text: @zeb92 what exactly do you mean by save? Do you want it in a file or simply a variable that can be called outside of the Tkinter program?
type: AnswerComment

http://stackoverflow.com/q/51587494
type: AnsweredQuestion
tagged with: twitter
tagged with: api
upvote count: 1
answer count: 1
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/51590066
accepted answer: http://stackoverflow.com/a/51590066
tagged with: python
has title: Retrieving tweets from twitter
tagged with: tweepy
has body: I want to retrieve tweets from twitter and save it in CSV file. I use the following code but no result is showed and no errors. what is wrong? import tweepy import csv consumer_key = 'xxx' consumer_secret = 'xxx' access_token = 'xxx' access_token_secret = 'xxx' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) search = raw_input('Search :&gt; ') csvFile = open('result.csv', 'a') csvWriter = csv.writer(csvFile) for tweet in tweepy.Cursor(api.search, q='{}'.format(search), since = "2018-07-1", until = "2018-07-4", lang = "ar").items(): csvWriter.writerow([tweet.created_at, tweet.text.encode('utf-8')]) print tweet.created_at, tweet.text csvFile.close()
downvote count: 1
type: Question

http://stackoverflow.com/q/51598745
type: Question
upvote count: 1
tagged with: variables
favorite count: 0
tagged with: class
score: 0
has comment: http://stackoverflow.com/comment/90163668
downvote count: 1
has comment: http://stackoverflow.com/comment/90163806
tagged with: reset
tagged with: macos
has comment: http://stackoverflow.com/comment/90163617
answer count: 0
has comment: http://stackoverflow.com/comment/90163448
has title: Unable to reset class variables
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90163529
has comment: http://stackoverflow.com/comment/90163725
has body: So I'm a tad new to Python, I've worked a lot with RPG but I've come across a problem when trying to reset or refresh my variables in my Classes. At the moment when the user successfully flees the monster, entering the next fight with a goblin will result in the goblin sharing the same statistics as the previous one. For example, the user damages Goblin_1 for 5 damage, meaning its health is at 25/30. If the user run away successfully, the next time the user fights a goblin, its starting health will be 25/30. This problem also carries over to the earned experience and gold given to the user when they kill the monster. I fairly certain that if the variables were reset after the user ran successfully away this would solve all the problems if I just carried it over to also the win condition. So to put this in short, we have Goblin_1. Goblin_1 gets damaged for 5 hit points, and is now at 25/30. If the user flees, Goblin_2 will override Goblin_1's statistics and not start at 25/30 hit points. Any help would be fantastic mates. import sys import os import random import pickle import time ## Weapons weapon1 = {"long sword":10} weapon2 = {"great sword":40} ## Potions healthpot = {"health potion": 10} # User Statistics class Player: def __init__(self, name): self.name = name self.exp = 0 self.maxhealth = 100 self.health = self.maxhealth self.base_attack = 10 self.gold = 0 self.pots_health = 0 self.weap = ["rusty sword"] self.curweap = "Rusty Sword" # Attack Modifiers @property def attack(self): attack = self.base_attack if self.curweap == "rusty sword": attack += 2 if self.curweap == "long sword": attack += 10 if self.curweap == "great sword": attack += 20 return attack ## Monsters class Goblin: def __init__(self, name): self.name = name self.maxhealth = 30 self.health = self.maxhealth self.attack = random.randint(3,8) self.goldgain = random.randint(5,10) self.expgain = random.randint(9,15) GoblinIG = Goblin("Goblin") class Skeleton: def __init__(self, name): self.name = name…
has comment: http://stackoverflow.com/comment/90163621

http://stackoverflow.com/a/51509093
type: Answer
has comment: http://stackoverflow.com/comment/90025766
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51508936
has body: First, Decimals are inherently slower than floats, because all of the logic is implemented in Python with a bit of C acceleration, instead of in custom circuitry on your CPU. Plus, if you've put them in a NumPy array, NumPy doesn't know anything about the Decimal type, so it has to store them as drtype=object, which means references to normal Python objects that have to be unboxed for every operation. By contrast, float values can be stored with dtype=float, which means they're just raw IEEE doubles that can be used directly (or even CPU-vectorized to process multiple values at a time). So, I'd expect it to be about an order of magnitude or so slower. And when I run a quick test, it takes a bit over as long. Second, scipy.stats.mode is inherently slow if you have a lot of unique elements. And, even if you don't, it's still doing extra work for extra features you may not need. Anyway, you don't need to do any math to calculate the mode, just compare values for equality. And we're not getting any benefit out of NumPy anywhere else. So, simpler, less-powerful, non-NumPy solutions might actually be faster. If you actually need any the features of scipy.stats.mode, that doesn't help you. For example, it can return multiple results if there are equally-common values; it gives the mode's count as well as the mode; it knows how to skip over NaN values instead of just telling you the mode is NaN; etc. If you need any of the scipy features, you might want to consider building a mode replacement out of find_repeats, as described here. This seems to be roughly 5x as fast as mode even in a fair case, and to not degenerate when there are tons of uniques. So, even adding the 10x cost for using Decimal, it still ends up pretty fast. But if you don't need them? statistics.mode(a) is actually slightly faster than scipy.stats.mode even on the fair case even on an array of floats. And, instead of taking 10x as long if you give it Decimals, it takes about the same amount of time. collec…
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90025036
answers question: http://stackoverflow.com/q/51508936

http://stackoverflow.com/comment/90139600
comment on: http://stackoverflow.com/q/51587098
type: Comment
type: QuestionComment
score: 1
has text: Perhaps you meant to use `self.cropped = cv2.resize(frame[y:y+h, x:x+w], (198,198))` in the `prediction` method so that it (`self.cropped`) could be used in `gender_classification`.

http://stackoverflow.com/a/53380743
type: Answer
downvote count: 3
has comment: http://stackoverflow.com/comment/111322569
score: 5
has body: Just change ASGI_APPLICATION = mysite.routing.application to ASGI_APPLICATION = "routing.application"
answers question: http://stackoverflow.com/q/51634522
upvote count: 8
has comment: http://stackoverflow.com/comment/111320366

http://stackoverflow.com/q/51510907
tagged with: evernote
score: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51715932
type: Question
answer count: 1
has title: Evernote access token Python
tagged with: oauth
tagged with: python
has body: I am trying to retrieve Evernote OAuth access token through Python by following the documentation here. However, multiple attempts, I am not able to retrieve the temporary access token which is the very first step in this 3 legged authorization. Any idea what am I doing wrong here? import time import base64 import random import uuid import urllib import collections import urllib.parse import hmac import hashlib import binascii import requests def escape(s): return urllib.parse.quote(s, safe='~') def get_nonce(): return uuid.uuid4().hex def stringify_parameters(parameters): output = '' ordered_parameters = {} ordered_parameters = collections.OrderedDict(sorted(parameters.items())) counter = 1 for k, v in ordered_parameters.items(): output += escape(str(k)) + '=' + escape(str(v)) if counter &lt; len(ordered_parameters): output += '&amp;' counter += 1 return output oauth_parameters={ 'oauth_timestamp': str(int(time.time())), 'oauth_signature_method': "HMAC-SHA1", 'oauth_version': "1.0", 'oauth_nonce': get_nonce(), 'oauth_consumer_key': 'consumerkey', 'oauth_callback':'http://localhost' } string_parameters=stringify_parameters(oauth_parameters) secret='secret' signature = hmac.new(secret.encode(), string_parameters.encode(),hashlib.sha1).digest() oauth_parameters['oauth_signature']=escape(base64.b64encode(signature).decode()) res=requests.get('https://sandbox.evernote.com/oauth?'+stringify_parameters(oauth_parameters)) print(res.status_code)
has answer: http://stackoverflow.com/a/51715932

http://stackoverflow.com/a/51607041
downvote count: 2
has comment: http://stackoverflow.com/comment/90216478
has comment: http://stackoverflow.com/comment/90190488
upvote count: 27
has comment: http://stackoverflow.com/comment/90190696
has comment: http://stackoverflow.com/comment/90180449
has body: Here is a summary of the approach it should be a proper solution: Detect keypoints and descriptors on the query image (img1) Detect keypoints and descriptors on the target image (img2) Find the matches or correspondences between the two sets of descriptors Use the best 10 matches to form a transformation matrix Transform the rectangle around img1 based on the transformation matrix Add offset to put the bounding box at the correct position Display the result image (as below). Here is the code: import numpy as np import cv2 from matplotlib import pyplot as plt img1 = cv2.imread('box.png', 0) # query Image img2 = cv2.imread('box_in_scene.png',0) # target Image # Initiate SIFT detector orb = cv2.ORB_create() # find the keypoints and descriptors with ORB kp1, des1 = orb.detectAndCompute(img1,None) kp2, des2 = orb.detectAndCompute(img2,None) # create BFMatcher object bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) # Match descriptors. matches = bf.match(des1,des2) # Sort them in the order of their distance. matches = sorted(matches, key = lambda x:x.distance) good_matches = matches[:10] src_pts = np.float32([ kp1[m.queryIdx].pt for m in good_matches ]).reshape(-1,1,2) dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good_matches ]).reshape(-1,1,2) M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0) matchesMask = mask.ravel().tolist() h,w = img1.shape[:2] pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2) dst = cv2.perspectiveTransform(pts,M) dst += (w, 0) # adding offset draw_params = dict(matchColor = (0,255,0), # draw matches in green color singlePointColor = None, matchesMask = matchesMask, # draw only inliers flags = 2) img3 = cv2.drawMatches(img1,kp1,img2,kp2,good_matches, None,**draw_params) # Draw bounding box in Red img3 = cv2.polylines(img3, [np.int32(dst)], True, (0,0,255),3, cv2.LINE_AA) cv2.imshow("result", img3) cv2.waitKey() # or another option for display output #plt.imshow(img3, 'result'), plt.show()
has comment: http://stackoverflow.com/comment/90179951
has comment: http://stackoverflow.com/comment/90185444
has comment: http://stackoverflow.com/comment/90216148
type: Answer
has comment: http://stackoverflow.com/comment/90180240
has comment: http://stackoverflow.com/comment/90180170
has comment: http://stackoverflow.com/comment/90185576
score: 25
answers question: http://stackoverflow.com/q/51606215

http://stackoverflow.com/comment/90165508
type: QuestionComment
type: Comment
has text: Probably helps to clarify that the boolean of an empty list is `False`
score: 0
comment on: http://stackoverflow.com/q/51599666

http://stackoverflow.com/a/51559128
upvote count: 1
has comment: http://stackoverflow.com/comment/90135634
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51557648
has comment: http://stackoverflow.com/comment/90104164
has body: Do you want to set weights for the RNN Cell or for the Dense layer? If it's for the RNN cell, you should be able to set the weights using the set_weights method. If it's for the Dense layer, you should be able to assign a Variable and use the initializer argument to pass your weights (and another for the bias'). Then, when you call layers.dense, you can pass both your variable tensors to kernel_initializer and bias_initializer for weights and biases respectively.
answers question: http://stackoverflow.com/q/51557648
type: Answer
score: 1

http://stackoverflow.com/comment/90051556
has text: This gives you a list of lengths of gaps. If you have 3 instances of 'house', code will return list of 2 distances.
type: Comment
comment on: http://stackoverflow.com/a/51541269
type: AnswerComment
score: 0

http://stackoverflow.com/q/51634945
type: UnansweredQuestion
tagged with: google-play-console
type: Question
has answer: http://stackoverflow.com/a/51648454
tagged with: google-cloud-storage
answer count: 1
has title: decode protobuf file returned by google cloud storage python api
score: 0
has body: I am trying to automatically download earnings report from Google Play through Google Cloud Storage and their client api library for python, googleapiclient. I use python 3.6.5 (Anaconda distribution) on Windows 10: client_email = '...@...iam.gserviceaccount.com' json_file_path = 'C:\\Users\\...' cloud_storage_bucket = 'pubsite_prod_rev_...' report_to_download = 'sales/salesreport_201806.zip' json_obj = json.loads(open(json_file).read()) _private_key = json_obj['private_key'] _private_key_id = json_obj['private_key_id'] _token_uri = json_obj['token_uri'] _client_id = json_obj['client_id'] credentials = ServiceAccountCredentials( service_account_email = client_email, private_key_id = _private_key_id, token_uri = _token_uri, client_id = _client_id, scopes = 'https://www.googleapis.com/auth/devstorage.read_only', signer = crypt.Signer.from_string(_private_key), ) storage = build('storage', 'v1', http=credentials.authorize(Http())) request = storage.objects().get_media(bucket=cloud_storage_bucket, object=report_to_download) response = request.execute() However, I get some protocol buffer file as response, which starts like this: b'PK\x03\x04\x14\x00\x08\x08\x08\x00\xdb\xa3\xe4L\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x13\x00\x00\x00PlayApps_201806.csv' I cannot figure out which decoder I should use to get response in a better format (when downloaded manually from Google Play, the report is .csv file in a .zip archive). Any suggestions?
tagged with: python
tagged with: google-python-api

http://stackoverflow.com/a/51576669
downvote count: 0
has comment: http://stackoverflow.com/comment/90119350
type: Answer
has body: Look closely at what your for loop is doing. for i in range(len(dlGuestBook)): # for each entry in the guestbook if CommentSearch in dlGuestBook[i]["Comment"]: # print the comment else: print("No results found") I think what you want is to only print "No results found" after your loop finishes, if it hasn't found any results. Something like this might be a solution. foundComment = False for i in range(len(dlGuestBook)): if CommentSearch in dlGuestBook[i]["Comment"]: foundComment = True # print the comment if not foundComment: print("No results found")
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90119016
answers question: http://stackoverflow.com/q/51576629

http://stackoverflow.com/a/51539073
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
has body: You merely apply the same API usage as appears in your question - recursively: Given: root = Resource() tmp = File("/tmp") root.putChild(b"foo", tmp) lost_found = File("/lost+found") root.putChild(b"bar", lost_found) opt = File("/opt") root.putChild(b"baz", opt) You have /foo, /bar, and /baz. If you wantsome_resourceat/foo/quux` then: tmp.putChild(b"quux", some_resource) The same applies to add additional levels. Therefore: root = Resource() europe = Resource() france = Resource() paris = Resource() root.putChild(b"europe", europe) europe.putChild(b"france", france) france.putChild(b"paris", paris) There is not really any such thing as "not returning a response" in HTTP. However, you can make the intermediate resources return a 404 (not found) status if you want. Just replace the intermediate Resource instances with something that behaves as you desire (for example, a NotFound instance). You may also want to investigate klein which implements the "route"-based resource hierarchy definition API which is often more common (in Python) these days.
has comment: http://stackoverflow.com/comment/90070557
upvote count: 1
answers question: http://stackoverflow.com/q/51537937
accepted answer of: http://stackoverflow.com/q/51537937
has comment: http://stackoverflow.com/comment/90070410

http://stackoverflow.com/a/51598166
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90163380
has comment: http://stackoverflow.com/comment/90407180
upvote count: 2
score: 2
has body: I believe you have to configure the credentials for your GCP account first. In the same session of the command line set environment variable: set GOOGLE_APPLICATION_CREDENTIALS=&lt;...&gt; You can set it on your machine in all commandline sessions in the local/machine environment variables tab (similarly to where you set your %PATH%). The details on how to obtain JSON file with your credentials is given under the URL that the exception points to.
answers question: http://stackoverflow.com/q/51597865
has comment: http://stackoverflow.com/comment/90166577
has comment: http://stackoverflow.com/comment/92579478

http://stackoverflow.com/q/51603459
has comment: http://stackoverflow.com/comment/90173156
tagged with: python-3.7
has comment: http://stackoverflow.com/comment/90174987
has title: Creating a beginners app using Django/Python: ModuleNotFoundError: No module named 'pages'
tagged with: macos
has comment: http://stackoverflow.com/comment/90174366
favorite count: 0
has comment: http://stackoverflow.com/comment/90172902
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90173261
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90174347
has comment: http://stackoverflow.com/comment/90173427
answer count: 4
has comment: http://stackoverflow.com/comment/90173220
score: 3
has comment: http://stackoverflow.com/comment/90210322
has comment: http://stackoverflow.com/comment/90173885
has answer: http://stackoverflow.com/a/51603746
has answer: http://stackoverflow.com/a/66711754
upvote count: 3
has answer: http://stackoverflow.com/a/51604345
has comment: http://stackoverflow.com/comment/90173293
has comment: http://stackoverflow.com/comment/90175174
type: Question
has body: I'm new to Django and am trying to create a very simple app off of a tutorial I found online. Working on a mac Django Version 2.0.7 Python 3.7.0 My file structure: helloworld ......venv ..........(other files) ......helloworld_project ..........(other files) ......manage.py ......pages .........._ pycache _ ..............otherfiles ..........admin.py ..........apps.py ..........migrations ..............(other files) ..........models.py ..........tests.py ..........urls.py ..........views.py The problem: when I run my urls.py file, I get the following message: Traceback (most recent call last): File "/Users/Bethany/Desktop/helloworld/pages/urls.py", line 3, in &lt;module&gt; from pages import views ModuleNotFoundError: No module named 'pages' My urls.py file: # pages/urls.py from django.urls import path from pages import views urlpatterns = [ path('', views.homePageView, name='home') ] I've tried replacing "from pages import views" with "from . import views" and get the same message. I've looked through a few similar questions on stack overflow, but haven't had success with finding a solution to fix my issue. does anyone have any suggestions? Thanks! If needed, this is the tutorial I'm following: https://djangoforbeginners.com/hello-world/
downvote count: 0
has answer: http://stackoverflow.com/a/58256156
has comment: http://stackoverflow.com/comment/90173478

http://stackoverflow.com/comment/90079104
has text: it's just to show how to convert map object to a list or a string
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51548952
type: Comment

http://stackoverflow.com/a/51674270
answers question: http://stackoverflow.com/q/51593406
has body: I fixed it by moving logging up from Lib/lib2to3/ to Lib/ where import canm now find it.
score: 0
type: Answer

http://stackoverflow.com/comment/90096872
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51564776
type: Comment
has text: Thanks. It is indeed a good skill set to have and will spend some time understanding it.

http://stackoverflow.com/comment/89951733
type: Comment
type: QuestionComment
has text: everything is working now
comment on: http://stackoverflow.com/q/51488600
score: 0

http://stackoverflow.com/q/51503288
tagged with: python
tagged with: kivy
answer count: 0
type: UnansweredQuestion
tagged with: screen
has comment: http://stackoverflow.com/comment/90054035
tagged with: background
has comment: http://stackoverflow.com/comment/89977633
type: Question
has title: Change Background color in Canvas
score: 0
has comment: http://stackoverflow.com/comment/89984163
tagged with: canvas
has body: I am trying to change the background color to white or remove the black screen in front of my first page screen. My second and third screen backgrounds show but the first has a black screen in front of it. It looks like the screen is blocking what I want to show until I click to the next screen. I'm not sure how to put the black screen in the back of my screen or remove it. screen.kv &lt;Login&gt;: BoxLayout: canvas.before: Color: rgb: 255, 255, 255 Rectangle: pos: self.pos size: self.size orientation: 'vertical' size: root.size padding: [150, 25, 150, 25] spacing: 50 Image: source:'NextStep.Final.png' texture: self.texture size: 0, 100 size_hint: 1, None Label: text: 'Welcome to A.M.B.L.E' font_size: 32 color: 0, 0, 0, 1 Label: text: 'Welcome to A.M.B.L.E' font_size: 32 color: 0, 0, 0, 1 BoxLayout: orientation: 'vertical' size_hint: 1, 10 Label: text: 'Username:' font_size: 18 halign: 'left' text_size: root.width-20, 20 color: 0, 0, 0, 1 TextInput: id: login multiline:False font_size: 28 BoxLayout: orientation: 'vertical' size_hint: 1, 10 Label: text: 'Password:' halign: 'left' font_size: 18 text_size: root.width-20, 20 color: 0, 0, 0, 1 TextInput: id: password multiline:False password:True font_size: 28 Button: text: 'Login' font_size: 24 size_hint: 1, 5 color: 1, 1, 1, 1 background_color: 0, 0, 0, 1 on_press: root.manager.current = 'Connected' &lt;Connected&gt;: canvas.before: Color: rgb: 1, 1, 1 Rectangle: pos: self.pos size: self.size BoxLayout: orientation: 'vertical' size: root.size padding: [150, 25, 150, 25] spacing: 50 Image: source:'NextStep.Final.png' texture: self.texture size: 0, 100 size_hint: 1, None Label: text: 'Welcome to A.M.B.L.E' font_size: 32 color: 0, 0, 0, 1 Button: text:'View Patient' font_size: 18 color: 1, 1, 1, 1 background_color: 0, 0, 0, 1 on_press: root.manager.current = 'Patient' Button: text:'Patient Goals' font_size: 18 color: 1, 1, 1, 1 background_color: 0, 0, 0, 1 Button: text:'Patient Progress' font_size: 18 color: 1, 1, 1, 1 ba…

http://stackoverflow.com/comment/90232539
type: Comment
comment on: http://stackoverflow.com/q/51634111
has text: Please add the full traceback as an edit.
type: QuestionComment
score: 0

http://stackoverflow.com/q/51621899
tagged with: pandas
upvote count: 1
has body: I ran in to this earlier today when creating pivot tables after categorizing a column of values using pd.cut. When creating the pivot tables I was finding that the subsequent index was incorrect. This was not an issue when using groupby instead, or after converting the category column to a different dtype. Simplified example: df = pd.DataFrame({'l1': ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b'] , 'g1': [1, 1, 2, 2, 1, 1, 1, 2, 2, 2] , 'vals': [3, 1, 3, 1, 3, 2, 2, 3, 2, 2]}) df['l2'] = pd.cut(df.vals, bins=[0, 2, 4], labels=['l', 'h']) df = df'l1', 'l2', 'g1', 'vals' Using groupby: df.groupby(['l1', 'l2', 'g1']).vals.agg(('sum', 'count')).unstack()'count', 'sum' count sum g1 1 2 1 2 l1 l2 a l 1 1 1 1 h 1 1 3 3 b l 2 2 4 4 h 1 1 3 3 Using pd.pivot_table: pd.pivot_table(df, index=['l1', 'l2'], columns='g1', aggfunc=('sum', 'count')) vals count sum g1 1 2 1 2 l1 l2 a h 1 1 1 1 l 1 1 3 3 b h 2 2 4 4 l 1 1 3 3 Using pd.pivot_table after converting the l2 column to str dtype: df2 = df.copy() df2['l2'] = df2.l2.astype(str) pd.pivot_table(df2, index=['l1', 'l2'], columns='g1', aggfunc=('sum', 'count')) vals count sum g1 1 2 1 2 l1 l2 a h 1 1 3 3 l 1 1 1 1 b h 1 1 3 3 l 2 2 4 4 The order in the last example is reversed, but the values are correct (in contrast to the middle example, where the order is reversed and the values are incorrect).
has comment: http://stackoverflow.com/comment/90209687
favorite count: 0
has comment: http://stackoverflow.com/comment/90209432
has comment: http://stackoverflow.com/comment/90209690
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90209406
tagged with: python
has comment: http://stackoverflow.com/comment/90209367
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90209648
has comment: http://stackoverflow.com/comment/90209422
type: Question
has title: Different results from pandas groupby and pivot_table when dtype is categorical
has comment: http://stackoverflow.com/comment/90209973

http://stackoverflow.com/comment/90064133
has text: I was only for testing.But I am fine now, thanks!
comment on: http://stackoverflow.com/q/51547719
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51548765
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/91774461
has answer: http://stackoverflow.com/a/65945574
tagged with: machine-learning
tagged with: tensorflow
has answer: http://stackoverflow.com/a/52415508
type: UnansweredQuestion
score: 6
tagged with: deep-learning
has title: How to find the output node name of given .ckpt.meta file in tensorflow
has comment: http://stackoverflow.com/comment/90075794
downvote count: 0
favorite count: 0
has body: So far I can get the list of all node names given any .ckpt.meta file, but I was wondering if there is a systematic way of finding out the output node name from the list. import tensorflow as tf tf.reset_default_graph() with tf.Session() as sess: saver = tf.train.import_meta_graph('mymodel.ckpt.meta') graph_def = tf.get_default_graph().as_graph_def() node_list=[n.name for n in graph_def.node]
type: Question
answer count: 2

http://stackoverflow.com/q/51586305
has comment: http://stackoverflow.com/comment/90138361
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90138084
answer count: 0
has comment: http://stackoverflow.com/comment/90138485
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90138059
type: Question
has comment: http://stackoverflow.com/comment/90138627
has comment: http://stackoverflow.com/comment/90138592
tagged with: chatbot
downvote count: 0
has comment: http://stackoverflow.com/comment/90138394
has comment: http://stackoverflow.com/comment/90138131
has comment: http://stackoverflow.com/comment/90138568
has body: I'm trying to work my way through Speech and Language Processing by Jurafsky &amp; Martin. One of their exercises is to "Implement an ELIZA-like program, using substitutions." Their suggested answer is as follows: import re, string patterns = [ (r"\b(i’m|i am)\b", "YOU ARE"), (r"\b(i|me)\b", "YOU"), (r"\b(my)\b", "YOUR"), (r"\b(well,?) ", ""), (r".* YOU ARE (depressed|sad) .*", r"I AM SORRY TO HEAR YOU ARE \1"), (r".* YOU ARE (depressed|sad) .*", r"WHY DO YOU THINK YOU ARE \1"),(r".* all .*", "IN WHAT WAY"), (r".* always .*", "CAN YOU THINK OF A SPECIFIC EXAMPLE"), (r"[%s]" % re.escape(string.punctuation), ""), ] while True: comment = raw_input() response = comment.lower() for pat, sub in patterns: response = re.sub(pat, sub, response) print response.upper() I don't see how this would work (and when I try it out in python, it doesn't) because it would just cycle through each tuple in patterns and if "pat" didn't match anything, it would just print out what the user inputted again and again... I feel like there is probably a (semi) simple fix, but I can't figure it out.
tagged with: regex
has comment: http://stackoverflow.com/comment/90138433
favorite count: 0
has comment: http://stackoverflow.com/comment/90138096
has title: Need help understanding the explanation Jurafsky & Martin give to a simple chatbot

http://stackoverflow.com/comment/90124887
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51574410
score: 0
has text: Every character is a Unicode character. The ones you are missing are also ASCII characters.

http://stackoverflow.com/comment/90157762
type: QuestionComment
comment on: http://stackoverflow.com/q/51594990
has text: Great to hear that it is figured out
score: 0
type: Comment

http://stackoverflow.com/a/51612860
answers question: http://stackoverflow.com/q/51612623
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51612623
type: AcceptedAnswer
has body: for line in words.split('\n'): time.sleep(0.05) sys.stdout.write(line + '\n') sys.stdout.flush() should work.
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/51630467
has comment: http://stackoverflow.com/comment/90531884
has comment: http://stackoverflow.com/comment/90532436
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90245444
has title: Log inside directory not the same outside directory
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/90245410
upvote count: 1
tagged with: logging
has comment: http://stackoverflow.com/comment/90532754
type: Question
has comment: http://stackoverflow.com/comment/90245359
has comment: http://stackoverflow.com/comment/90531688
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: My project structure is like that : |--projects |--scanner-app |--main.py So If I run my script from the scanner-app (amine@amine ~/scanner-app $ python main.py) I got log in the console like that : 2018-08-01 11:46:54,368 - root - INFO - Script Started But when I run the script from projects directory (amine@amine ~/projects $ python scanner-app/main.py) here is what I receive: INFO:root:Script Started This is my config file : { "version": 1, "disable_existing_loggers": false, "formatters": { "simple": { "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" } }, "handlers": { "console": { "class": "logging.StreamHandler", "level": "DEBUG", "formatter": "simple", "stream": "ext://sys.stdout" }, "info_file_handler": { "class": "logging.handlers.RotatingFileHandler", "level": "INFO", "formatter": "simple", "filename": "info.log", "maxBytes": 10485760, "backupCount": 20, "encoding": "utf8" }, "error_file_handler": { "class": "logging.handlers.RotatingFileHandler", "level": "ERROR", "formatter": "simple", "filename": "errors.log", "maxBytes": 10485760, "backupCount": 20, "encoding": "utf8" } }, "loggers": { "my_module": { "level": "ERROR", "handlers": ["console"], "propagate": "no" } }, "root": { "level": "INFO", "handlers": ["console", "info_file_handler", "error_file_handler"] } } And finally my fucntion that call the json file to configure the log : def setup_logging( default_path='logging.json', default_level=logging.DEBUG, env_key='LOG_CFG' ): """Setup logging configuration """ path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as f: config = json.load(f) logging.config.dictConfig(config) else: logging.basicConfig(level=default_level) I call my fucntion like that : setup_logging('logging.json', logging.DEBUG, 'LOG_CFG') I have 3 questions : Why I have 2 type of logs here ? In the second case when I run the script outside the root directory (scanner-app) I got some additional log (the…

http://stackoverflow.com/comment/90181113
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51607847
has text: Sorry I did not post letters_only code.
type: QuestionComment

http://stackoverflow.com/comment/90218632
type: Comment
comment on: http://stackoverflow.com/a/51626882
type: AnswerComment
has text: Very elegant, thank you. Lastly, is `random_state` in `df.sample` just for reproducibility? I don't actually need it?
score: 0

http://stackoverflow.com/comment/89995928
type: Comment
type: QuestionComment
has text: Can you provide an error log?
comment on: http://stackoverflow.com/q/51513808
score: 0

http://stackoverflow.com/q/51591908
favorite count: 0
tagged with: python-3.x
has body: I am converting some codes from Mathematica into Python. Suppose I have the following list: l = [["x1", "x2", "x3"], ["x4", "x5", "x6"], ["x7", "x8"], ["x9", "x10"], ["x11"]] I want to turn above into a polynomial such that the length of each element in the list would be the power of the variable x. In Mathematica I do this by: Total[x^Map[Length, l]] which gives: Output: x + 2 x^2 + 2 x^3 This means I have 1 element in list l with length 1, 2 elements with length 2 and 2 elements with length 3. In Python I have tried the following: sum(x**map(len(l), l)) But this does not work as x is not defined, also I tried with "x", and it does not work either. I wonder how does one translate such code.
tagged with: python
has answer: http://stackoverflow.com/a/51592629
accepted answer: http://stackoverflow.com/a/51592629
has comment: http://stackoverflow.com/comment/90149216
type: AnsweredQuestion
tagged with: list
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90149472
has comment: http://stackoverflow.com/comment/90149893
has comment: http://stackoverflow.com/comment/90149979
type: Question
has comment: http://stackoverflow.com/comment/90150661
has answer: http://stackoverflow.com/a/51592744
has comment: http://stackoverflow.com/comment/90149701
has answer: http://stackoverflow.com/a/51593107
has title: Converting a Mathematica code into Python
has comment: http://stackoverflow.com/comment/90150324
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/90150407
possible better answer: http://stackoverflow.com/a/51592744
tagged with: wolfram-mathematica

http://stackoverflow.com/q/51499715
type: Question
has answer: http://stackoverflow.com/a/51501798
has body: I am quite new to the whole world of Docker. Actually I am trying to establish an environment for different python machine learning applications which should act independently from each other in an own docker container. Since I dont really understood the way of using base images and trying to extend those base images I using a dockerfile for each new application which defines the different packages that I use. They all have in one thing in common - they use the command FROM python:3.6-slim as the base. I am looking for a starting point or way that I can easily extend this base image to form a new image which contains the individual packages that each of the application needs in order to save disk space. Right now, each of the images has a file size of approx. 1gb and hopefully this could be a solution to reduce the amount.
tagged with: docker
has title: Reuse Docker Images for multiple python applications
upvote count: 4
answer count: 1
accepted answer: http://stackoverflow.com/a/51501798
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/89967834
downvote count: 2
tagged with: dockerfile

http://stackoverflow.com/q/51500403
favorite count: 0
accepted answer: http://stackoverflow.com/a/51500830
tagged with: python
tagged with: sh
has comment: http://stackoverflow.com/comment/89969456
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89970779
tagged with: subprocess
possible better answer: http://stackoverflow.com/a/51500840
has comment: http://stackoverflow.com/comment/89969202
type: Question
has title: Kill Bash Script from within a python exception
has answer: http://stackoverflow.com/a/51500840
score: 5
has comment: http://stackoverflow.com/comment/89969418
has answer: http://stackoverflow.com/a/51500830
upvote count: 5
linked to: http://stackoverflow.com/q/821396
has comment: http://stackoverflow.com/comment/89969310
has comment: http://stackoverflow.com/comment/89971560
has comment: http://stackoverflow.com/comment/89969498
tagged with: bash
answer count: 3
has body: I have a shell script calling Python inside it. #! /bin/bash shopt -s extglob echo "====test====" ~/.conda/envs/my_env/bin/python &lt;&lt;'EOF' import sys import os try: print("inside python") x = 2/0 except Exception as e: print("Exception: %s" % e) sys.exit(2) print("at the end of python") EOF echo "end of script" If I execute this, the lines below still get printed. "end of script" I want to exit the shell in the exception block of the python script and let the script not reach EOF Is there a way to create and kill a subprocess in the except block above, that will kill the entire shell script? Can I spawn a dummy subprocess and kill it inside the exception block there by killing the entire shell script? Any examples would be helpful. Thanks in advance.
has answer: http://stackoverflow.com/a/51501141
downvote count: 0
has comment: http://stackoverflow.com/comment/89969576
tagged with: shell

http://stackoverflow.com/a/51548053
type: Answer
has body: You are missing __init__.py's within your folders (to indicate that they are import-able packages). app ├── __init__.py ├── a │ └── __init__.py └── b ├── c │ ├── __init__.py │ └── drive_train.py └── d ├── __init__.py └── serial.py Within app/__init__.py contains from app.b.d import serial. Within app/b/d/serial.py contains from app.b.c import drive_train. Within app/b/c/drive_train.py contains print("imported!"). Importing app from app/.. prints imported! I'll let you connect this example with your own code.
answers question: http://stackoverflow.com/q/51547793
score: 0

http://stackoverflow.com/comment/89993697
comment on: http://stackoverflow.com/a/51504034
score: 0
type: Comment
has text: When I declare the variable in outside the function : I have "UnboundLocalError: local variable 'buil' referenced before assignment" error .
type: AnswerComment

http://stackoverflow.com/q/51573309
upvote count: 5
answer count: 2
tagged with: string
has answer: http://stackoverflow.com/a/51573336
possible better answer: http://stackoverflow.com/a/51573341
favorite count: 0
has answer: http://stackoverflow.com/a/51573341
has comment: http://stackoverflow.com/comment/90112509
has comment: http://stackoverflow.com/comment/90112532
accepted answer: http://stackoverflow.com/a/51573336
tagged with: python
has title: How to create a statement that will print out words that start with particular word?
score: -1
has body: How to print words starting from a particular letter in python without using functions, but using methods or loops. 1 ) I got a string and wants to print words starting with 'm' St= "where is my mobile" result = "my", "mobile" 2 ) For the below list, how to output list starting with "p", which can be either lower or upper. List = ['mobile',"pencil","Pen","eraser","Book"] RESULT= "pencil","pen". Thanks Nb: This is not a homework, only a python newbie
downvote count: 6
has comment: http://stackoverflow.com/comment/90112513
type: AnsweredQuestion
tagged with: python-3.x
type: Question

http://stackoverflow.com/q/51584363
tagged with: python
upvote count: 23
has body: I have the following data: Invoice NoStockCode Description Quantity CustomerID Country 536365 85123A WHITE HANGING HEART T-LIGHT HOLDER 6 17850 United Kingdom 536365 71053 WHITE METAL LANTERN 6 17850 United Kingdom 536365 84406B CREAM CUPID HEARTS COAT HANGER 8 17850 United Kingdom I am trying to do a groupby so i have the following operation: df.groupby(['InvoiceNo','CustomerID','Country'])['NoStockCode','Description','Quantity'].apply(list) I want to get the output |Invoice |CustomerID |Country |NoStockCode |Description |Quantity |536365| |17850 |United Kingdom |85123A, 71053, 84406B |WHITE HANGING HEART T-LIGHT HOLDER, WHITE METAL LANTERN, CREAM CUPID HEARTS COAT HANGER |6, 6, 8 Instead I get: |Invoice |CustomerID |Country |0 |536365| |17850 |United Kingdom |['NoStockCode','Description','Quantity'] I have tried agg and other methods, but I haven't been able to get all of the columns to join as a list. I don't need to use the list function, but in the end I want the different columns to be lists.
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51584521
downvote count: 0
has title: Pandas groupby multiple columns, list of multiple columns
score: 23
has answer: http://stackoverflow.com/a/51584444
tagged with: pandas-groupby
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/51584457
accepted answer: http://stackoverflow.com/a/51584444
favorite count: 0
has answer: http://stackoverflow.com/a/51584498
possible better answer: http://stackoverflow.com/a/51584457

manova
tags question: http://stackoverflow.com/q/51553355
tag name: manova
type: Tag

http://stackoverflow.com/comment/90184956
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51609960
type: Comment
has text: It still doesn't find and click the "next" button. Here's the error I get: TimeoutException: Message:

http://stackoverflow.com/a/67775246
has comment: http://stackoverflow.com/comment/119828723
type: Answer
has body: I had the same issue. The issue is happening if the same request is sending multiple times to the server. This problem happened to me and as the error was intermittent, I initially believed that it was some firewall or antivirus problem, but it was much simpler. I had a form that was being submitted twice when the SEND button was clicked. The button was set to type="submit" and a javascript code submitted this form when this button was clicked. I changed the button to type="button" and the problem was solved.
answers question: http://stackoverflow.com/q/51562067
upvote count: 1
downvote count: 1
score: 0

http://stackoverflow.com/q/51617279
answer count: 0
score: 1
upvote count: 1
type: Question
has body: I'm trying to add keybinding functionality to my bearlibterminal project. Currently, using from bearlibterminal import terminal terminal.open() terminal.refresh() terminal.read() print(chr(terminal.state(terminal.TK_WCHAR))) I can get the proper unicode symbol for the current keyboard layout (for example, the same key gives me [ for the US layout and ü for the German layout). What I want is to be able to use "shift-ü" to match "Ü", or "shift-[" in the US layout to match "{", or "alt-q" in the German layout to match "@". I believe to do this I need to be able to both determine the currently active keyboard layout (for which I was able to find a bit) and the contents of the layout (for which I found nothing). Is this possible?
has title: How can I get the contents of the currently active keyboard layout in Python?
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51544615
answers question: http://stackoverflow.com/q/51544427
type: Answer
score: 2
has body: You can use GroupBy.size to calculate in-scope values. Then filter your original dataframe. nulls = df[df['Yurt'] == '-'].groupby('ID').size() df = df[df['ID'].isin(nulls[nulls == 2].index)] print(df) ID % Yurt 4 lmn789 0.837 Mickey's 5 lmn789 0.856 ChoppedCheese 6 lmn789 0.813 - 7 lmn789 0.812 - You may find this more efficient than a custom lambda function: def jpp(df): nulls = df[df['Yurt'] == '-'].groupby('ID').size() return df[df['ID'].isin(nulls[nulls == 2].index)] def root(df): return df.groupby('ID').filter(lambda grp: grp['Yurt'].eq('-').sum() == 2) %timeit jpp(df) # 2.99 ms per loop %timeit root(df) # 4.93 ms per loop
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/90160086
comment on: http://stackoverflow.com/q/51597021
score: 0
type: QuestionComment
has text: So when you pick this random positive number, what do you want to do to the lists to make them conform
type: Comment

http://stackoverflow.com/comment/90219904
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51627274
has text: Double quotes don't work because your `python -c ..` is bracketed with double quotes, and if you use it in your python script it will 'crash'
score: 0

http://stackoverflow.com/q/51601508
has title: Django & React with django-webpack-loader vs Decoupled App structure linked to Rest API?
favorite count: 0
has answer: http://stackoverflow.com/a/51601946
upvote count: 2
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/51601664
accepted answer: http://stackoverflow.com/a/51601946
type: Question
possible better answer: http://stackoverflow.com/a/51601664
tagged with: reactjs
tagged with: webpack
has body: I am reading through the following tutorial: http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/ I can't quite grasp what the added value is of using something like django-webpack-loader to fully integrate react.js and django when you can completely decouple django from react, running a separate frontend which links to a DRF rest api. I may be comparing apples to oranges here, but I am not sure. Any help ?
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/90046571
has text: have you tried accessing df111 in the function, it only exists in the scope of the function so wont be accessible outside of the function unless returned or assigned to a global variable
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51539125
score: 2

http://stackoverflow.com/comment/90775592
comment on: http://stackoverflow.com/a/51803709
score: 0
type: Comment
has text: I used a one shot iterator. Are you having issues reproducing the result ?
type: AnswerComment

peewee
tag name: peewee
tags question: http://stackoverflow.com/q/51600405
type: Tag
tags question: http://stackoverflow.com/q/51621799

http://stackoverflow.com/q/51547064
has answer: http://stackoverflow.com/a/62720461
has comment: http://stackoverflow.com/comment/90062161
answer count: 3
has title: Convert 18-digit LDAP/FILETIME timestamps to human readable date
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54131481
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/58739305
has comment: http://stackoverflow.com/comment/90062187
has body: I have exported a list of AD Users out of AD and need to validate their login times. The output from the powershell script give lastlogin as LDAP/FILE time EXAMPLE 130305048577611542 I am having trouble converting this to readable time in pandas Im using the following code: df['date of login'] = pd.to_datetime(df['FileTime'], unit='ns') The column FileTime contains time formatted like the EXAMPLE above. Im getting the following output in my new column date of login EXAMPLE 1974-02-17 03:50:48.577611542 I know this is being parsed incorrectly as when i input this date time on a online converter i get this output EXAMPLE: Epoch/Unix time: 1386031258 GMT: Tuesday, December 3, 2013 12:40:58 AM Your time zone: Monday, December 2, 2013 4:40:58 PM GMT-08:00 Anyone have an idea of what occuring here why are all my dates in the 1970'
upvote count: 3
type: Question
score: 3
linked to: http://stackoverflow.com/q/4869769

http://stackoverflow.com/a/51646865
score: 2
downvote count: 0
has body: Assigning to varname might run you into problems, especially as it won't iterate and you'll end up with one referencable tuple, instead of the large list of tuples you want to be able to look through. You might want to consider instantiating each reads() class into a collection of objects. For a list of objects, the object doesn't need a name, so you don't need a variable, just the collection list type will suffice. The penalty for later iterating through the records is not being able to reference one if you know the record id. Naming each one with a variable would be exponentially worse. The solution to preventing variable bloat and being able to reference each reads object by the record id is a dictionary. This seems consistent with how your code now tries to reveal the identity of the tuple by you later having to scan through to read the record id, which, in your case, is not yet made unique because all you've attached to it is '.txt', and your id values appear to be in a list. That list appears as though it might benefit from a list comprehension. In any case, for a named reference to the record, the dictionary would be labeled with a variable. Your record id could optionally be in the class, in case you move a record to a list and detach from the dictionary key for some reason... With the record id serving as the dictionary key, the following roughly approximates what you'd end up with for the data model: dict_varname = {'record_id_unique': } Your prototype namedtuple 'reads' can be reused using the namedtuple ._replace() method. The prototype never has to go into the list, it just has to be accessible as a functional blueprint. It's already labeled as the variable 'reads' in your example. You could name the variable something different, but it works that way. The class name is in quotes inside the parentheses of the namedtuple declaration. from collections import namedtuple as nt reads = nt('reads', ('id', 'length', 'text')) Some of the items of that prototype…
upvote count: 2
answers question: http://stackoverflow.com/q/51635713
type: Answer

http://stackoverflow.com/comment/121369418
type: Comment
type: QuestionComment
has text: Bravo, wish more high-ranking users were like you. Actually put in the time to explain why the question is wrong.
score: 0
comment on: http://stackoverflow.com/q/51553355

http://stackoverflow.com/comment/90090851
has text: The second method was there to demonstrate it happens by using tkinter inline or using classes. When root.destroy() is called, the mainloop stops and the program runs, but leaves the tkinter window behind being unresponsive. I'll update the question to be more clear.
type: Comment
comment on: http://stackoverflow.com/a/51557056
score: 0
type: AnswerComment

http://stackoverflow.com/a/51620099
accepted answer of: http://stackoverflow.com/q/51620014
type: AcceptedAnswer
has body: You can do this by modifying globals() but that's not really adviseable. for S in Sports: globals()[str(S)] = data.loc[data['Sport']==S] Below is a self-contained example: In [1]: import pandas as pd In [2]: df = pd.DataFrame({'sport':['football', 'football', 'tennis'], 'value':[1, 2, 3]}) In [3]: df Out[3]: sport value 0 football 1 1 football 2 2 tennis 3 In [4]: for name in df.sport.unique(): ...: globals()[name] = df.loc[df.sport == name] ...: In [4]: football Out[4]: sport value 0 football 1 1 football 2 While this is a direct answer to your question, I would recommend sacul's answer, dictionaries are meant for this (i.e. storing keys and values) and variable names inserted via globals() are usually not a good idea to begin with. Imagine someone else or yourself in the future reading your code - all of a sudden you are using football like a pd.DataFrame which you have never explicitly defined before - how are you supposed to know what is going on?
answers question: http://stackoverflow.com/q/51620014
type: Answer
score: 0

http://stackoverflow.com/q/51548079
tagged with: pymysql
has comment: http://stackoverflow.com/comment/90063988
has body: My output works in csv, but not when trying to insert it into mysql. I get the following error and have not been able to figure it out. I'm a novice so I may be missing something obvious. Same error in Python 2x and 3x. pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key, title, content, start_date, end_date, initial_update) VALUES('reddit', 'h' at line 1") mainDB_cnx = pymysql.connect(user='XXXX', password='XXXX', host='XXXX', database='Test', use_unicode=True, charset="utf8mb4") with mainDB_cnx: mainDB_cursor = mainDB_cnx.cursor() mainDB_cursor.execute( "INSERT INTO reddit(site, site_url, key, title, content, start_date, end_date, initial_update) VALUES(%s, %s, %s, %s, %s, STR_TO_DATE(%s,'%%Y-%%m-%%d'), STR_TO_DATE(%s,'%%Y-%%m-%%d'), STR_TO_DATE(%s,'%%Y-%%m-%%d'))", (["reddit", "http://www.reddit.com", url, title, content, datetime.strptime(date,'%d %B %Y').strftime('%Y-%m-%d'), datetime.strptime('2018-07-25','%Y-%m-%d').strftime('%Y-%m-%d'), datetime.strptime('2018-07-25','%Y-%m-%d').strftime('%Y-%m-%d')])) print("Successful")
tagged with: syntax-error
has comment: http://stackoverflow.com/comment/90063924
has comment: http://stackoverflow.com/comment/90064040
answer count: 1
has title: Can't get the right SQL syntax using pymsql, error 1064
tagged with: python
has comment: http://stackoverflow.com/comment/90063960
type: UnansweredQuestion
score: 0
tagged with: mysql
type: Question
has answer: http://stackoverflow.com/a/51548318

http://stackoverflow.com/q/51530814
tagged with: python
tagged with: openpyxl
has title: os.walk in Python
tagged with: excel
tagged with: os.walk
type: Question
has body: I'm trying to walk through directories of audio files in order to print out their data into an Excel sheet. Right now I'm only able to access the files in the root folder - I am stuck on accessing the files of in any subfolders. When I 'print(audio_file)' before the line 'if os.path.isfile(audio_file):' it loops through all the files in all directories, however I have the 'isfile' line so the code below only looks at the files. I'm stuck at this point and not sure what to do. The os.walk loop is at the bottom of the code: import openpyxl, os, wave, time, datetime from openpyxl.styles import Font from datetime import datetime os.chdir('c:\\Users\\Sonorityscape\\Desktop\\audiofiles') wb = openpyxl.Workbook() sheet = wb['Sheet'] headings = {'A1' : 'File Name', 'B1' : 'Relative Path', 'C1' : 'File Size', 'D1' : 'Date of Creation', 'E1' : 'File Length (hr:mn:sc.msc)', 'F1' : 'Channels', 'G1' : 'Sample Rate', 'H1' : 'Bit Depth'} cell_widths = {'A' : 30, 'B' : 40, 'C' : 11.5, 'D' : 19, 'E' : 25.75, 'F' : 10.5, 'G' : 13.5, 'H' : 10.5} for k, v in headings.items(): sheet[k].value = v sheet[k].font = Font(bold = True, name = 'Calibri', size = 12) for k, v in cell_widths.items(): sheet.column_dimensions[k].width = float(v) def file_info(file_name, folder_name, file_size, date_time, col_file, col_folder, col_size, col_time): sheet.cell(row = r, column = col_file).value = file_name sheet.cell(row = r, column = col_folder).value = folder_name sheet.cell(row = r, column = col_size).value = str(round((file_size / 2**20), 3)) + ' MB' sheet.cell(row = r, column = col_time).value = date_time def sample_rate(frames, col): frame_rate = w.getframerate() file_length = (frames / frame_rate) length_milliseconds = str(round((frames / frame_rate), 3)) sheet.cell(row = r, column = col).value = str(time.strftime('%H:%M:%S', time.gmtime(file_length))) + '.' + length_milliseconds[-3:] def wave_info(channels, frame_rate, bit_depth, col_chan, col_fr, col_bit): sheet.cell(row = r, column = col_chan)…
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51531178
type: UnansweredQuestion

http://stackoverflow.com/comment/90169532
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51601706
type: Comment
has text: `for mul in range(0,3)` => `for mul in range(3)` is shorter

http://stackoverflow.com/comment/90150545
type: AnswerComment
has text: @R71: You're welcome. What you're asking for now is rather off-topic, as it is basically an opinion poll ("which of these four workable options should I use?"). You may as well implement two or three and see how it goes.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51569664

http://stackoverflow.com/comment/90191302
has text: Thanks, its working! but program is quitting by any keystroke. Why is that?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51612269

http://stackoverflow.com/comment/115584403
type: Comment
has text: Why in the world is that other question considered (even nearly) equivalent to this one? This one is about _Pycharm_ and has a completely different approach to the title and is different in perspective. The choice of setting duplicates is often the most perplexing of close reasons on this site.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51552292

http://stackoverflow.com/comment/90047742
has text: Thanks a lot! I appreciate it
type: Comment
comment on: http://stackoverflow.com/a/51539885
score: 0
type: AnswerComment

http://stackoverflow.com/q/51483516
has comment: http://stackoverflow.com/comment/89943430
type: Question
tagged with: object
has comment: http://stackoverflow.com/comment/94937694
tagged with: class
has comment: http://stackoverflow.com/comment/89938429
score: 0
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51483639
tagged with: python
tagged with: properties
has title: How to make Multiply function inside a Class Python
tagged with: oop
has body: What am I missing here in the code or in function area? any pieces of advice? if anybody knows a very good place to study from it object-oriented programming please tell me and thanks. class Square(): def __init__(self,height=0,width=0): self._height = height self._width = width @property def height(self): return self._height @property def width(self): return self._width def area(self): return height * width @height.setter def set_height(self,new_height): self._height = new_height @width.setter def set_width(self,new_width): self._width = new_width
has comment: http://stackoverflow.com/comment/89942293

http://stackoverflow.com/comment/90055754
score: 1
type: AnswerComment
has text: Thanks between its performing better now :)
type: Comment
comment on: http://stackoverflow.com/a/51542050

http://stackoverflow.com/comment/90140072
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51587468
has text: Can you add sample data to question in floats?
score: 0

yaml
tags question: http://stackoverflow.com/q/51581941
tags question: http://stackoverflow.com/q/51496677
tags question: http://stackoverflow.com/q/51503779
tags question: http://stackoverflow.com/q/51529458
tags question: http://stackoverflow.com/q/51547996
tags question: http://stackoverflow.com/q/51546872
tags question: http://stackoverflow.com/q/51628463
tags question: http://stackoverflow.com/q/51629816
tag name: yaml
type: Tag
tags question: http://stackoverflow.com/q/51636378
tags question: http://stackoverflow.com/q/51534572

http://stackoverflow.com/comment/90151380
has text: The other keys would be `[key for key in dictyy if key not in ('first', 'last')]`.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51592945

http://stackoverflow.com/a/51505602
score: 0
type: Answer
has body: The minimum of the SSD distance ("sum of squared difference") is the maximum of the correlation. Correlations are known to be computed efficiently (in time N Log N instead of NM), by the famous FFT. With N=1000 and M=500000 you can expect a speedup.
has comment: http://stackoverflow.com/comment/89982578
has comment: http://stackoverflow.com/comment/89992628
has comment: http://stackoverflow.com/comment/90024658
answers question: http://stackoverflow.com/q/51486003

http://stackoverflow.com/comment/89988315
comment on: http://stackoverflow.com/a/51489407
type: Comment
has text: If you're able to import the base tensorflow module, can you access add_arg_scope through the whole tensorflow.contrib.framework.python.ops.add_arg_scope?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90161057
type: AnswerComment
comment on: http://stackoverflow.com/a/51596840
type: Comment
has text: Yeah it may be because of single double quotes.
score: 0

http://stackoverflow.com/comment/90194356
type: Comment
type: AnswerComment
has text: The last line path_dict[i] = 1, the key of the dict is your path and the value is an arbitrary number (1 in this case)
score: 0
comment on: http://stackoverflow.com/a/51614428

http://stackoverflow.com/q/51509999
has comment: http://stackoverflow.com/comment/90005307
tagged with: multidimensional-array
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/89993294
score: 0
tagged with: matplotlib
has body: I am currently working on a project related to space optimization. The project is basically arranging a set of objects within a box to use the least amount of space. I have the object's dimensions, surface area, volume, shape, etc. (units are originally in meter) The problem now is that I need to create a three dimensional box container to hold a certain number of objects where i can track the coordinates if they are filled out by an object or not. Say 'object 1' fills out the corner of the box so it fills coordinates [0,0,0] to [150,150,150] Note that i converted meter to millimeter, so when i put them in a 3D array i can disregard the decimal of the dimensions (minimize the inaccuracy). I tried using a three-dimensional array for the box but a problem arises when its dimensions is too big. so a box of 1x1x1 meter is equivalent to 1000 x 1000 x 1000 millimeter which leads to a memory error is there any alternative in creating such "box" environment that my algorithm can operate on in python? I tried matplotlib's pyplot 3d but i cant track the coordinates and give a specific length,width,height to the plot since it was really meant for plotting data, not storing them.
has comment: http://stackoverflow.com/comment/90005606
type: Question
has answer: http://stackoverflow.com/a/51519150
has comment: http://stackoverflow.com/comment/89990290
tagged with: arrays
has comment: http://stackoverflow.com/comment/90005314
has title: Creating a "box" environment in python for optimization
has comment: http://stackoverflow.com/comment/90005430
tagged with: optimization
has comment: http://stackoverflow.com/comment/90003079
has comment: http://stackoverflow.com/comment/90005373
answer count: 1

http://stackoverflow.com/q/51626203
tagged with: python
has comment: http://stackoverflow.com/comment/90224779
tagged with: nlp
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51630477
accepted answer: http://stackoverflow.com/a/51630477
type: Question
has title: Python: Create a new variable derived from extracting a sentence from a text
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90224521
has body: I have a data frame which one of the variables is a fairly long paragraph containing many sentences. Sometimes the sentences are separated by a full stop sometimes by a comma. I'm trying to create a new variable by extracting only selected parts of the text using selected words. Please see below a short sample of the data frame the result I have at the moment, followed by the code I'm using. Note - the text in the first variable is pretty large. PhysicalMentalDemands Physical_driving Physical_telephones [driving may be necessary [driving......] [telephones...] occasionally. as well as telephones will also be occasional to frequent.] Code used: searched_words = ['driving' , 'telephones'] for i in searched_words: Test ['Physical' +"_"+ str(i)] = Test ['PhysicalMentalDemands'].apply(lambda text: [sent for sent in sent_tokenize(text) if any(True for w in word_tokenize(sent) if w.lower() in searched_words)]) Issue: At the moment my code extract the sentences but extract using both of the words. I've seem other similar posts but none managed to solve my issue. Fixed searched_words = ['driving', 'physical'] for i in searched_words: df['Physical' + '_' + i] = result['PhysicalMentalDemands'].str.lower().apply(lambda text: [sent for sent in sent_tokenize(text) if i in word_tokenize(sent)])

pyorient
tag name: pyorient
tags question: http://stackoverflow.com/q/51637887
type: Tag

http://stackoverflow.com/a/51563986
accepted answer of: http://stackoverflow.com/q/51563736
upvote count: 2
type: AcceptedAnswer
type: Answer
has body: You omitted the underscores: if __name__ == "__main__" so it never entered the if. The print("Esperado: [%d]" % saidas) statements will fail, you can't format a list in that way. You could use print("Esperado: [%s]" % str(saidas)), but there's not much point, you might as well: print("Esperado:", saidas): if __name__ == "__main__": entradas = [[2, 50], [4, 90], [1, 38], [5, 105], [2, 48], [6, 120], [3, 65], [4, 80], [5, 100], [3, 60]] saidas = [250, 490, 138, 505, 248, 612, 365, 480, 500, 360] knn = KNNRegressao(entradas, saidas, 3) resultado = [] for entrada in entradas: resultado.append(knn.predict(entrada)) print("Esperado:", saidas) print("Predict:" resultado)
score: 2
answers question: http://stackoverflow.com/q/51563736
downvote count: 0

http://stackoverflow.com/comment/91500707
has text: @AnkitAgrawal I'll edit the answer. So it'll be more precise.
comment on: http://stackoverflow.com/a/52093118
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51547412
downvote count: 6
type: AnsweredQuestion
type: Question
score: -6
has title: Numpy arrays in a for loop
has comment: http://stackoverflow.com/comment/90062637
has comment: http://stackoverflow.com/comment/90062966
has answer: http://stackoverflow.com/a/51547456
tagged with: numpy
has comment: http://stackoverflow.com/comment/90062598
has comment: http://stackoverflow.com/comment/90062619
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: I want to accomplish the following in a loop: A1 = a/(a+b) B1 = A1*Z1 A2 = B1*Z2 B2 = A2*Z1 A3 = B2*Z2 B3 = A3*Z1 . . I tried putting the values in a list like so: val_A = [] val_B = [] val_A.append(A1) val_B.append(B1) for i in range(5): val_A.append(val_B[i]*Z1) val_B.append(val_A[i]*Z2) Output [0.9090909090909091, -0.4958677685950413, -0.4958677685950413, 0.270473328324568, 0.270473328324568] It works for the first 2 numbers but then it repeats the number twice. Can't figure out what's going on.
tagged with: python
accepted answer: http://stackoverflow.com/a/51547456

http://stackoverflow.com/q/51597306
downvote count: 0
type: UnansweredQuestion
has title: What is the most efficient algorithm to find pixel clusters and draw bbox
has comment: http://stackoverflow.com/comment/90160832
has answer: http://stackoverflow.com/a/51619846
has comment: http://stackoverflow.com/comment/90161664
favorite count: 0
type: Question
upvote count: 2
answer count: 2
tagged with: bounding-box
has comment: http://stackoverflow.com/comment/90161736
tagged with: python
tagged with: computer-vision
tagged with: object-detection
has answer: http://stackoverflow.com/a/51614354
has body: I have the following scenario, I have a N*N binary image and I want to find the number of clusters and draw bbox around them. A few requirements: - There is at least 1 cluster, there could be many. - The only parameter "controlable" is k being the maximum distance between pixels belonging to same cluster. Here is some code to show what I am talking about: 1. Generate a random image with 6 clusters (just a random example) Note: I don't want to improve this part, this is just for example. import numpy as np from PIL import Image from IPython.display import display def display_array(image): image_display_ready = (image * 255).astype(np.uint8) img = Image.fromarray(image_display_ready) display(img) def generate_image(): image = np.zeros([256,256]) for _ in range(200): while True: i, j = np.random.randint(25, 100, size=2) if image[i, j] == 0: break image[i, j] = 1 for _ in range(200): while True: i, j = np.random.randint(150, 225, size=2) if image[i, j] == 0: break image[i, j] = 1 for _ in range(100): while True: i, j = (np.random.randint(150, 225), np.random.randint(25, 50)) if image[i, j] == 0: break image[i, j] = 1 for _ in range(100): while True: i, j = (np.random.randint(150, 225), np.random.randint(75, 100)) if image[i, j] == 0: break image[i, j] = 1 for _ in range(100): while True: i, j = (np.random.randint(25, 50), np.random.randint(150, 225)) if image[i, j] == 0: break image[i, j] = 1 for _ in range(100): while True: i, j = (np.random.randint(75, 100), np.random.randint(150, 225)) if image[i, j] == 0: break image[i, j] = 1 return image image = generate_image() display_array(image) Output: 2. Find the number of clusters Below is the solution, I currently have, I would like to know if it can be improved. It doesn't look like an efficient solution to me. Note: lookup_range is the k parameter introduced earlier def compute_bbox_coordinates(mask_img, lookup_range, verbose=0): bbox_list = list() visited_pixels = list() bbox_found = 0 for i in range(mask_img.shape[0]):…
has comment: http://stackoverflow.com/comment/90160889
tagged with: numpy
score: 2

http://stackoverflow.com/a/51586303
upvote count: 1
has body: Taken from another answer: It appears to be a design decision in the python language. Functions still have local variables, but for loops don't create local variables. Previous proposals to make for-loop variables local to the loop have stumbled on the problem of existing code that relies on the loop variable keeping its value after exiting the loop, and it seems that this is regarded as a desirable feature. http://mail.python.org/pipermail/python-ideas/2008-October/002109.html
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/51586260

http://stackoverflow.com/comment/90063811
type: Comment
type: QuestionComment
has text: Can you expand on what you mean by 'it does not work'? Are you getting any exceptions, does it silently fail? Please create a [mcve] so it's easier for people to help you.
comment on: http://stackoverflow.com/q/51547926
score: 0

http://stackoverflow.com/comment/90079359
type: QuestionComment
score: 0
has text: Requirement already satisfied: xlrd in c:\users\XXX\appdata\local\programs\ python\python36-32\lib\site-packages (1.1.0)
type: Comment
comment on: http://stackoverflow.com/q/51556281

http://stackoverflow.com/a/51633400
has body: You need to zip the list and pass it as a dict: list = zip([(1,2,3,4,5,6,7,8),(1,2,3,4,5,6,7,8),(1,2,3,4,5,6,7,8)]) return render(request, 'accounts/page.html', {'list':list})
answers question: http://stackoverflow.com/q/51633309
has comment: http://stackoverflow.com/comment/90234681
type: Answer
has comment: http://stackoverflow.com/comment/90238222
score: 0

http://stackoverflow.com/comment/90236186
type: AnswerComment
has text: great. I'm gonna check it out and come back. in the meantime others are also offering solutions [here](https://gist.github.com/celliern/c715151a247dbb3c8caec15aeb9af83d) and [here](https://groups.google.com/forum/#!topic/sympy/V4KRzA-3doI). you may like to see them too.
type: Comment
comment on: http://stackoverflow.com/a/51635624
score: 0

http://stackoverflow.com/a/51524957
downvote count: 1
has body: You could work around this by using this link with selenium. The behavior might be slightly different, however. chrome-extension://&lt;the extension identity&gt;/html/login.html Visit this link to get extension identity: How to get extension identity
answers question: http://stackoverflow.com/q/51524109
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/90020948
type: Answer

http://stackoverflow.com/a/51539497
has body: Your are trying to decode JSON from empty file (size 0). Check your filepath and content of that file. Note: the example you have provided in your question is valid JSON, it should load without problem.
has comment: http://stackoverflow.com/comment/90093643
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90095432
type: Answer
has comment: http://stackoverflow.com/comment/90095383
has comment: http://stackoverflow.com/comment/90095605
score: 1
has comment: http://stackoverflow.com/comment/90095710
answers question: http://stackoverflow.com/q/51539344
has comment: http://stackoverflow.com/comment/90093543

libvirt
tag name: libvirt
tags question: http://stackoverflow.com/q/51576014
type: Tag

http://stackoverflow.com/q/51578043
type: AnsweredQuestion
has body: I am new in python and I was wondering the following. I have two matrices g1 and g2 and I would like to run a for loop for all the values of g1 and then g2. I initially thought I could do: for A in g1: ..... for A in g2: ..... But I was wondering if there is a way to run both at the same for loop. Eg. I tried this but it didn't work for A in g1,g2:
score: 0
has answer: http://stackoverflow.com/a/51578065
type: Question
has answer: http://stackoverflow.com/a/51578077
has comment: http://stackoverflow.com/comment/90121465
accepted answer: http://stackoverflow.com/a/51578065
has answer: http://stackoverflow.com/a/51578058
linked to: http://stackoverflow.com/q/1663807
has title: For loop run in two arrays
answer count: 3
tagged with: for-loop
possible better answer: http://stackoverflow.com/a/51578058
duplicate of: http://stackoverflow.com/q/1663807
tagged with: python

http://stackoverflow.com/a/51531869
type: Answer
has body: You can use generator comprehension in the following way: result = int(''.join((str(i) for i in a))) This turns every item of the list to a string, joins the list together and then turns the whole thing back to an integer
score: 0
answers question: http://stackoverflow.com/q/51531804

http://stackoverflow.com/a/51622468
accepted answer of: http://stackoverflow.com/q/51622144
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51622144
has comment: http://stackoverflow.com/comment/90240091
has comment: http://stackoverflow.com/comment/90239359
has comment: http://stackoverflow.com/comment/90240865
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90240499
has comment: http://stackoverflow.com/comment/90240779
has body: You're right; I strongly suspect that you have one or more features in your X data that is nearly perfectly correlated with the Y data. Usually this is bad, because those variables don't explain Y but are either explained by Y or jointly determined with Y. To troubleshoot this, consider performing a linear regression of Y on X and then using simple p values or AIC/BIC to determine which X variables are the least relevant. Drop these and repeat the process until your R^2 begins to drop seriously (though it will drop a little each time). The remaining variables will be the most relevant in prediction, and hopefully you'll be able to identify from that subset which variables are so tightly correlated with Y.

http://stackoverflow.com/comment/90068681
has text: @RafaelC Apply this to the result of most_common without arguments. Slice off the first n elements.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51550679

http://stackoverflow.com/comment/89957249
has text: What do you mean, "in between requests"? How are you running this code?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51493502

http
tags question: http://stackoverflow.com/q/51563910
tags question: http://stackoverflow.com/q/51630571
tags question: http://stackoverflow.com/q/51545033
tag name: http
tags question: http://stackoverflow.com/q/51549087
tags question: http://stackoverflow.com/q/51581676
type: Tag
tags question: http://stackoverflow.com/q/51592560
tags question: http://stackoverflow.com/q/51585240
tags question: http://stackoverflow.com/q/51491246

http://stackoverflow.com/q/51603520
has title: Pandas: remove duplicates that exist in any order
tagged with: python
has comment: http://stackoverflow.com/comment/90173135
type: AnsweredQuestion
upvote count: 5
has answer: http://stackoverflow.com/a/51603585
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/51603585
downvote count: 0
has comment: http://stackoverflow.com/comment/90173074
has body: My question is similar to Pandas: remove reverse duplicates from dataframe but I have an additional requirement. I need to maintain row value pairs. For example: I have data where column A corresponds to column C and column B corresponds to column D. import pandas as pd # Initial data frame data = pd.DataFrame({'A': [0, 10, 11, 21, 22, 35, 5, 50], 'B': [50, 22, 35, 5, 10, 11, 21, 0], 'C': ["a", "b", "r", "x", "c", "w", "z", "y"], 'D': ["y", "c", "w", "z", "b", "r", "x", "a"]}) data # A B C D #0 0 50 a y #1 10 22 b c #2 11 35 r w #3 21 5 x z #4 22 10 c b #5 35 11 w r #6 5 21 z x #7 50 0 y a I would like to remove duplicates that exist in columns A and B but I need to preserve their corresponding letter value in columns C and D. I have a solution here but is there a more elegant way of doing this? # Desired data frame new_data = pd.DataFrame() # Concat numbers and corresponding letters new_data['AC'] = data['A'].astype(str) + ',' + data['C'] new_data['BD'] = data['B'].astype(str) + ',' + data['D'] # Drop duplicates despite order new_data = new_data.apply(lambda r: sorted(r), axis = 1).drop_duplicates() # Recreate dataframe new_data = pd.DataFrame.from_items(zip(new_data.index, new_data.values)).T new_data = pd.concat([new_data.iloc[:,0].str.split(',', expand=True), new_data.iloc[:,1].str.split(',', expand=True)], axis=1) new_data.columns=['A', 'B', 'C', 'D'] new_data # A B C D #0 0 a 50 y #1 10 b 22 c #2 11 r 35 w #3 21 x 5 z EDIT technically output should look like this: new_data.columns=['A', 'C', 'B', 'D'] new_data # A B C D #0 0 a 50 y #1 10 b 22 c #2 11 r 35 w #3 21 x 5 z
favorite count: 0
has answer: http://stackoverflow.com/a/51603649
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/40474799
possible better answer: http://stackoverflow.com/a/51603599
has answer: http://stackoverflow.com/a/51603599

http://stackoverflow.com/comment/90109053
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51560331
has text: Then what is exactly the question? It is not clear now, it is running with AVX2 and there is an improvement with it.
score: 0

http://stackoverflow.com/comment/90147356
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51587175
has text: What have you tried so far and where are you stuck exactly?
score: 0

http://stackoverflow.com/comment/90027770
has text: Although this answer is on the right track, it doesn't provide the expected results. For instance, if we remove commas at the beginning, there is the chance of joining two numbers entered as "123,456", which would result in "123456".
type: Comment
comment on: http://stackoverflow.com/a/51489369
score: 0
type: AnswerComment

http://stackoverflow.com/q/51493578
has comment: http://stackoverflow.com/comment/89959292
has comment: http://stackoverflow.com/comment/89955777
has body: Below is a code to remove the recurrent alphabets from a string in python. I would like to know the time complexity of this code. More specifically time complexity of line if string_1[i] not in char_found:. Searching in a list. Also if possible can this be explained using space allocated by a list. def remove_recorring_char(string_1): result = "" char_found = [] for i in range(0,len(string_1)): if string_1[i] not in char_found: char_found.append(string_1[i]) result = result+string_1[i] return result if __name__== "__main__": print(remove_recorring_char("aabbbcc")) print(remove_recorring_char("chdsgdsgggsggsjddaaxcvcj"))
type: AnsweredQuestion
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/51493719
has comment: http://stackoverflow.com/comment/89955703
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/89957695
has title: What is the time complexity of the below code in python?
has answer: http://stackoverflow.com/a/51493719

http://stackoverflow.com/comment/111851301
comment on: http://stackoverflow.com/a/59229237
type: Comment
type: AnswerComment
has text: perhaps using `.item()` would be better than `.float()`
score: 0

http://stackoverflow.com/q/51631237
has comment: http://stackoverflow.com/comment/90226539
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/90228040
has comment: http://stackoverflow.com/comment/90227304
has comment: http://stackoverflow.com/comment/90227620
has body: I am working on a Django project and have some instances of a class. I cached instance A with key 'A', and create a new instance B in another request. The thing is instance B now has data of instance A. When I change instance B's data and get instance 'A' from cache, instance A's data changes too. I guess this has something to do with python's reuse mechanism. Anyone know how to fix this problem? Edit 1: This is how I create a class using its name: def create_model_by_name(name): name = name.capitalize() klass = globals()[name] instance = klass() return instance I use django.core.cache.cache to cache objects. This is some data I store in my class. I have some classes inherited from Abstract. class Abstract: class_name = 'unknown' prev_text = [] props = {} waiting_state = '' output = '' props_alias = {}
has answer: http://stackoverflow.com/a/51631731
linked to: http://stackoverflow.com/q/1680528
tagged with: caching
type: Question
answer count: 2
score: 0
has title: Cached object is reused in Django
tagged with: python
duplicate of: http://stackoverflow.com/q/1680528
has answer: http://stackoverflow.com/a/51631719

http://stackoverflow.com/q/51557940
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90091547
downvote count: 1
tagged with: tensorflow
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/51562743
score: -1
tagged with: keras
has title: Python Keras - CNN stuck on epoch 1
answer count: 1
has body: from keras import * import os import numpy as np from keras.models import Sequential from keras.layers import Activation, Dropout, Flatten, Dense from keras.preprocessing.image import ImageDataGenerator from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D from keras import optimizers #from parser import load_data # data loading # Collecting data: img_width, img_height = 150, 150 training_data_dir = "train" testing_data_dir = "test" # used to rescale the pixel values from [0, 255] to [0, 1] interval datagen = ImageDataGenerator(rescale=1./255) # automagically retrieve images and their classes for train and validation sets train_generator = datagen.flow_from_directory( training_data_dir, target_size=(img_width, img_height), batch_size=16, class_mode='binary') test_generator = datagen.flow_from_directory( testing_data_dir, target_size=(img_width, img_height), batch_size=32, class_mode='binary') # Building model: model = Sequential() model.add(Convolution2D(32, 3, 3, input_shape=(img_width, img_height,3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(32, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(64, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation('sigmoid')) model.compile(loss="binary_crossentropy", optimizer="rmsprop", metrics=["accuracy"]) # Training model: nb_epoch = 30 nb_train_samples = 2048 nb_validation_samples = 832 model.fit_generator( train_generator, samples_per_epoch=nb_train_samples, nb_epoch=nb_epoch, validation_data=test_generator, nb_val_samples=nb_validation_samples) This is my code for a CNN which is trained using images from the folders train and test. But whenever I try training it, the program seems to get stuck at epoch 1/30 all the time, i left it on overnig…
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90088617
has answer: http://stackoverflow.com/a/51562743

http://stackoverflow.com/a/51544421
accepted answer of: http://stackoverflow.com/q/51543507
has comment: http://stackoverflow.com/comment/90062915
type: AcceptedAnswer
downvote count: 0
has body: You could approximate the same unit length on both x-axes by specifying the gridspec_kw parameter that defines the ratio of the subplots. import numpy as np from matplotlib import pyplot as plt t1 = np.linspace(0, 1, 1000) t2 = np.linspace(0, 0.5, 1000) fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = {"width_ratios": [np.max(t1)-np.min(t1), np.max(t2)-np.min(t2)]}) ax1.plot(t1, np.sin(t1 * np.pi)) ax2.plot(t2, np.sin(t2 * np.pi)) plt.show() Sample output:
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/90059584
score: 2
answers question: http://stackoverflow.com/q/51543507

http://stackoverflow.com/q/51568417
upvote count: 4
answer count: 4
has answer: http://stackoverflow.com/a/55339505
has body: I'm using the latest version of pycharm 2018.2, on Windows. I've also updated the Google Cloud Sdk to the latest versions too. When I use the built in App Engine run configuration in Pycharm: I get an import error ImportError: cannot import name _common appearing in the run window: "C:\Program Files\JetBrains\PyCharm 2018.1.1\bin\runnerw.exe" C:\Code\my- project\env\Scripts\python.exe "C:/Program Files (x86)/Google/Cloud SDK/google-cloud-sdk/bin/dev_appserver.py" --port 8484 app.yaml tasks.yaml longtasks.yaml --log_level=debug Traceback (most recent call last): File "C:/Program Files (x86)/Google/Cloud SDK/google-cloud- sdk/bin/dev_appserver.py", line 12, in &lt;module&gt; from bootstrapping import bootstrapping File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud- sdk\bin\bootstrapping\bootstrapping.py", line 24, in &lt;module&gt; from . import setup # pylint:disable=g-import-not-at-top File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud- sdk\bin\bootstrapping\setup.py", line 55, in &lt;module&gt; from googlecloudsdk.core import properties File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud- sdk\lib\googlecloudsdk\core\properties.py", line 36, in &lt;module&gt; from googlecloudsdk.core.util import times File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud- sdk\lib\googlecloudsdk\core\util\times.py", line 55, in &lt;module&gt; from dateutil.tz import _common as tz_common ImportError: cannot import name _common Process finished with exit code 1 The dateutil.tz package is located in C:\Python27\Lib\site-packages and I have a dateutil package in the project I'm running. I don't know whether that has something to do with the issue. I've tried changing the default python interpreter which also did not work. I've tried running Pycharm as administrator which also had no effect. Both the debug and non-debug run commands result in this issue. If I run the command to start up dev_appserver.py directly in the terminal (with or without virtual environm…
has comment: http://stackoverflow.com/comment/90224305
has comment: http://stackoverflow.com/comment/90379844
has answer: http://stackoverflow.com/a/60838956
tagged with: pycharm
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19885821
tagged with: dev-appserver
has comment: http://stackoverflow.com/comment/90222197
downvote count: 0
has comment: http://stackoverflow.com/comment/90120841
has answer: http://stackoverflow.com/a/58009489
has comment: http://stackoverflow.com/comment/90103562
type: Question
has answer: http://stackoverflow.com/a/52561496
score: 4
has comment: http://stackoverflow.com/comment/90161891
has comment: http://stackoverflow.com/comment/90108660
favorite count: 0
has title: ImportError when running dev_appserver.py from pycharm
has comment: http://stackoverflow.com/comment/90112782
tagged with: google-app-engine
tagged with: python

http://stackoverflow.com/a/51640019
has comment: http://stackoverflow.com/comment/90294673
has comment: http://stackoverflow.com/comment/90320770
type: Answer
has body: [I am assuming you have the latest version of the Python extension for VS code installed as this won't have anything directly to do with VS Code 1.25.1] If you are using the new language server from the Python extension then errors as you type do not turn off at the moment (you referenced the specific issue suggesting having a setting to turn that off). If you're not using the new language server than the extension only runs linters on save, which would mean you have automatic saving as you type turned on and that's triggering the constant linting of your code. Tweak your settings to not automatically save and that will stop constant linting (and you can specify settings in VS Code for specific languages if you only want to change this for Python).
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51629696
accepted answer of: http://stackoverflow.com/q/51629696
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89981048
comment on: http://stackoverflow.com/a/51505879
type: AnswerComment
score: 0
type: Comment
has text: @Muzol My apologies; I was unclear on what you wanted. I'm not sure there's a good way to do that. You might be better off using Ctrl + C

http://stackoverflow.com/comment/90066290
comment on: http://stackoverflow.com/a/51527614
score: 0
has text: Is there a better way to go about writing a decorator? Following PEP 20 the zen of python "Simple is better than complex. Flat is better than nested." the nested function seems a bit obnoxious if you ask me.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/90092091
has text: @AnderBiguri I tried `numpy.linalg.solve` according to your advise but it unfortunately returns the same result that I got with using `inv`. :(
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51562302
score: 0

http://stackoverflow.com/q/51574574
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51574740
has body: I am trying to delete the rows that do not contain "HW" or "CA" in column Vndr. This is my code: data.drop(data[data.Vndr != 'HW' or 'CA'].index) I am getting this error "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."
score: 1
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51574723
favorite count: 0
has title: Pandas - Python drop rows if Column contains multiples criteria
tagged with: pandas
has answer: http://stackoverflow.com/a/51574659
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/57300158

http://stackoverflow.com/q/51623898
score: 0
has comment: http://stackoverflow.com/comment/90212982
has body: So I am trying to build a NIM game. I got stuck with the reducing from the list and printing out an updated list instead: #reduces from board-list def reducer(choice_1, choice_2,board): if choice_1 == 'a': board[0] - int(choice_2) if choice_1 == 'b': board[1] - int(choice_2) if choice_1 == 'c': board[2] - int(choice_2) def lets_play(): import random board = [5,4,3] print ('a) |') print ('b) |||') print ('c) |||||') chosen_move = input('type in letter of choice: ') chosen_move2 = input ('choose amount you wish to reduce: ') reducer (chosen_move,chosen_move2,board) print (board) When I try printing the board after the changes from the user input, the list does not change. I am obviously missing out on something. Appreciate the help Thanks
tagged with: nim-game
tagged with: python
type: AnsweredQuestion
tagged with: list
has title: How to reduce values in list using user input and printing updated list
type: Question
has answer: http://stackoverflow.com/a/51623951
accepted answer: http://stackoverflow.com/a/51623951
answer count: 1

http://stackoverflow.com/comment/90050101
type: QuestionComment
comment on: http://stackoverflow.com/q/51541164
has text: Can we see your `urls.py`
score: 0
type: Comment

http://stackoverflow.com/comment/89965422
type: Comment
type: QuestionComment
has text: Same result, unfortunately. Appreciate the help though.
comment on: http://stackoverflow.com/q/51486736
score: 0

http://stackoverflow.com/a/51628747
score: 0
answers question: http://stackoverflow.com/q/51626747
type: Answer
has body: Have you tried with Xo[:,k+1] instead of Xo(:,k+1)? Python uses [] for slicing and indexing. EDIT: Xo = np.array([[ix],[idx]]) This creates a 1x1 array with 1 value: (ix, idx). I think you're looking for something like Xo = np.zeros((ix, idx)), which will give you an ixxidx array initialized to zeros. If you don't need the zeros you can use Xo = np.empty((ix, idx)). See the docs on array creation.
has comment: http://stackoverflow.com/comment/90249824

http://stackoverflow.com/q/51619554
has title: Having trouble submitting a query that has > and < signs to Bigquery API
tagged with: google-bigquery
type: Question
score: -1
tagged with: python-2.7
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51620161
accepted answer: http://stackoverflow.com/a/51620161
tagged with: python
has body: Our environment uses Python 2.7 along with BigQuery library 0.27.0. The query that is to be submitted is part of a JSON string which is loaded by json.loads(json_blob) then the value for query is extracted from a key: query_str = json_blob["sql_command"] Printing the query_str gives the following value: ('query_str: ', '" select distinct id from my_table where step_count &gt; 3 and lower(name) = \'test\') "') When the script submits the query for execution as following: job = self.bq_client.run_async_query(job_id, query_str, udf_resources=udf_obj, query_parameters=query_params) BigQuery job comes back with an error, and when I lookup the job information using the job_id on https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/get I see that the query that is actually executed is as following: select distinct id from my_table where step_count \u003e 3 and lower(name) = 'test') I have read on encoding/decoding and tried them, and doesn't make a diference. Is there a way that I can convert that query_str retrieved from the json_blob (query_str = json_blob["sql_command"]) to a true string? We know that when we define such query as a string (hard-coded in the script rather than retrieved from a key in a JSON blob) the query gets executed successfully, ex. query_str = """select distinct id from my_table where step_count &gt; 3 and lower(name) = 'test')""" Any suggestions is greatly appreciated.
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/q/51634450
tagged with: python-3.x
has title: Python Flask Web Application - Multi-line Input Option
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
linked to: http://stackoverflow.com/q/11556958
has answer: http://stackoverflow.com/a/51638624
type: Question
has body: I am building a Flask application that has a text box and allows users to type in a domain name and submit the form with a button (the results of the search appear in HTML below the search box). I want to support multiple domain entry at once using a textarea input box. How can I use a button to toggle the form (or use a separate form) between using the text box input and the text area based on the button the user selects? And how can I take the input from the related box and process it in python?
tagged with: flask
has comment: http://stackoverflow.com/comment/90233316
score: 0
answer count: 1

http://stackoverflow.com/comment/89952014
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51490597
has text: One missed thing here is a definition of script encoding, a line looking like "# -*- coding: <encoding name> -*-". See [PEP263](https://www.python.org/dev/peps/pep-0263/) for details.
score: 0

http://stackoverflow.com/comment/90148240
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51590693
has text: That works like a charm, with a run time in the order of seconds. Thanks.
type: AnswerComment

http://stackoverflow.com/q/51567500
has title: How to delete canvas on Python Tkinter?
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90103495
upvote count: 1
downvote count: 1
type: Question
has body: import tkinter from tkinter import font def deleteButton(event): canvas.delete("tag1") main = tkinter.Tk() main.geometry("1280x720+320+180") main.resizable(0,0) cv = tkinter.Canvas(main, bg = "turquoise", width = 200, height = 200) cv.create_polygon(400, 400, 400, 400, fill = "turquoise", tag = "tag1") cv.place(x = 300, y = 300) cv.pack() start_button = tkinter.Button(main, text = "Play!", command = deleteButton, fg =` `"white", bg = "#0A9AFF", relief = "flat") start_button.place(x = 625, y = 300) main.mainloop() when run this code, I get "TypeError: deleteButton() missing 1 required positional argument: 'event'." I've already tried to .bind but I couldn't fix it. I want to delete canvas with pushing button, how can I do that? Starting new line doesn't work. Thank you
has comment: http://stackoverflow.com/comment/90108365
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51567529
has comment: http://stackoverflow.com/comment/90108616
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90101886
tagged with: python
has answer: http://stackoverflow.com/a/51571253

http://stackoverflow.com/comment/90173074
has text: Why `B` and `C` were swaped at the end?
type: QuestionComment
comment on: http://stackoverflow.com/q/51603520
score: 2
type: Comment

http://stackoverflow.com/a/51573809
type: Answer
accepted answer of: http://stackoverflow.com/q/51573795
answers question: http://stackoverflow.com/q/51573795
score: 0
type: AcceptedAnswer
has body: You can use zip() to achieve this as: >>> ol = [("a","b","c"),("A","B","C")] # v to unpack the list >>> nL = [''.join(x) for x in zip(*ol)] # OR explicitly concatenate elements at each index # >>> nL = [a+b for a, b in zip(*ol)] >>> nL ['aA', 'bB', 'cC']

http://stackoverflow.com/q/51491325
accepted answer: http://stackoverflow.com/a/51492321
has body: I'm reading this book called Master Object Oriented programming Python by Steven Lott. I came across this code: class Card: def __init__( self, rank, suit ): self.suit= suit self.rank= rank self.hard, self.soft = self._points() class NumberCard( Card ): def _points( self ): return int(self.rank), int(self.rank) class AceCard( Card ): def _points( self ): return 1, 11 class FaceCard( Card ): def _points( self ): return 10, 10 I'm not able to understand how can self._points() in Card be legal expression. I run the code in compiler too it stats the following error Instance of Card has No points member Full Code I have kept it as gist here
has comment: http://stackoverflow.com/comment/89951619
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89951180
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/89952256
has title: Instance error in OOP design: Instance of Card has No points member
tagged with: python
has answer: http://stackoverflow.com/a/51492321
tagged with: oop
possible better answer: http://stackoverflow.com/a/51492369
has comment: http://stackoverflow.com/comment/89952292
has answer: http://stackoverflow.com/a/51492369

http://stackoverflow.com/a/51494111
score: 2
answers question: http://stackoverflow.com/q/51493842
downvote count: 0
has body: You can even do it without pandas: data = [ [51, 'F', 46, 'M', 0, 15100, 531, 555], [52, 'M', 29, 'M', 2, 14200, 673, 633], [53, 'M', 25, 'S', 0, 22200, 742, 998], [54, 'M', 36, 'M', 2, 1000, 677, 646], [55, 'F', 99, 'S', 0, 10600, 608, 998], [56, 'F', 45, 'M', 2, 6100, 710, 743], [57, 'M', 99, 'M', 2, 16500, 679, 646], [58, 'F', 37, 'M', 0, 7400, 637, 683], [59, 'M', 45, 'S', 0, 22800, 683, 998], [60, 'M', 22, 'S', 0, 6400, 699, 998], ] sorted(data, key=lambda x: x[2]) and we can also define a function which can be used with a key: def filter(key): index = ['id', 'gen', 'age', 'mar', 'loc', 'inc', 'iscr', 'escr'].index(key) return index The call of sorted changes to sorted(data, key=lambda x: x[filter('age')])
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51493842

http://stackoverflow.com/q/51629009
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90223163
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90222305
type: Question
has body: When i did file = pd.read_csv("x.csv"), it does read the csv into a dataframe and doing head() it looks alright with the correct columns shown. As my csv has 1M + rows, i expect to see 1M + when i do len(file), but i saw 19M+. What could be the problem? Using my friend's computer and doing the same thing for a test csv file gives the right number of rows after doing len(file). The file contains weird special characters like chinese characters that are probably shown as ?? in the csv. Thus, i'm quite sure it isn't because of the function used - is it more likely the difference between python 2 and 3, delimiter used (default ,) or dirty data such as missing rows, or other reasons? E.g csv containing col1 col2 col3 col4 a 112 111 q??p
has comment: http://stackoverflow.com/comment/90222395
has comment: http://stackoverflow.com/comment/90223814
has title: python pandas read_csv length is > rows in csv
has comment: http://stackoverflow.com/comment/90224067
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90222626

http://stackoverflow.com/comment/90093375
has text: If I just have the median, that would be great. med_loc is not absolutely necessary. Spark version is 2.1.1.
comment on: http://stackoverflow.com/q/51550341
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90220738
type: Comment
comment on: http://stackoverflow.com/a/51627351
has text: It is very strange, have you tried the first option? Is the histogram image saved correctly?
type: AnswerComment
score: 0

apache
tag name: apache
tags question: http://stackoverflow.com/q/51532928
tags question: http://stackoverflow.com/q/51622109
tags question: http://stackoverflow.com/q/51499246
tags question: http://stackoverflow.com/q/51505589
tags question: http://stackoverflow.com/q/51484646
type: Tag
tags question: http://stackoverflow.com/q/51571899

http://stackoverflow.com/comment/90098031
type: AnswerComment
type: Comment
has text: Additionally, the last codes you wrote .( I mean `{ key:my_key,...` ) are giving syntax error in PYTHON.
comment on: http://stackoverflow.com/a/51563770
score: 0

http://stackoverflow.com/comment/90166328
type: Comment
score: 0
type: AnswerComment
has text: Is there a way to add some logic if the image on that page is jpeg or png or will the type not matter if a png is saved as .jpg?
comment on: http://stackoverflow.com/a/51599859

http://stackoverflow.com/q/51526190
answer count: 2
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90029076
has answer: http://stackoverflow.com/a/51526715
has answer: http://stackoverflow.com/a/51538159
has title: Django POST with ModelViewSet and ModelSerializer 405
downvote count: 0
type: UnansweredQuestion
tagged with: django-rest-framework
type: Question
score: 1
favorite count: 0
has body: How can I make a ModelViewSet accept the POST method to create an object? When I attempt to call the endpoint I get a 405 'Method "POST" not allowed.'. Within views.py: class AccountViewSet(viewsets.ModelViewSet): """An Account ModelViewSet.""" model = Account serializer_class = AccountSerializer queryset = Account.objects.all().order_by('name') Within serializers.py: class AccountSerializer(serializers.ModelSerializer): name = serializers.CharField(required=False) active_until = serializers.DateTimeField() class Meta: model = Account fields = [ 'name', 'active_until', ] def create(self, validated_data): with transaction.atomic(): Account.objects.create(**validated_data) within urls.py: from rest_framework import routers router = routers.SimpleRouter() router.register( prefix=r'v1/auth/accounts', viewset=AccountViewSet, base_name='accounts', ) Do I need to create a specific @action? my attempts to do so have yet to be successful. If that is the case what would the url = reverse('app:accounts-&lt;NAME&gt;') be such that I can call it from tests? I haven't found a full example (urls.py, views.py, serializers.py, and tests etc).
has comment: http://stackoverflow.com/comment/90043211

http://stackoverflow.com/q/51600622
type: UnansweredQuestion
has body: I am looking to install pip on my Linux sevrer with Suse 11 and has Python 2.6.9. I tried with zypper install python-pip but I got the below error zypper install python-pip Loading repository data... Reading installed packages... Package 'python-pip' not found. Resolving package dependencies... Nothing to do. Am I missing anything here , is there any other method to download pip ?
tagged with: pip
has title: Installing pip on Suse 11 with Python 2.6.9
downvote count: 1
type: Question
score: 1
has answer: http://stackoverflow.com/a/51601857
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90167725
tagged with: sles
tagged with: python
upvote count: 2

http://stackoverflow.com/comment/90090879
has text: This code only works as long as you never call `setName`. Try inserting some of these into your dict as keys, then calling `setName` on them, then trying to look them up, iterate the dict, add a new key that has the name the old one used to have, etc.
comment on: http://stackoverflow.com/a/51561720
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89995391
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51513220
has text: @WillemVanOnsem and groupBy does not add to the complexity, right?
score: 0

http://stackoverflow.com/comment/90163736
type: Comment
type: QuestionComment
score: 5
has text: When would anything ever be in `found`?
comment on: http://stackoverflow.com/q/51598916

http://stackoverflow.com/comment/103034067
type: Comment
comment on: http://stackoverflow.com/a/52918528
score: 2
has text: I have to use tempfile.TemporaryFile(mode = "r+") and code = get_default_cli().invoke(args, out_file=temp) But all the other bits work great!! Thank you.
type: AnswerComment

http://stackoverflow.com/q/51577822
tagged with: python
has comment: http://stackoverflow.com/comment/90122194
has comment: http://stackoverflow.com/comment/90121227
has comment: http://stackoverflow.com/comment/90125556
answer count: 0
has body: i have question. I have models called Visitor, that i don't want to Migrate when i run flask db migrate, because i already have the table in database. my question is how to avoid that models to become a table ? here my visitor.py class Visitor(db.Model): id = db.Column(db.Integer(), primary_key=True) Name = db.Column(db.String(50)) DateDeparture = db.Column(db.DateTime()) DateArrival = db.Column(db.DateTime()) FlightNo = db.Column(db.String(15)) LocationFrom = db.Column( db.Integer(), db.ForeignKey('Location.id') ) LocationTo = db.Column( db.Integer(), db.ForeignKey('Location.id') ) DriverId = db.Column( db.Integer(), db.ForeignKey('Driver.id') ) NoVehicle = db.Column( db.Integer(), db.ForeignKey('Vehicle.id') ) Marks = db.Column(db.Text()) Status = db.Column(db.String(11)) CancelMark = db.Column(db.Text()) is_pickup = db.Column(db.String(1)) Thank you :)
linked to: http://stackoverflow.com/q/41989969
has title: How to ignore some models to migrate?
tagged with: flask-migrate
type: Question
duplicate of: http://stackoverflow.com/q/41989969
score: 0
tagged with: alembic
tagged with: flask
has comment: http://stackoverflow.com/comment/90122206
type: UnansweredQuestion

http://stackoverflow.com/q/51630093
has title: Does anyone knows if python can use the message group in activemq
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: activemq-classic
downvote count: 2
type: Question
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/51630350
answer count: 1
favorite count: 0
has body: Our project use Django and my leader want me to use the message group in activemq, but I did't find how to use it with python, I need your help.

http://stackoverflow.com/comment/89948646
has text: While this has been marked as duplicate, there is a little more nuance here than just python slice notation. For one, normal python arrays cannot accept a tuple as a slice, that is part of numpy. Secondly it's not clear if it's the slice notation itself which is the question or if it's why the last axis has been reversed. I imagine the image you're plotting is in greyscale, if you try it with a color image you will find the red and blue color channels have been reversed.
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51489880

http://stackoverflow.com/comment/90046283
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51538489
has text: First convert your parsed arguments to a dictionary. `args = vars(parser.parse_args())` `vars` converts to a dictionary. Now you can pop those that you don't want to be your kwargs from this dictionary. `a = args.pop('a')` and `b = args.pop('b')`. After that your args is just your kwargs: a dictionary with only k1, k2, and k4 as its keys.

http://stackoverflow.com/q/51489390
tagged with: python
tagged with: image-preprocessing
has answer: http://stackoverflow.com/a/51494847
type: Question
tagged with: keras
score: 0
answer count: 1
has title: Understanding parameters in ImageDataGenerator and flow in Keras
has body: Question 1 Does the rotation_range: Int. Degree range for random rotations refer to the range [0, rotation_range] or [-rotation_range, rotation_range]. If I set rotation_range=40, will my images be randomly rotated between [-40, 40] or [0, 40]? Question 2 Does ImageDataStore.flow randomly generate different augmentations of an input image at every epoch or is a single augmentation generated at the start and used for all epochs. For example, let's say I have some image A that is part of my inputs into the flow method. Is image A augmented only once before training, and this augmented version used for all epochs? Or is image A randomly augmented every epoch? Question 3 When the param shuffle is set to True in the flow method, does this mean the batches are shuffled every epoch, or the images within the batches are shuffled every epoch? For example, lets say our training data consists of 15 images (labeled I1 - I15) is divided into 3 batches/mini-batches before epoch 1 starts (labeled B1, B2, B3). Lets say before epoch 1, the images were assigned to the batches as follows: B1 = {I1, I2, I3, I4, I5} B2 = {I6, I7, I8, I9, I10} B3 = {I11, I12, I13, I14, I15} Now in epoch 1, the batches are trained in the order B1, B2, B3. When epoch 2 starts, will the images in B1, B2, B3 be shuffled so that each batch will not contain the same set of 5 images?
type: UnansweredQuestion

http://stackoverflow.com/comment/116289091
comment on: http://stackoverflow.com/a/55960725
score: 0
type: AnswerComment
has text: I am getting this error when I run this : `CommandNotFoundError: 'az' is misspelled or not recognized by the system.`
type: Comment

http://stackoverflow.com/comment/89972862
type: Comment
type: QuestionComment
score: 1
has text: Good, now the only thing we miss is your attempt. Can yo share what have you tried?
comment on: http://stackoverflow.com/q/51502230

http://stackoverflow.com/q/51529507
has answer: http://stackoverflow.com/a/51529551
has body: so basically, I am creating a program where I grab a list of subreddits from Reddit, and am currently storing them in a txt file. however, I dont know how to count duplicates. So if I run it and there is a name that is already in the file, how do i "add 1" to the value? so it could be like : subone : 1 subtwo : 3 subthree: 2 and so on... here is what i have: class Isduplicate: def read(self): f = open(r'C:\Users\jacka\OneDrive\Documents\outputs.txt', "r") contents = f.read() return contents while counter &lt; len(elem): e = str(elem[counter].get_attribute("href")) e = e.replace("https://www.reddit.com/r/", "") e = e[:-1] if e in Is.read(): text_file.write("duplicate found") else: text_file.write(e + "\n") print(e) counter = counter +2 any general advice is also appreciated!
answer count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90027381
tagged with: python
has comment: http://stackoverflow.com/comment/90027294
tagged with: list
has comment: http://stackoverflow.com/comment/90027308
upvote count: 2
type: UnansweredQuestion
downvote count: 1
type: Question
has title: best way to store a list in python?
has comment: http://stackoverflow.com/comment/90027309

http://stackoverflow.com/a/51610568
score: 0
accepted answer of: http://stackoverflow.com/q/51608408
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90196253
has comment: http://stackoverflow.com/comment/90194956
has body: I'm not sure if this is according to best practices but this seems to work. As a pure python user, I have to say this feels like hocus pocus. I took me a while but I figured it out by looking at the definition of the protobuf files and this documentation. import tensorflow as tf import numpy as np from tensorflow_serving.apis import classification_pb2, input_pb2 image = np.random.rand(1, 32,32,3) def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) request = classification_pb2.ClassificationRequest() request.model_spec.name = 'model' request.model_spec.signature_name = 'classification_results' # Wrap numpy image in an example protobuf example = tf.train.Example(features=tf.train.Features(feature={'image': _bytes_feature(image.tostring())})) inp = input_pb2.Input() inp.example_list.examples.extend([example]) request.input.CopyFrom(inp)
type: Answer
has comment: http://stackoverflow.com/comment/90186376
has comment: http://stackoverflow.com/comment/90194251
has comment: http://stackoverflow.com/comment/90196045
answers question: http://stackoverflow.com/q/51608408
has comment: http://stackoverflow.com/comment/90195796

http://stackoverflow.com/a/67282561
type: Answer
answers question: http://stackoverflow.com/q/51534667
has body: Another surprising case: I was getting error of the same flavour, namely mismatched input 'from' expecting <EOF>. My query contained a parameter and I forgot to resolve it (please note the initial f is missing): # failing query my_qry = """ create table my_tab as select columns from source_tab where somecolumn < {parameter} """ spark.sql(qry_defaults).collect() So the solution was to resolve the parameters properly (mind the initial f): # correct query my_qry = f""" create table my_tab as select columns from source_tab where somecolumn < {parameter} """ spark.sql(qry_defaults).collect() To summarise, in my case the error had nothing to do with the missing EOF. I hope someone finds this helpful.
has comment: http://stackoverflow.com/comment/121200135
score: 0

http://stackoverflow.com/a/51607641
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51607143
has body: Maybe you could use the pickle module to save the parameters from the 2.7 script and then load the pickle object in the 3.7 script. https://docs.python.org/3/library/pickle.html

http://stackoverflow.com/comment/114209126
has text: hello. could you let me know how to use it in fit_generator()?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/55892107

http://stackoverflow.com/comment/89934613
type: QuestionComment
score: 0
has text: `save` return user, you should check that to ensure that it's returning correctly.
comment on: http://stackoverflow.com/q/51482832
type: Comment

http://stackoverflow.com/comment/89983317
comment on: http://stackoverflow.com/q/51506944
has text: @Ajax1234 : Yes, I made a mistake there. Thank you.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90128665
comment on: http://stackoverflow.com/q/51580689
score: 0
type: Comment
type: QuestionComment
has text: The package you are referring to does not currently provide that kind of functionality. It only works properly (most of the times, see github issue list) if you pass it a string that *only* contains the number word. If the number word is embedded in more text, the rest of the text gets removed.

http://stackoverflow.com/q/51585732
tagged with: dockerpy
has answer: http://stackoverflow.com/a/51598006
score: 1
tagged with: mysql
upvote count: 1
has title: I try to execute into container with exec_run but doesn't work
type: Question
downvote count: 0
answer count: 1
has body: I try to execute 4 commands into a container (it has a mysql database) but if i do it in anothe terminal work, but if a create a container and then execute the commands, it not working. I have this code: this code create the container but dont execute the command 1 ,2 , 3 and 4. import docker from docker.types import Mount from threading import Thread client = docker.DockerClient(base_url='unix://var/run/docker.sock') container= client.containers.run( "python_base_image:v02", detach=True, name='201802750001M04', ports={'3306/tcp': None, '80/tcp': None}, mounts= [Mount("/var/lib/mysql","201802750001M04_backup_db",type='volume')] ) command1 = "sed -i '/bind/s/^/#/g' /etc/mysql/my.cnf" command2 = "mysql --user="root" --password="temprootpass" -- execute="GRANT ALL PRIVILEGES ON . TO 'macripco'@'172.17.0.1' IDENTIFIED BY '12345';"" command3 = "mysql --user="root" --password="temprootpass" -- execute="GRANT ALL PRIVILEGES ON . TO 'macripco'@'localhost' IDENTIFIED BY '12345';"" command4 = "sudo /etc/init.d/mysql restart" a = container.exec_run(command1,detach=False,stream=True,stderr=True, stdout=True) b = container.exec_run(command2,detach=False,stream=True,stderr=True, stdout=True) c = container.exec_run(command3,detach=False,stream=True,stderr=True, stdout=True) d = container.exec_run(command4,detach=False,stream=True,stderr=True, stdout=True)` But if i execute the commands later(in another terminal), once the container has been created, that work. I need create and execute the commands together. Thanks.
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90134732
type: QuestionComment
has text: Sorry, didn't realize there wasn't a question in there. How would I go about seeing and/or changing the neighboring cells?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51584574

http://stackoverflow.com/q/51631063
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51631323
type: Question
accepted answer: http://stackoverflow.com/a/51631323
has body: I have a dataframe (similar below) that I'm trying to deal with. | user | weight | height | timestamp | | ------ | ----- |------ |---------------------------------| | user 1 | NA | 180 | 2017-11-09 17:21:49.025259+00:00| | user 1 | 90 | NA | 2017-11-09 17:21:49.025259+00:00| | user 1 | 89 | NA | 2017-11-10 17:21:49.025259+00:00| | user 1 | 88 | NA | 2017-11-11 17:21:49.025259+00:00| | user 2 | NA | 175 | 2017-11-09 17:21:49.025259+00:00| | user 2 | 95 | NA | 2017-11-09 17:21:49.025259+00:00| | user 3 | NA | 170 | 2017-12-09 17:21:49.025259+00:00| | user 4 | 70 | NA | 2017-08-09 17:21:49.025259+00:00| My end goal is to calculate the BMI of each user, using the latest timestamp data of each weight and height. Some users only have one datum, many have more than one of weight, height, or both. Since the data are in kg and cm the BMI would be BMI = (Weight in Kilograms x 10,000)/((Height in centimeters)^2) I am hoping to return something like the following. (a dictionary would be sufficient as well) | user | BMI | | ------ | ------------------| | user 1 | 27.1604938272 | | user 2 | 31.0204081633 | | user 3 | NA | | user 4 | NA |
has title: Grouping multiple user data with multiple timestamps
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/q/51600367
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/51602765
score: 5
tagged with: python
tagged with: generator
has comment: http://stackoverflow.com/comment/90170916
answer count: 3
linked to: http://stackoverflow.com/q/47240184
tagged with: iterator
has comment: http://stackoverflow.com/comment/90167680
upvote count: 5
downvote count: 0
has answer: http://stackoverflow.com/a/51623477
type: UnansweredQuestion
has title: Creating a Python generator that yields ordered products of integers from two large lists
has comment: http://stackoverflow.com/comment/90167153
has answer: http://stackoverflow.com/a/51600426
has comment: http://stackoverflow.com/comment/90167012
has body: So, I have two very large lists of numbers l1 and l2. I'd like to multiply each element of l1 with each element of l2 without explictly creating a new list of products. Thus, I'd like a generator. This part is easy. I can just do something like for a in l1: for b in l2: yield a * b However, I also need these products to be ordered by their magnitude. I am wondering if there is some clever trick to order the yield statements so that this can also be done with a generator. In Python 3, if possible. Thanks.
favorite count: 0
has comment: http://stackoverflow.com/comment/90166931

http://stackoverflow.com/a/51499120
type: Answer
has body: You may try to wait for it using Explicit Wait, wait = WebDriverWait(driver, 10) wait.until(EC.element_to_be_clickable(By.XPATH, "//span[contains(text(),'Berlin')]")).click() Click event by Javascript Function: driver.execute_script("arguments[0].click()", ElementToClick)
score: 0
has comment: http://stackoverflow.com/comment/89991008
answers question: http://stackoverflow.com/q/51493599

http://stackoverflow.com/comment/90177409
type: Comment
type: QuestionComment
has text: and you want to get this id back?
comment on: http://stackoverflow.com/q/51605708
score: 0

http://stackoverflow.com/q/51500338
accepted answer: http://stackoverflow.com/a/51507607
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/89982323
has title: Python Create Tables and save as CSV and show 1st row contents
tagged with: python
has answer: http://stackoverflow.com/a/51507607
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89980518
score: 0
has body: I have this function code: def make_dash_table(df): table = [] for index, row in df.iterrows(): html_row = [] for i in range(len(row)): html_row.append(html.Td([row[i]])) table.append(html.Tr(html_row)) return table that creates a table for Dash Framework (Python) but it doesn't show the header (first .csv row) when I call it on Python. For some Tables, it is customized to show subtitles as below: modifed_perf_table.insert( 0, html.Tr([ html.Td([]), html.Td(['Cumulative'], colSpan=4, style={'text-align': "center"}), html.Td(['Annualised'], colSpan=4, style={'text-align': "center"}) ], style={'background': 'white', 'font-weight': '600'} ) ) But I want to let the table show the csv headers (first row). Where I need to change: is on this code or CSS? Full code below: df_perf_summary = pd.read_csv('17530.csv', encoding='latin-1') df_perf_summary.head() def make_dash_table(df): table = [] for index, row in df.iterrows(): html_row = [] for i in range(len(row)): html_row.append(html.Td([row[i]])) table.append(html.Tr(html_row)) return table modifed_perf_table = make_dash_table(df_perf_summary) modifed_perf_table.insert( 0, html.Tr([ html.Td([]), html.Td(['Cumulative'], colSpan=4, style={'text-align': "center"}), html.Td(['Annualised'], colSpan=4, style={'text-align': "center"}) ], style={'background': 'white', 'font-weight': '600'} ) ) html.Div([ html.Div([ html.Div([ html.H6("#####", className="gs-header gs-table-header padded"), html.Table(modifed_perf_table, className="reversed"), ], className="eight columns"), ], className="row "), external_css = ["https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css", "https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css", "//fonts.googleapis.com/css?family=Raleway:400,300,600", "https://cdn.rawgit.com/plotly/dash-app-stylesheets/5047eb29e4afe01b45b27b1d2f7deda2a942311a/goldman-sachs-report.css", "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"] csv as follow, save it …
has comment: http://stackoverflow.com/comment/89977588
type: Question
tagged with: plotly-dash

http://stackoverflow.com/a/51500979
has comment: http://stackoverflow.com/comment/89973755
answers question: http://stackoverflow.com/q/51496038
has comment: http://stackoverflow.com/comment/89973348
score: 0
has body: I see you have included a C# tag, so I will give you a solution in C#. If you need a solution in Python I can't help you, but you made it sound as if you didn't care, so here is my best effort. I don't know what your XAML looks like, so I can only give you a rough implementation, but you should be able to implement this easily. Here is the XAML: &lt;Grid&gt; &lt;ComboBox Name="ComboBox1" SelectionChanged="ComboBox1_SelectionChanged" Height="50" Width="Auto"&gt; &lt;ComboBoxItem Name="GreenOption" Content="Green"/&gt; &lt;ComboBoxItem Name="BlueOption" Content="Blue"/&gt; &lt;ComboBoxItem Name="PinkOption" Content="Pink"/&gt; &lt;ComboBoxItem Name="RedOption" Content="Red"/&gt; &lt;/ComboBox&gt; &lt;/Grid&gt; Again, that should be replaced with whatever you happen to have, this is just an example. Here is the C#: using System.Windows.Media; /*The rest of your code goes here*/ private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) { var foo = sender as ComboBox; var bar = foo.SelectedItem as ComboBoxItem; switch (bar.Name) { case "GreenOption": foo.Background = Brushes.Green; break; case "PinkOption": foo.Background = Brushes.Pink; break; case "RedOption": foo.Background = Brushes.Red; break; case "BlueOption": foo.Background = Brushes.Blue; break; } } /* Or Here */ It's very possible that there are more elegant solutions, and I don't know how it would be done in Python, but the basic principle should be the same. Make sure you remember the using System.Windows.Media; directive, and this should work like a charm.
type: Answer

http://stackoverflow.com/comment/89939734
comment on: http://stackoverflow.com/q/51485285
score: 0
type: Comment
has text: Where are you running this code?
type: QuestionComment

http://stackoverflow.com/comment/90182018
has text: Thanks for your kindly answer and details about regex!
comment on: http://stackoverflow.com/a/51608457
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90076352
type: Comment
comment on: http://stackoverflow.com/a/51552503
type: AnswerComment
has text: try to print articles before return
score: 0

http://stackoverflow.com/comment/90025017
score: 0
type: Comment
has text: @Anthony sorry, this is just wording difference - you are correct, but it is not `pipelines.py` that is executed, what is executed is the pipelines you defined. They can be defined anywhere and registered in the framework. Usually you define them in `pipelines.py` but nothing forces you to define them there.
comment on: http://stackoverflow.com/a/51527494
type: AnswerComment

http://stackoverflow.com/q/51606276
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90218100
tagged with: python
tagged with: sha
tagged with: php
has body: I create an HMAC in Node like below: const check = crypto.createHmac("sha1", "mysecret"); check.update(JSON.stringify("mybody")); const digest = check.digest("hex"); Then I create the HMAC in PHP: hash_hmac("sha1","mybody","mysecret") Then I create the HMAC in Python 3 key = bytes("mysecret", 'utf-8') message = bytes("mybody", 'utf-8') digester = hmac.new(key, message, hashlib.sha1).hexdigest(): Then HMAC from Node and PHP match, no issues. But the HMAC from Python is always different and I cant figure out why. Any help will be appreciated.
tagged with: hmac
has comment: http://stackoverflow.com/comment/90177927
type: Question
has comment: http://stackoverflow.com/comment/90177986
score: 0
linked to: http://stackoverflow.com/q/31919154
has title: hmac in python not matching hmac in PHP and node

http://stackoverflow.com/a/51573120
score: 3
has body: You should have third intermediate table which will have following columns: id (primary) author id (from Authors table) book id (from Books table) This way you will be able to create a record which will map 1 author to 1 book. So you can have following records: 1 ... Author1ID ... Book1ID 2 ... Author1ID ... Book2ID 3 ... Author2ID ... Book2ID AuthorXID and BookXID - foreign keys from corresponding tables. So Book2 has 2 authors, Author1 has 2 books. Also separate tables for Books and Authors don't need to contain any info about anything except itself. Authors .. 1---Many .. BOOKSFORAUTHORS .. Many---1 .. Books
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51572979
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51572979

http://stackoverflow.com/q/51623878
has comment: http://stackoverflow.com/comment/90215500
tagged with: django
has comment: http://stackoverflow.com/comment/90212954
has comment: http://stackoverflow.com/comment/90215390
has comment: http://stackoverflow.com/comment/90215249
has body: This generates a request and passes it to my view factory = APIRequestFactory() body = {'satellite': 'sat', 'groundStation': 'groundA'} request = factory.post('/accesses', body) response = view(request) When the view function receives the request, request.data contains {'satellite': 'sat', 'ground_station': 'ground_a'} The keys and there values have been reformatted. I'm trying to keep app this consistent with an API some other services are familiar with. How do I turn off this reformatting?
tagged with: http://stackoverflow.com/tag/json
has title: Django APIRequestFactory converting CamelCase JSON keys and values to underscore_formatting
type: Question
answer count: 1
tagged with: django-rest-framework
tagged with: python
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51626301

http://stackoverflow.com/q/51583624
tagged with: ansible
linked to: http://stackoverflow.com/q/13069634
has body: I have a systemd service that I deploy and want to be started by Ansible. My systemd service unit file is this: [Unit] Description=Collector service After=network.target mariadb.service Requires=mariadb.service [Service] Type=simple ExecStart=/opt/collector/app.py WorkingDirectory=/opt/collector Restart=on-abort User=root [Install] WantedBy=multi-user.target I am using Type=simple since this looks like the correct solution (also the preferred one in this Question). I tried using Type=oneshot as well (as suggested by the initial user making this question as duplicate of this question) but the problem is that the /opt/collector/app.py script is a long running process: while True: t = threading.Thread(...) t.start() t.join() time.sleep(15) and with Type=oneshot, Ansible will block forever. And my Ansible starting code is: - name: start Collector service systemd: name: collector state: started enabled: yes On the target system, systemctl will display: [root@srv01 /]# systemctl UNIT LOAD ACTIVE SUB DESCRIPTION dev-sda1.device loaded activating tentative /dev/sda1 -.mount loaded active mounted / dev-mqueue.mount loaded active mounted POSIX Message Queue File System etc-hostname.mount loaded active mounted /etc/hostname etc-hosts.mount loaded active mounted /etc/hosts etc-resolv.conf.mount loaded active mounted /etc/resolv.conf run-user-0.mount loaded active mounted /run/user/0 session-73.scope loaded active running Session 73 of user root crond.service loaded active running Command Scheduler dbus.service loaded active running D-Bus System Message Bus haproxy.service loaded active running HAProxy Load Balancer &lt;E2&gt;&lt;97&gt;&lt;8F&gt; collector.service loaded failed failed Collector service .... The service fails because of the Python process exception (using un undefined variable). But my Ansible playbook run does not fail: TASK [inventory : start Collector service] ********************************* changed: [srv01] I tried with both systemd and service Ansible modu…
upvote count: 10
downvote count: 1
has answer: http://stackoverflow.com/a/57380779
has title: How can I make Ansible fail when the systemd service fails to start?
has answer: http://stackoverflow.com/a/57364115
tagged with: service
favorite count: 0
tagged with: daemon
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/132188098
tagged with: python
linked to: http://stackoverflow.com/q/39032100
tagged with: systemd
has comment: http://stackoverflow.com/comment/90142429
type: Question
has comment: http://stackoverflow.com/comment/90134762
score: 9
has comment: http://stackoverflow.com/comment/90142557
has comment: http://stackoverflow.com/comment/90141265
answer count: 2
has comment: http://stackoverflow.com/comment/90159924

http://stackoverflow.com/comment/89985445
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51507836
has text: Anaconda3 is just a directory that I specified for anaconda2. Because once it gave an error, the second time I tried to install in anaconda2 directory, I got warning: this directory exists and I can't install it here.

http://stackoverflow.com/comment/90224626
type: Comment
has text: Ya. The python2 code is quite bulky. plus it has used opencv2.4 which is I guess only supported by python2. It will be more comfortable if I take 3 part 2. Currently, i am working on that. If that doesn't work out, I guess that I have to go the other way. (I cannot live with the code with poor performance)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51630114

http://stackoverflow.com/comment/90091449
type: QuestionComment
comment on: http://stackoverflow.com/q/51562302
score: 4
has text: You never want to invert a matrix. Very very rarely. `inv` is a bad choice. Just use `A\b` instead of `inv(A)*b`. This happens because you have a badly conditioned matrix.
type: Comment

http://stackoverflow.com/q/51499676
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/89967787
has title: unable to load variable back from pickled file
has comment: http://stackoverflow.com/comment/89968089
has comment: http://stackoverflow.com/comment/89968112
type: Question
has comment: http://stackoverflow.com/comment/89967656
score: 0
has comment: http://stackoverflow.com/comment/89967989
has body: import pickle myDictOne = { "Key1": "Value1", "Key2": "Value2", "Key3": "Value3" } myMovieTuple = ( "DDLJ", "SRK", "1993", ( (1, "Zara sa jhoom lu main"), (2, "Na jane mere "), (3, "Ghar a ja pardesi"), (4, "Mehdi laga ke rakhna") ) ) myList = ["One", 3.5, 7, "two"] with open('VariblesFile.pickle', 'wb') as myPickleFile: pickle.dump(myDictOne, myPickleFile) pickle.dump(myMovieTuple, myPickleFile) pickle.dump(myList, myPickleFile) with open('VariblesFile.pickle', 'rb') as myPickled_File: myNewDictOne = pickle.load(myPickled_File) myNewMovieTuple = pickle.load(myPickled_File) myNewList = pickle.load(myPickled_File) print(myNewDictOne) for i in myNewMovieTuple: for j in i: print(j) print(myNewList) I am getting below mentioned error message if i execute this program. Basically pickle file get created , but when i try to load back variables ,That is not working....Please help Traceback (most recent call last): None File "E:/myNewPythonDir/CompletePythonDeveloperCourse/Module10/myOwnPickle.py", line 32, in &lt;module&gt; for i in myNewMovieTuple: TypeError: 'NoneType' object is not iterable Process finished with exit code 1
tagged with: serialization
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51488486
has title: Can I retrieve Twitter Card headline and media URLs?
linked to: http://stackoverflow.com/q/21188683
tagged with: twitter
tagged with: web-scraping
type: Question
has body: I want to collect all Twitter card headlines and urls from my tweets for a project. For example, for this tweet: https://twitter.com/WSJ/status/1021517076069056514, I would want to retrieve the following information: Headline: "Global Central Bank Chatter Rattles Bond Market" Image Link: "https://pbs.twimg.com/card_img/1021513789722841093/LQWGa8uL?format=jpg&amp;name=600x314" Right now, I'm getting this information by going to the tweet and inspecting the card, but I'd like to do this for code and iterate through my tweets. Does anyone know how to get this information programmatically? Would really appreciate it!
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/89987884
favorite count: 0
has answer: http://stackoverflow.com/a/51509356
tagged with: twitter-card
tagged with: tweets
type: UnansweredQuestion
tagged with: python
score: 2

http://stackoverflow.com/comment/90011162
type: QuestionComment
score: 1
has text: use instead of "\n"... that is HTML tag for a line break
comment on: http://stackoverflow.com/q/51521111
type: Comment

http://stackoverflow.com/q/51562033
tagged with: sql
upvote count: 0
has answer: http://stackoverflow.com/a/71624145
has comment: http://stackoverflow.com/comment/90092893
has title: Python Script for SQL Server - Update values with MERGE
favorite count: 0
has body: I have this python function which inserts to a SQL database. The script is such that every time it is rerun it will have to insert the same row over again in addition to new rows. Eventually I will be changing this so that it only inserts new rows but for now I have to work with some sort of update statement. I'm aware that I can use MERGE in SQL Server to achieve something similar to MySQL's ON DUPLICATE KEY UPDATE, but I'm not exactly sure how it should be used. Any advice is welcome. Thanks! def sqlInsrt(headers, values): #create string input of mylisth strheaders = ','.join(str(i) for i in headers) #create string ? param's for INSERT clause placestr = ','.join(i for i in ["?" for i in headers]) #create string ? param's for UPDATE clause replacestr = ', '.join(['{}=?'.format(h) for h in headers]) #Setup and execute SQL query insert = ("INSERT INTO "+part+" ("+strheaders+") VALUES ("+placestr+")") cursor.execute(insert, values) cnx.commit()
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51571916
has comment: http://stackoverflow.com/comment/90092756
tagged with: python
has comment: http://stackoverflow.com/comment/90091645
tagged with: sql-merge
has comment: http://stackoverflow.com/comment/90091743
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/79428479
score: -1
has comment: http://stackoverflow.com/comment/90090998
answer count: 3

http://stackoverflow.com/comment/90088678
type: Comment
comment on: http://stackoverflow.com/a/51560556
has text: I was able to add the convolutions to __init__. I'll see if the error goes away
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90218611
comment on: http://stackoverflow.com/q/51624496
has text: @EamonnMcEvoy Actually some part had been missed when changed to the binary image, because the missing parts' RGB is very similar with the background(gray), methods could not identify then even I used HSV.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89953524
type: Comment
type: AnswerComment
has text: I have to update this - ,header=None, encoding='iso-8859-1',quoting=csv.QUOTE_NONE
comment on: http://stackoverflow.com/a/51492296
score: 0

http://stackoverflow.com/a/51515089
upvote count: 1
has body: Below is a functional solution using collections.defaultdict. Depending on your use case you may not need to instantiate children dictionaries manually. You can just use a nested defaultdict. from collections import defaultdict from operator import getitem from functools import reduce tree = lambda: defaultdict(tree) d = tree() def setDictKeys(dataDict, atKey, keysList): reduce(getitem, atKey, dataDict).update({i: {} for i in keysList}) setDictKeys(d, ['a', 'b'], [1, 2, 3]) print(d) defaultdict({'a': defaultdict({'b': defaultdict({1: {}, 2: {}, 3: {}})})})
downvote count: 0
answers question: http://stackoverflow.com/q/51514098
type: Answer
score: 1

http://stackoverflow.com/a/51628884
has comment: http://stackoverflow.com/comment/90225074
score: 0
answers question: http://stackoverflow.com/q/51628514
has comment: http://stackoverflow.com/comment/90224590
has comment: http://stackoverflow.com/comment/90226515
has body: I think I would go for this solution! def set_labels_text(fn, ft, t=None, a=None, i=None, reset=False): at = None it = None tt = None if reset: it = 'bla bla 3 %s' % i else: at = 'bla bla 2 %s' % a tt = 'bla bla 1 %s' % t; if ft == 1 get_component('template' + ft).get_component(fn + 'Label1').text = tt or '' get_component('template' + ft).get_component(fn + 'Label2').text = at or '' else: get_component('template' + ft).get_component(fn + 'Label3').text = it or ''
type: Answer
has comment: http://stackoverflow.com/comment/90226200
has comment: http://stackoverflow.com/comment/90227096

http://stackoverflow.com/a/51621764
downvote count: 0
score: 1
type: Answer
has body: Try: doc = [] for i in range(1,5): with open('0000{}.xml'.format(i)) as fd: doc.append(xmltodict.parse(fd.read())) def panda_maker (xml_dict): logData_list = [] for xmlval in xml_dict: channel_list = xmlval['logs']['log']['logData']['mnemonicList'].split(",") temp = [i.split(",") for i in xml_dict ['logs']['log']['logData']['data']] temp.insert(0, xml_dict ['logs']['log']['logData']['unitList'].split(",")) logData_list.extend(temp) return pd.DataFrame(np.array(logData_list).reshape(len(logData_list),len(channel_list)), columns = channel_list) logData_frame_01 = panda_maker(doc) logData_frame_01.head() #all good
upvote count: 1
has comment: http://stackoverflow.com/comment/90209667
accepted answer of: http://stackoverflow.com/q/51621579
answers question: http://stackoverflow.com/q/51621579
type: AcceptedAnswer

http://stackoverflow.com/comment/119328244
comment on: http://stackoverflow.com/a/51716763
score: 0
type: Comment
has text: @abhiieor check out the output of `pipenv graph` in the question - the first two are versions of direct dependencies, the last two are conflicting versions of the same transient dependency. Overall, this answer may be obsolete, I don't use `pipenv` anymore.
type: AnswerComment

http://stackoverflow.com/comment/90258069
type: Comment
type: AnswerComment
has text: Thanks! I created a python executable to run the php commands to host the server and it's working perfectly! I can't quite figure out how to serve files on the empty url though... (http://localhost:8080/)
score: 0
comment on: http://stackoverflow.com/a/51636351

http://stackoverflow.com/a/51582583
has body: Your code works fine for me. The problem is at the end of file (EOF). Verify the last element of your mylist mylist = ['[1,2,3,4,5]', '[4,47,6,7,3,9]'] my_new_list = [] for item in mylist: new_item = eval(item) my_new_list.append(new_item) print (my_new_list) Answer: [[1, 2, 3, 4, 5], [4, 47, 6, 7, 3, 9]]
answers question: http://stackoverflow.com/q/51582546
downvote count: 0
type: AcceptedAnswer
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51582546
has comment: http://stackoverflow.com/comment/90130562
score: 1

http://stackoverflow.com/q/51506378
tagged with: recursion
answer count: 0
has comment: http://stackoverflow.com/comment/89984175
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/21805047
has comment: http://stackoverflow.com/comment/90012940
upvote count: 1
has body: I want to build a QTreeWidget with a JSON file that contains several family generational levels, using recursion. Here is my code: import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5 import QtWidgets from PyQt5 import QtCore import json #read in JSON family structure def readJsonData(fileName): with open(fileName) as json_data: treeData = json.load( json_data ) return treeData fileName = 'family.json' d = readJsonData(fileName) myList = [] def myprint( d, myList ): for k, v in d.items(): if isinstance(v, dict): myprint(v, myList ) myList.append(k) else: myList.append(k) return myList a = myprint(d, myList ) class MyMainWindow(QMainWindow): def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) self.tree = QTreeWidget(self) self.tree.setSelectionMode(QAbstractItemView.SingleSelection) editKey = QShortcut(QKeySequence(Qt.Key_Return), self.tree) self.setCentralWidget(self.tree) self.tree.setHeaderLabel('Tree') i = QTreeWidgetItem(self.tree, [a[len(a)-1]]) a.pop() self.tree.addTopLevelItem(i) for x in a: QTreeWidgetItem(i, ['{}'.format(x)]) if __name__ == "__main__": app = QApplication(sys.argv) ui = MyMainWindow() ui.show() sys.exit(app.exec_()) This creates a family tree with root mainMenu and members as: ['grandChild12', 'grandChild11', 'Child1', 'grandChild21', 'grandChild22', 'Child2', 'grandChild31', 'grandChild32', 'Child3'] But, the result should be nested like the JSON file structure: 'mainMenu': 'Child1' 'grandChild11' 'grandChild12' 'Child2' 'grandChild21' 'grandChild22' 'Child3' 'grandChild31' 'grandChild32' How do I adapt the line: for x in a: QTreeWidgetItem(i, ['{}'.format(x)]) to create the correct structure with recursion? I've done this before in Java, so I know it can be done by walking up a limb to a node and down to a terminal leaf, either from left or center or right of the main stem. The JSON file is presented below: { "mainMenu": { "Child1": { "grandChild11": "None", "grand…
downvote count: 1
type: Question
has title: PyQt: recursively adding children to TreeWidget dynamically
has comment: http://stackoverflow.com/comment/90012881
score: 0
tagged with: qtreewidget
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90012954
has comment: http://stackoverflow.com/comment/90017950
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51538662
has comment: http://stackoverflow.com/comment/90045090
has body: You need a better algorithm than trial division to factor numbers the size you are working with. A simple step up from trial division is John Pollard's rho algorithm: Python 2.7.13 (default, Mar 13 2017, 20:56:15) [GCC 5.4.0] on cygwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; def isPrime(n, k=5): # miller-rabin ... from random import randint ... if n &lt; 2: return False ... for p in [2,3,5,7,11,13,17,19,23,29]: ... if n % p == 0: return n == p ... s, d = 0, n-1 ... while d % 2 == 0: ... s, d = s+1, d/2 ... for i in range(k): ... x = pow(randint(2, n-1), d, n) ... if x == 1 or x == n-1: continue ... for r in range(1, s): ... x = (x * x) % n ... if x == 1: return False ... if x == n-1: break ... else: return False ... return True ... &gt;&gt;&gt; def factors(n, b2=-1, b1=10000): # 2,3,5-wheel, then rho ... def gcd(a,b): # euclid's algorithm ... if b == 0: return a ... return gcd(b, a%b) ... def insertSorted(x, xs): # linear search ... i, ln = 0, len(xs) ... while i &lt; ln and xs[i] &lt; x: i += 1 ... xs.insert(i,x) ... return xs ... if -1 &lt;= n &lt;= 1: return [n] ... if n &lt; -1: return [-1] + factors(-n) ... wheel = [1,2,2,4,2,4,2,4,6,2,6] ... w, f, fs = 0, 2, [] ... while f*f &lt;= n and f &lt; b1: ... while n % f == 0: ... fs.append(f) ... n /= f ... f, w = f + wheel[w], w+1 ... if w == 11: w = 3 ... if n == 1: return fs ... h, t, g, c = 1, 1, 1, 1 ... while not isPrime(n): ... while b2 &lt;&gt; 0 and g == 1: ... h = (h*h+c)%n # the hare runs ... h = (h*h+c)%n # twice as fast ... t = (t*t+c)%n # as the tortoise ... g = gcd(t-h, n); b2 -= 1 ... if b2 == 0: return fs ... if isPrime(g): ... while n % g == 0: ... fs = insertSorted(g, fs) ... n /= g ... h, t, g, c = 1, 1, 1, c+1 ... return insertSorted(n, fs) ... &gt;&gt;&gt; factors(1917141215419419171412154194191714) [2, 3, 13, 449941L, 54626569996995593878495243L] The factorization is returned immediately. See here for an explanation of how it works. To factor even lar…
has comment: http://stackoverflow.com/comment/90045781
has comment: http://stackoverflow.com/comment/90045405
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51533621
answers question: http://stackoverflow.com/q/51533621
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/128272852

http://stackoverflow.com/q/51634824
score: 0
has comment: http://stackoverflow.com/comment/90233957
has title: My python code is not importing JSON data correctly to CSV
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51635061
has answer: http://stackoverflow.com/a/51635066
tagged with: http://stackoverflow.com/tag/json
type: Question
tagged with: export-to-csv
answer count: 2
has body: So i am trying to import json data from file and want to export in CSV file. Only few tags like "authors" and "title" work fine with this code but when i try that for "abstract" it split every word of abstract in new column of csv. Before I try split() it was doing the same for every character here is my code import json import csv filename="abc.json" csv_file= open('my.csv', 'w',encoding="utf-8") csvwriter = csv.writer(csv_file) with open(filename, 'r') as f: for line in f: data = json.loads(line) if 'abstract' in data: csvwriter.writerow(data['abstract'].split()) elif 'authors' in data: csvwriter.writerow(data['authors']) else: f="my" sample json file can be downloaded from here http://s000.tinyupload.com/?file_id=28925213311182593120

http://stackoverflow.com/comment/90035676
comment on: http://stackoverflow.com/q/51530507
type: Comment
type: QuestionComment
score: 1
has text: You need to add condition of not false for day before calling weekday().

http://stackoverflow.com/comment/90239353
comment on: http://stackoverflow.com/q/51637374
score: 0
type: Comment
type: QuestionComment
has text: do you want to choose which method name you call?

http://stackoverflow.com/comment/90003104
comment on: http://stackoverflow.com/q/51516978
score: 0
type: Comment
type: QuestionComment
has text: Yes Yogesh, in this example

http://stackoverflow.com/a/51519916
has body: As per the HTML you have shared the &lt;ul&gt; tag contains a lot of JavaScripts so to invoke click() on the desired element you have to induce WebDriverWait for the element to be clickable and you can use either of the following solutions: CSS_SELECTOR: WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ul.delivery-method li.courierDelivery.selectDeliveryWay input[value='Courier']"))).click() XPATH: WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='delivery-method']//li[@class='courierDelivery selectDeliveryWay']//input[@value='Courier']"))).click()
type: Answer
has comment: http://stackoverflow.com/comment/90008840
answers question: http://stackoverflow.com/q/51519601
has comment: http://stackoverflow.com/comment/90008789
score: 0

http://stackoverflow.com/comment/90161924
comment on: http://stackoverflow.com/q/51597936
type: Comment
type: QuestionComment
has text: `ans` is an `int`, yet you call it as if it were a function: `ans(ans+1)`. May be you meant to multiply here: `ans * (ans+1)`
score: 1

http://stackoverflow.com/q/51609519
tagged with: python
answer count: 4
downvote count: 4
has answer: http://stackoverflow.com/a/51609630
has answer: http://stackoverflow.com/a/51609685
has body: I have a list of 1000 elements. Now I need to delete the 1st, 2nd, 4th, 8th, 16th, 32nd, etc element from that list. Here's my solution i = 0 while pow(2,i) &lt; len(arr): del arr[pow(2,i) - 1 - i] i += 1 But I think it seems like some bad code. Is there more elegant way to get the same result?
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51609938
score: -2
has title: Better way to delete every n-th element from list
has comment: http://stackoverflow.com/comment/90184129
has answer: http://stackoverflow.com/a/51609733
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/51698475
has body: You would probably want to create the figure to plot to external of the xgboost plotting function. This would allow you to set the size to whatever you like. fig, ax = plt.subplots(figsize=(10,8)) plot_importance(model, ax=ax) Alternatively you can let the plotting function create the figure as you have it and later change its size. ax = plot_importance(model) ax.figure.set_size_inches(10,8)
type: AcceptedAnswer
downvote count: 0
score: 7
accepted answer of: http://stackoverflow.com/q/51546340
answers question: http://stackoverflow.com/q/51546340
type: Answer
upvote count: 7

http://stackoverflow.com/comment/90046382
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51538832
type: Comment
has text: Your code doesn't seem to do what I want. It does not detach from terminal. Doing stdout=subprocess.PIPE does detach from terminal, but it opens in the browser and not in the pdf-viewer.

azure-iot-hub
type: Tag
tags question: http://stackoverflow.com/q/51488457
tag name: azure-iot-hub

http://stackoverflow.com/q/51622197
has body: So after utilizing pyinstxtractor to get the PYC file, adding a magic number to the beggining of said file (it took hours to get to this point...) and finally trying to decompile it using Uncompyle6, I recieve the following error: "C code is Python 1.0 - 1.2; can't handle yet" I have no idea how to proceed... help
type: Question
answer count: 1
score: 0
tagged with: python
has title: Error when decompiling utilizing Uncompyle6
has answer: http://stackoverflow.com/a/52229276
type: UnansweredQuestion
tagged with: reverse-engineering
tagged with: decompiler

qtreeview
tags question: http://stackoverflow.com/q/51586200
type: Tag
tag name: qtreeview
tags question: http://stackoverflow.com/q/51549271

http://stackoverflow.com/a/51611162
downvote count: 0
answers question: http://stackoverflow.com/q/51606234
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/51606234
has body: Position the table outside the axes You may use loc="right" to position the table right of the axes. Something like fig.subplots_adjust(right=0.8) will leave enough space for it. import matplotlib.pyplot as plt import matplotlib as mpl plt.style.use('ggplot') fig, ax = plt.subplots(figsize = (10,6)) fig.subplots_adjust(right=0.8) ax.axis('equal') ax.grid(False) xy = 0,0 circle = mpl.patches.Circle(xy, 160, lw = 3, edgecolor = 'black', facecolor = 'b', alpha = 0.1, zorder = 5) ax.add_patch(circle) col_labels=['A','B','C','D','E'] row_labels=['diff','total'] table_vals=[['','','','',''],['','','','','']] the_table = plt.table(cellText=table_vals, colWidths = [0.05]*5, rowLabels=row_labels, colLabels=col_labels, loc='right', zorder=3) ax.autoscale() plt.show() Put the table in its own axes You may put the table in a new axes next to the existing one. The advantage is that there is no need to then play with the column width or subplot parameters. import matplotlib.pyplot as plt import matplotlib as mpl plt.style.use('ggplot') fig, (ax, ax_table) = plt.subplots(ncols=2, figsize = (10,6), gridspec_kw=dict(width_ratios=[3,1])) ax.axis('equal') ax_table.axis("off") ax.grid(False) xy = 0,0 circle = mpl.patches.Circle(xy, 160, lw = 3, edgecolor = 'black', facecolor = 'b', alpha = 0.1, zorder = 5) ax.add_patch(circle) col_labels=['A','B','C','D','E'] row_labels=['diff','total'] table_vals=[['','','','',''],['','','','','']] the_table = ax_table.table(cellText=table_vals, rowLabels=row_labels, colLabels=col_labels, loc='center') ax.autoscale() plt.show()
upvote count: 3
has comment: http://stackoverflow.com/comment/90251830
type: AcceptedAnswer

http://stackoverflow.com/comment/90238672
has text: `**` isn't really a wrapper for the `pow()` function. The builtin `pow()` function [calls `PyNumber_Power()`](https://github.com/python/cpython/blob/cfc8831f5ed607048679427f7d76d6cb4f8a2e8a/Python/bltinmodule.c#L1838) and [`**` is translated to bytecode `BINARY_POWER`](https://stackoverflow.com/a/354626/1322401) and evaluated as a call to `PyNumber_Power()`. So yes, `PyNumber_Power()` is slower than simple multiplication, but the call doesn't go `**` => `pow()` => `PyNumberPower()`.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51625533
type: AnswerComment

http://stackoverflow.com/a/51633973
type: Answer
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51620641
score: 0
has body: This is an example to add an attachment with text/html conent. import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders message = MIMEMultipart() # add text message.attach( MIMEText( content, 'html', 'utf-8' ) ) # add attachment attachment = MIMEBase('application', "octet-stream") # open a file to attach attachment.set_payload(open(filepath, "rb").read()) encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % self.filename ) message.attach(attachment) server.sendmail(SENDER, receivers, message.as_string())

http://stackoverflow.com/a/51593548
score: 4
accepted answer of: http://stackoverflow.com/q/51593083
upvote count: 4
has body: First of all, you need to add missing indentations (as Colonbracket has mentioned) lines = [] while True: s = input() if s: lines.append(s.upper()) else: break for sentence in lines: print(sentence) You need to be careful with indentations in Python, since logic of Python program heavily depends on indentations. For more info on this see "First Steps Towards Programming" section of Python tutorial Secondly, based on what I understand about this code, its aim is to: Read lines from standard input (s = input()) until it gets an empty string from the user (break). Every line of this input is converted to an upper case (s.upper()) and stored in list data structure (lines.append) After user inputs an empty string, the program outputs all upper-cased strings to the standard output (for sentence in lines: print(sentence)) and then exits.
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51593083

http://stackoverflow.com/q/51635981
upvote count: 1
has body: This is the script that actually exports the values in my five lists to a .csv file: def exportEmployee(): # I moved the indentation over for clarity import csv with open('exportemployee.csv', 'w') as csvfile: export_employee = csv.writer(csvfile) export_employee.writerows([employeeName_List, employeeSSN_List, employeePhone_List,employeeEmail_List, employeeSalary_List]) print("Employees' record exported to file.\n\n") The funtionality works, but I am having an issue doing the reverse (importing): def importEmployee(): # I moved the indentation over for clarity import csv f = open('importemployee.csv') data = [] for line in f: data_line = line.rstrip().split(',') data.append(data_line) employeeName_List = data[0] employeeSSN_List = data[1] employeePhone_List = data[2] employeeEmail_List = data[3] employeeSalary_List = data[4] # print(*employeeName_List, sep = ', ') I print the lists outside of the import function, the lists are blank. However, if I print the list using print(*employeeName_List, sep = ', ') within the function it does return the values within the lists. What am I missing here?
type: Question
has title: Importing/Exporting .csv list
has comment: http://stackoverflow.com/comment/90238230
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51636972
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/90163034
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51598114
has text: If you don't want to go into programming, maybe you should not ask on Stackoverflow... Anyway, it seems to me that you are mostly looking for a converter.

http://stackoverflow.com/a/51575865
has comment: http://stackoverflow.com/comment/90117418
has comment: http://stackoverflow.com/comment/90117459
score: 0
answers question: http://stackoverflow.com/q/51574834
type: Answer
has body: Try this import json json = { "1": { "name": "item1", "symbol": "symbol1", "quotes": { "Amount": "45345", "other": "value", } }, "734": { "name": "item1", "symbol": "symbol1", "quotes": { "Amount": "45345", "other": "value", } }, "378": { "name": "item1", "symbol": "symbol1", "quotes": { "Amount": "45345", "other": "value", } }, "2": { "name": "item1", "symbol": "symbol1", "quotes": { "Amount": "45345", "other": "value", } } }; jsonSorted = sorted(json.items()) print(jsonSorted)

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/51629652
tags question: http://stackoverflow.com/q/51621553
tags question: http://stackoverflow.com/q/51584257
tags question: http://stackoverflow.com/q/51535038
tags question: http://stackoverflow.com/q/51627258
tags question: http://stackoverflow.com/q/51504525
type: Tag

http://stackoverflow.com/q/51485536
score: 1
type: Question
has title: pip install PyGTK error
answer count: 2
possible better answer: http://stackoverflow.com/a/55116335
favorite count: 0
has answer: http://stackoverflow.com/a/55116335
accepted answer: http://stackoverflow.com/a/51488405
linked to: http://stackoverflow.com/q/23708898
tagged with: python
has body: i type the following into the command prompt as administrator: pip install PyGTK and get the following error: Could not find a version that satisfies the requirement PyGTK &lt;from versions:&gt; No matching distribution found for PyGTK any thoughts of why this is happening, thank you in advance.
tagged with: installation
has answer: http://stackoverflow.com/a/51488405
upvote count: 2
tagged with: pip
downvote count: 1
tagged with: gtk
type: AnsweredQuestion

http://stackoverflow.com/q/51628968
has answer: http://stackoverflow.com/a/51629240
accepted answer: http://stackoverflow.com/a/51629710
possible better answer: http://stackoverflow.com/a/51629240
tagged with: python
has answer: http://stackoverflow.com/a/51629710
has title: Unable to return response from function
type: AnsweredQuestion
has body: I am working on a simple script to return a JIRA Case ID after an issue is submitted to JIRA. I have a created an issue function that takes JSON parameters from a RESTful web service and it then passes on said parameters to create a case in JIRA automatically. Here's a snippet of the function I've written: def create_issue(): issue = { 'summary': request.json['summary'], 'project': request.json['project'], 'desc': request.json['desc'], 'issuetype': request.json['issuetype'] } issue_dump= json.dumps(issue) issue_source = json.loads(issue_dump) summ = (issue_source["summary"]) proj = (issue_source["project"]) desc = (issue_source["desc"]) type = (issue_source["issuetype"]) print(f"{summ}") print(f"{proj}") print(f"{desc}") print(f"{type}") issue_dict = { 'project': proj, 'summary': summ, 'description':desc, 'issuetype':type, } new_issue = jira.create_issue(fields=issue_dict) #Used to print response of new_issue print(f"{new_issue}") response = {'JIRA ID': new_issue} return jsonify(response),201 I added a print statement of new_issue and I see the JIRA ID (e.g. ID-2) does appear on the console, but for some reason when I try to include it into my JSON response as a variable, I get the Object of type Issue is not JSON serialisable. I have tried substituting the new_issue variable in my response JSON with another defined test variable and it works just fine. I am using Flask to host the web services. Am I missing entirely on something here?
tagged with: http://stackoverflow.com/tag/json
type: Question
score: 0
answer count: 2

http://stackoverflow.com/q/51602116
type: Question
score: 0
answer count: 3
tagged with: pandas
has title: Conditional transformation of column in pandas Dataframe
possible better answer: http://stackoverflow.com/a/51602438
has answer: http://stackoverflow.com/a/51602260
has body: I would like to create a new column in my dataframe that is the difference between two variables IF a 3rd column in that row satisfies a certain condition. A min example looks like this: dict1 = [{'var0': 0, 'var1': 1, 'var2': 2}, {'var0': 0, 'var1': 2, 'var2': 4}, {'var0': 1, 'var1': 5, 'var2': 8}, {'var0': 1, 'var1': 15, 'var2': 12},] df = pd.DataFrame(dict1, index=['s1', 's2','s3','s4']) In particular I want the difference between var0 and var1 (var0-var1), for all rows where var 2 is larger than 3, else I want the difference between var0 and var2 (var0-var2) My target output would be: var0 var1 var2 var3 s1 0 1 2 -2 s2 0 2 4 -2 s3 1 5 8 -4 s4 1 15 12 -14
has answer: http://stackoverflow.com/a/51602254
has answer: http://stackoverflow.com/a/51602438
tagged with: python
type: AnsweredQuestion
tagged with: conditional-formatting
accepted answer: http://stackoverflow.com/a/51602254

http://stackoverflow.com/comment/97970344
type: AnswerComment
score: 0
has text: @JohnMoutafis I understand that. But if I have another (similar) file with routes, how to get app object itself to this file?
type: Comment
comment on: http://stackoverflow.com/a/53205515

http://stackoverflow.com/q/51623877
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: tweepy
score: 2
answer count: 0
upvote count: 2
has title: Exclude retweets when scraping tweets from accounts using Tweepy
tagged with: twitter
type: Question
has body: I have a list of Twitter usernames and I use the following code to retrieve 100 tweets from each user: account_list = list(['altgeldshrugged', 'colsonwhitehead', 'NickKristof', 'ayeletw', 'Bourdain']) data = [] for i in account_list: tweets = api.user_timeline(screen_name=i, count=100, include_rts=False) print("Number of tweets extracted: {}.\n".format(len(tweets))) for t in tweets: data.append(t.text) newdata = pd.DataFrame(np.array(data).reshape(100, 13), columns=account_list) However, the 100 tweets per user include retweets. When I use filter 'include_rts=False', the result will be like: Number of tweets extracted: 90. Number of tweets extracted: 26. Number of tweets extracted: 96. Number of tweets extracted: 42. Number of tweets extracted: 32. How can I modify the script so I get 100 tweets excluding retweets?
has comment: http://stackoverflow.com/comment/90324586

http://stackoverflow.com/comment/90197635
comment on: http://stackoverflow.com/q/51613969
has text: But one thing here is that, when i closed and again open spyder, then same prlb occurs. Is that mean always i have to write and run `matplotlib.rcParams['backend'] = 'Qt5Agg'` What is permanent solution
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51593406
tagged with: python
tagged with: logging
has answer: http://stackoverflow.com/a/60280342
has body: Having just upgraded to pip-18.0 all uses of pip produce this error: ...\site-packages\pip\_internal\__init__.py", line 5, in &lt;module&gt; import logging ModuleNotFoundError: No module named 'logging' logging.py exists in \site-packages\pip\_internal\utils\ (and also contains an 'import logging' statement!) I suppose I could move it up a directory level or update _init to 'import utils.logging' In fact lots of my programs' packages eg numpy are now failing with no logging module. I have now identified the problem: import logging Traceback (most recent call last): File "", line 1, in import logging ModuleNotFoundError: No module named 'logging' import lib2to3.logging lib2to3 is a subdir of Lib, containing the logging module, but is no longer found in the module search.
tagged with: pip
type: Question
has comment: http://stackoverflow.com/comment/90156667
score: 0
has answer: http://stackoverflow.com/a/73622250
answer count: 3
has answer: http://stackoverflow.com/a/51674270
has title: pip-18.0 has 'logging module not found' error
type: UnansweredQuestion

http://stackoverflow.com/q/51626090
has comment: http://stackoverflow.com/comment/90217810
has title: Select all the combinations of 8 elements from a given list
score: 0
has comment: http://stackoverflow.com/comment/90216966
answer count: 1
type: UnansweredQuestion
tagged with: python
has body: I have a list of 27 elements. str1=[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] I need to find all the combinations of selecting 8 elements from the list. So far I have found an algorithm as below. def combi(iterable, r): pool = tuple(iterable) n = len(pool) if r &gt; n: return indices = list(range(r)) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices) Any suggestion would be really helpful Edit- def getCombinations5(list1): list1=list1 list2=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] #print list2 #str1='123456' str1=[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] #print str1 list3=[] for value in combi(str1,8): #print '#############################' #print list3 #print value #print list2[int(value[0])] list2[int(value[0])]=0 list2[int(value[1])]=0 list2[int(value[2])]=0 list2[int(value[3])]=0 list2[int(value[4])]=0 list2[int(value[5])]=0 list2[int(value[6])]=0 list2[int(value[7])]=0 #print list2 list3.append(list2[:]) #print list3 #print list3 list2[int(value[0])]=1 list2[int(value[1])]=1 list2[int(value[2])]=1 list2[int(value[3])]=1 list2[int(value[4])]=1 list2[int(value[5])]=1 list2[int(value[6])]=1 list2[int(value[7])]=1 #print '@@@@@@@@@@@@@@@@@' #print len(list3) #print list2 print len(list3) list4=[] for value in list3: str2=''.join(str(e) for e in value) if '00000000' in str2 or '0000000' in str2 or '000000' in str2 or '00000' in str2 or '0000' in str2: continue elif '000' in str2: continue else: list0=list(str2) #print list0 list0=map(int, list0) list4.append(list0) print list4 What I want to do is to get combinations of 1s and 0s of 28 length pattern where only 8 bits are 0s and I need to discard combinations with 8,7,6,5,4 or 3 consecutive 0s.(First bit of the pattern is always 1) This method I have is real…
has answer: http://stackoverflow.com/a/51626217
type: Question
tagged with: algorithm

http://stackoverflow.com/comment/90188614
type: QuestionComment
comment on: http://stackoverflow.com/q/51611500
score: 0
type: Comment
has text: this is the code used to generate:

http://stackoverflow.com/comment/90047691
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51539460
has text: I am using python 3.6.5
score: 0

http://stackoverflow.com/comment/90208918
type: Comment
type: QuestionComment
score: 1
has text: "simple", but every other line is a branch statement.
comment on: http://stackoverflow.com/q/51621665

http://stackoverflow.com/a/51581542
has comment: http://stackoverflow.com/comment/90142034
type: AcceptedAnswer
score: 8
has comment: http://stackoverflow.com/comment/90130558
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/90128654
has comment: http://stackoverflow.com/comment/90130518
has comment: http://stackoverflow.com/comment/90128361
accepted answer of: http://stackoverflow.com/q/51581521
answers question: http://stackoverflow.com/q/51581521
has body: Change your activation at your output layer to sigmoid from top_model.add(Dense(1,activation='softmax')) to top_model.add(Dense(1,activation='sigmoid'))
downvote count: 0

http://stackoverflow.com/comment/90208263
has text: ....Well, maybe. What I mean to say is that I don't understand how to do what I want to do from reading the documentation. If you know of somewhere in the documentation that says "The equivalent of rpm -Va is xyz," I may have missed it and would appreciate reiteration...or at least a link.
score: 0
comment on: http://stackoverflow.com/q/51621281
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/89963735
comment on: http://stackoverflow.com/q/51497747
score: 0
type: Comment
type: QuestionComment
has text: If I use extend, this is the results ['h, 'e', 'l', 'l', 'o'] ['t', 'e', 's', 't']

http://stackoverflow.com/q/51612146
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51612265
score: 2
type: Question
downvote count: 0
has title: Perform cumulative count on a pandas column taking order into account
tagged with: python-2.7
tagged with: pandas-groupby
tagged with: pandas
has body: I have a pandas data frame pd.DataFrame(columns=["A", "B"], data=[['id1','a'],['id1','a'], ['id1','a'], ['id1','b'], ['id1','b'], ['id1','a'], ['id1','a'], ['id2','c'], ['id2','c'], ['id2','a'], ['id2','c']]) A B 0 id1 a 1 id1 a 2 id1 a 3 id1 b 4 id1 b 5 id1 a 6 id1 a 7 id2 c 8 id2 c 9 id2 a 10 id2 c I want to do a group by that gives me cumulative sum of occurrences in B column considering the order A B C 0 id1 a 3 1 b 2 2 a 2 3 id2 c 2 4 a 1 5 c 1
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/89992426
type: QuestionComment
comment on: http://stackoverflow.com/q/51511661
has text: @mehrdad-pedramfar Well if the size if 1 maybe. But if you have a large one next will be much quicker.
score: 1
type: Comment

http://stackoverflow.com/comment/90228441
comment on: http://stackoverflow.com/a/51631883
type: AnswerComment
score: 0
has text: OK, so filtering is what need, right? and because in `se` are only `0-30` values, get for `0-30` value`1`.
type: Comment

size
type: Tag
tags question: http://stackoverflow.com/q/51541053
tag name: size

http://stackoverflow.com/a/51528720
type: Answer
answers question: http://stackoverflow.com/q/51528643
has comment: http://stackoverflow.com/comment/90025991
downvote count: 0
has body: IIUC, from df = pd.DataFrame() df['x'] = [[{'QuestionId': 11, 'ResponseId': 1},{'QuestionId': 15, 'ResponseId': 1}, {'QuestionId': 16, 'ResponseId': 1}, {'QuestionId': 17, 'ResponseId': 1}, {'QuestionId': 18, 'ResponseId': 1, 'Value': 'abc'}, {'QuestionId': 23, 'DataLabel': 'xxx', 'ResponseId': 1}, {'QuestionId': 23, 'DataLabel': 'xxx', 'ResponseId': 2}, {'QuestionId': 23, 'DataLabel': 'xxx', 'ResponseId': 4}], [{'QuestionId': 11, 'ResponseId': 1}]] You can sum your lists to aggregate them, and use DataFrame constructor new_df = pd.DataFrame(df.x.values.sum()) DataLabel QuestionId ResponseId Value 0 NaN 11 1 NaN 1 NaN 15 1 NaN 2 NaN 16 1 NaN 3 NaN 17 1 NaN 4 NaN 18 1 abc 5 xxx 23 1 NaN 6 xxx 23 2 NaN 7 xxx 23 4 NaN 8 NaN 11 1 NaN If you want to maintain the original indexes, you can build a inds list and pass it as arguments to the constructor: inds = [index for _ in ([i] * len(v) for i,v in df.x.iteritems()) for index in _] pd.DataFrame(df.x.values.sum(), index=inds) DataLabel QuestionId ResponseId Value 0 NaN 11 1 NaN 0 NaN 15 1 NaN 0 NaN 16 1 NaN 0 NaN 17 1 NaN 0 NaN 18 1 abc 0 xxx 23 1 NaN 0 xxx 23 2 NaN 0 xxx 23 4 NaN 1 NaN 11 1 NaN
accepted answer of: http://stackoverflow.com/q/51528643
has comment: http://stackoverflow.com/comment/90025986
has comment: http://stackoverflow.com/comment/90058558
score: 3
has comment: http://stackoverflow.com/comment/90026112
has comment: http://stackoverflow.com/comment/90026199
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/comment/90080111
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51556728
has text: Yes, but it is lists inside a dictionary
score: 0

http://stackoverflow.com/q/51487144
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: camera
type: Question
tagged with: network-programming
answer count: 1
favorite count: 0
score: 0
has body: I've seen demos with wireshark and 3rd party utilities, but i've yet to see any in python. I've seen scapy but I'm not an infosec guy so this domain is quite confusing. Anyone know how I can use python to scan for networked IP cameras on home network?
has title: How to Scan for IP cameras on local network using Python?
tagged with: python-3.x
linked to: http://stackoverflow.com/q/207234
has answer: http://stackoverflow.com/a/51487237

http://stackoverflow.com/comment/89978732
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51498510
has text: @MarkSetchell If the image is close to the image. it recognizes two or three images as one image.It does not make sense to change the parameters according to the image. That is currently implemented state.

http://stackoverflow.com/comment/90160551
score: 0
comment on: http://stackoverflow.com/q/51597222
type: Comment
type: QuestionComment
has text: @RushabhMehta sorry maybe i didn't convey what i am asking well enough. i want to update a line that would already be in the dictionary when scanned in. i dont know how to go to the specific line and change the value.

http://stackoverflow.com/a/51497684
upvote count: 1
answers question: http://stackoverflow.com/q/51497423
score: 1
has comment: http://stackoverflow.com/comment/89963363
has body: The idiomatic way to search a specific line in a file is not your while...if...else that is likely to give an endless loop but a for line in...if...break construct. And you should reopen the file on each call, or at least rewind it, or make PERFORMANCE_FILE a list of lines to be able to scan the file more than once. def get_running_time(test): for line in PERFORMANCE_FILE: line_split = line.split() if test in line_split: return line_split[-2] return 0
has comment: http://stackoverflow.com/comment/89963434
downvote count: 0
type: Answer

http://stackoverflow.com/a/51560140
answers question: http://stackoverflow.com/q/51559978
type: Answer
has body: If you want imports to be referenced of the base proj directory you must set the PYTHONPATH to that directory. Currently honda.py is looking around for a moudule called params inside it's own module. ~$ cd path/to/project ~$ PYTHONPATH=$(pwd) Alternatively you could use relative imports.
score: 0

http://stackoverflow.com/q/51514315
possible better answer: http://stackoverflow.com/a/53657012
accepted answer: http://stackoverflow.com/a/51638839
upvote count: 11
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89997231
tagged with: django
score: 11
type: Question
has body: Recently i discovered that there is not-documented django.db.models.fields.Field.name option: @total_ordering class Field(RegisterLookupMixin): # here we have it ... ↓↓↓↓↓↓↓↓↓ def __init__(self, verbose_name=None, name=None, primary_key=False, max_length=None, unique=False, blank=False, null=False, db_index=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, choices=None, help_text='', db_column=None, db_tablespace=None, auto_created=False, validators=(), error_messages=None): ... There is mention of it in doc-way: # A guide to Field parameters: # # * name: The name of the field specified in the model. # * attname: The attribute to use on the model object. This is the same as # "name", except in the case of ForeignKeys, where "_id" is # appended. # * db_column: The db_column specified in the model (or None). # * column: The database column for this field. This is the same as # "attname", except if db_column is specified. # # Code that introspects values, or does other dynamic things, should use # attname. For example, this gets the primary key value of object "obj": # # getattr(obj, opts.pk.attname) Description above is related with #683 ([patch] Saving with custom db_column fails) ticket. So if we look through whole django.db.models.fields.Field class, this seems as name option is setting attribute name, which make real name of variable invalid: Suppose we have our model: # models.py from django.db import models class SomeModel(models.Model): first = models.CharField(max_length=50, verbose_name='first', name='second') third = models.CharField(max_length=50, verbose_name='third') What django-admin shell tells us: In[2]: from app.models import SomeModel In[3]: SomeModel.objects.create(first='first', third='third') Traceback (most recent call last): File "/Users/ailove/Home/personal/untitled/venv/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exe…
tagged with: django-models
has comment: http://stackoverflow.com/comment/89996974
has title: Purpose of django.db.models.fields.Field.name argument
has answer: http://stackoverflow.com/a/51638839
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/53657012
has comment: http://stackoverflow.com/comment/89997011
tagged with: python

http://stackoverflow.com/a/51640645
has body: As the &lt;select&gt; element is a Angular element so you have to induce WebDriverWait for the &lt;select&gt; element to be clickable and utilizing the Select class you can use the following solution: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import Select # other lines of code mySelect = Select(WebDriverWait(driver, 20).until(EC.visibilty_of_element_located((By.XPATH, "//select[contains(@class,'ng-tns-') and @aria-label='A']")))) # select by value mySelect.select_by_value("LD")
has comment: http://stackoverflow.com/comment/90247408
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51639372

http://stackoverflow.com/comment/89949033
type: Comment
type: QuestionComment
has text: What is version windows 32 or 64 bit?
comment on: http://stackoverflow.com/q/51487972
score: 0

google-cloud-platform
tags question: http://stackoverflow.com/q/51583060
tags question: http://stackoverflow.com/q/51599242
tags question: http://stackoverflow.com/q/51601631
tags question: http://stackoverflow.com/q/51551067
tags question: http://stackoverflow.com/q/51553183
tags question: http://stackoverflow.com/q/51504193
tags question: http://stackoverflow.com/q/51488117
tags question: http://stackoverflow.com/q/51623806
type: Tag
tags question: http://stackoverflow.com/q/51554341
tags question: http://stackoverflow.com/q/51490175
tags question: http://stackoverflow.com/q/51509373
tags question: http://stackoverflow.com/q/51581039
tag name: google-cloud-platform
tags question: http://stackoverflow.com/q/51490635
tags question: http://stackoverflow.com/q/51598801
tags question: http://stackoverflow.com/q/51597865
tags question: http://stackoverflow.com/q/51505029
tags question: http://stackoverflow.com/q/51540658
tags question: http://stackoverflow.com/q/51585440

http://stackoverflow.com/q/51501974
upvote count: 0
type: UnansweredQuestion
tagged with: file
has answer: http://stackoverflow.com/a/51502094
has body: import re import os def scan_folder(parent): # iterate over all the files in directory 'parent' for file_name in os.listdir(parent): if file_name.endswith(".txt"): mensaje = file_name.read() mensaje = mensaje.replace("\n","") # Number of CVE from "DiarioOficial" regex = r"\s*CVE\s+([^|]*)" matches = re.search(regex, mensaje) if matches: print (matches.group(1).strip()) scan_folder("/Users/.../DiarioOficial") I have the previous code to load and open all the .txt located in this route. I want to execute the function of Regex implemented for all the txt files that are in this route. It does not work, it gives me: Traceback (most recent call last): File "/Users/anna/PycharmProjects/extractData/Principal.py", line 80, in &lt;module&gt; scan_folder("/Users/anna/PycharmProjects/extractData/DiarioOficial") File "/Users/anna/PycharmProjects/extractData/Principal.py", line 16, in scan_folder mensaje = file_name.read() AttributeError: 'str' object has no attribute 'read' I want to go through all the files and operate the same in each one of them.
has title: Load, Open and Operate with RegEx, text files in Python
score: -1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/89972327
has answer: http://stackoverflow.com/a/51502071
favorite count: 0
tagged with: path
downvote count: 1
tagged with: python
tagged with: directory
tagged with: regex
has comment: http://stackoverflow.com/comment/89972330

http://stackoverflow.com/q/51623385
has answer: http://stackoverflow.com/a/51772866
tagged with: python
tagged with: rabbitmq
type: AnsweredQuestion
has title: Celery sometimes do not create tasks
has body: I am developing a Python API that uses Celery with Redis and RabbitMQ in order to manage my messages. Sometimes, when I submit some tasks to the queue, it just will not receive the messages I was expecting, it keeps empty, and when a retry them manually they may run. The messages that it misses are usually the same, but I can not understand why some specific arguments will only work sometimes. I have tried many codes to submit the messages. The first one: advertising_price_set_item.delay(account_id=account.id, tool_id=tool_id, ml_item_id=advertising.external_id, price=price, process_id=process_id) The second one: advertising_price_set_item.apply_async(kwargs={'account_id': account.id, 'tool_id': tool_id, 'ml_item_id': advertising.external_id, 'price': price, 'process_id': process_id}, retry=True) And finally: try: advertising_price_set_item.apply_async(kwargs={'account_id': account.id, 'tool_id': tool_id, 'ml_item_id': advertising.external_id, 'price': price, 'process_id': process_id}, retry=True, retry_policy={'max_retries': 44, 'interval_start': 0, 'interval_step': 0.2, 'interval_max': 0.2},) except Exception as e: print(e) logging.error(traceback.format_exc()) But all of them failed at some point, and I never got any message of Exception or error. The message in RabbitMQ looks something like this: {'user_id': 1, 'tool_id': 1, 'ml_items_id': ['A123', 'B123', 'C123'], 'price_premium': 0.01, 'price_classic': 0.01, 'price_free': 0.01, 'process_id': 1}
tagged with: celery
type: Question
tagged with: message
accepted answer: http://stackoverflow.com/a/51772866
tagged with: queue
score: 0
answer count: 1

http://stackoverflow.com/q/51636459
has comment: http://stackoverflow.com/comment/90237341
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51636578
tagged with: python
has answer: http://stackoverflow.com/a/51636585
has comment: http://stackoverflow.com/comment/90237398
type: Question
has title: difference between method and attribute python?
has comment: http://stackoverflow.com/comment/90237256
score: 0
answer count: 2
upvote count: 1
has body: I'm probably using the wrong terminology here, but I'm looking for an explanation on the difference between a function called on an object, i.e. method, and then an attribute of the object itself. Take the following df: df = pd.DataFrame({'a':[4, 5, 6, 7], 'b':[3, 2, 5, 4]}) You can call the sum() method/function on df, and you can call the columns attribute on df. I may be getting confused between chaining a method vs. calling an attribute using .. df.sum() df.columns
downvote count: 1

http://stackoverflow.com/comment/90101682
has text: @juanpa.arrivillaga well, then how do i get a list of all `classinfo` types for 3.x?! put it as the answer and ill mark it as correct
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51567392
type: Comment

http://stackoverflow.com/a/51635009
answers question: http://stackoverflow.com/q/51634868
downvote count: 0
score: 1
has body: Use subprocess from subprocess import check_output # check_output returns the output of the command # note: date is a unix command, try something else if on windows result = check_output('date', encoding='utf8') print(result)
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51634868

http://stackoverflow.com/q/51552075
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51552846
accepted answer: http://stackoverflow.com/a/51552846
linked to: http://stackoverflow.com/q/11544398
type: AnsweredQuestion
type: Question
score: 0
has title: Cannot login using user model Django
answer count: 1
has comment: http://stackoverflow.com/comment/90071846
has comment: http://stackoverflow.com/comment/90071966
has body: I have inserted data using User.objects.create() to the the User model and I cannot seem to login using the correct email and password. Whenever I try to Django always returns "wrong username or password" even though I have checked that the user exist using Django ORM. However, if I register using the link on the webpage, I can login but it created a user with a blank username so I can only create one user, change the username using Django ORM, and then create another one. Is there anything I did wrong? Thanks in advance Here is my User model: from django.contrib.auth.models import AbstractUser, UserManager from django.core.urlresolvers import reverse from django.db import models from django.db.models import Q from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ class MyUserManager(UserManager): def create_user(self, *args, **kwargs): """ Set username field as email. """ kwargs['email'] = self.normalize(kwargs['email']) kwargs['username'] = self.normalize(kwargs['email']) return super(MyUserManager, self).create_user(*args, **kwargs) @python_2_unicode_compatible class User(AbstractUser): ADMIN_AREA = 'aa' FINANCE = 'fn' RELATIONSHIP_MANAGER = 'rm' BUSINESS_MANAGER = 'bm' SENIOR_BUSINESS_MANAGER = 'sbm' ADMIN_INTERNAL = 'brm' POSITION_CHOICES = { (ADMIN_INTERNAL, 'Admin Internal'), (SENIOR_BUSINESS_MANAGER, 'Senior Business Manager'), (BUSINESS_MANAGER, 'Business Manager'), (RELATIONSHIP_MANAGER, 'Relationship Manager'), (FINANCE, 'Finance'), (ADMIN_AREA, 'Admin Area') } name = models.CharField(_('Nama Lengkap'), blank=True, max_length=255) phone = models.CharField('Nomor telepon', blank=True, max_length=20) phone_alt = models.CharField('Nomor telepon alternatif', blank=True, max_length=20) date_of_birth = models.DateField('Tanggal lahir', null=True) leader = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True) email = models.EmailField(max_length=255, unique=True) position = model…

http://stackoverflow.com/comment/90097155
has text: [How to debug small programs (#1)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) . This type of error happens if you index into a list _after_ its end. Output counter and see how many lines are in proglist.
comment on: http://stackoverflow.com/q/51565092
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51533985
answers question: http://stackoverflow.com/q/51532831
has comment: http://stackoverflow.com/comment/90047784
has comment: http://stackoverflow.com/comment/90036347
has comment: http://stackoverflow.com/comment/90038772
has body: This error message... Message: unknown error: unable to discover open pages ...implies that the ChromeDriver was unable to initiate/spawn a new WebBrowsing session through Chrome Browser. Your main issue is the incompatibility between the version of the binaries you are using as follows: You are using chromedriver=2.4 chromedriver=2.4 is pretty old and ancient. You are using Google Chrome Version 68.0.3440.75 (Official Build) (64-bit) Release Notes of ChromeDriver v2.40 clearly mentions the following : Supports Chrome v66-68 So there is a clear mismatch between the ChromeDriver v2.4 and the Chrome Browser v68.0 Solution As you are using Google Chrome Version 68.0.3440.75 as per the Release Notes you need to use a compatible ChromeDriver binary. Download the compatible ChromeDriver binary i.e. ChromeDriver v2.40 (2018-06-07) from ChromeDriver - WebDriver for Chrome. Update As you mentioned, even after upgrading to chromedriver=2.40 you still se the ChromeDriver version as chromedriver=2.4, you can override the previous version within OS PATH by explicitly mentioning the argument executable_path as follows: from selenium import webdriver driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe')
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90036961
type: Answer
has comment: http://stackoverflow.com/comment/90039929
has comment: http://stackoverflow.com/comment/90035747
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51532831
has comment: http://stackoverflow.com/comment/90039983
has comment: http://stackoverflow.com/comment/90035856
score: 1

http://stackoverflow.com/comment/90015015
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51522976
has text: Can you add example of input and desired output? Something like [mcve].
type: Comment

mongodb-atlas
tags question: http://stackoverflow.com/q/51526142
tag name: mongodb-atlas
type: Tag

http://stackoverflow.com/a/51577947
has body: I don't know about python but this is how you can do it with JS const arr = [ { "evt.category": "file", "evt.cpu": 0, "evt.num": 10078507, "evt.res": "SUCCESS", "evt.time": 1532841047277584400, "evt.type": "read", "fd.filename": "libnss_files.so.2", "fd.name": "/lib/x86_64-linux-gnu/libnss_files.so.2", "fd.num": 13, "fd.type": "file", "fd.uid": "1996913", "proc.loginshellid": 19968, "proc.name": "last", "proc.pid": 19969, "thread.ismain": true, "thread.tid": 19969 }, { "evt.buffer": "1000", "evt.category": "file", "evt.cpu": 0, "evt.num": 10078564, "evt.res": "SUCCESS", "evt.time": 1532841047277731300, "evt.type": "read", "fd.filename": "loginuid", "fd.name": "/proc/16009/loginuid", "fd.num": 13, "fd.type": "file", "fd.uid": "1996913", "proc.loginshellid": 19968, "proc.name": "last", "proc.pid": 19969, "thread.ismain": true, "thread.tid": 19969 }, { "evt.buffer": "", "evt.category": "file", "evt.cpu": 0, "evt.num": 10078566, "evt.res": "SUCCESS", "evt.time": 1532841047277733400, "evt.type": "read", "fd.filename": "loginuid", "fd.name": "/proc/16009/loginuid", "fd.num": 13, "fd.type": "file", "fd.uid": "1996913", "proc.loginshellid": 19968, "proc.name": "last", "proc.pid": 19969, "thread.ismain": true, "thread.tid": 19969 } ] const newArr = arr.map(obj =&gt;{ const newObj = {}; for(let key in obj){ const [mainKey,subKey] = key.split('.') if(newObj[mainKey] === undefined){ newObj[mainKey] = {} } newObj[mainKey][subKey] = obj[key]; } return newObj }) console.log(newArr)
score: 1
answers question: http://stackoverflow.com/q/51577527
has comment: http://stackoverflow.com/comment/90121311
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90023565
has text: Ok, I think this is a good illustration of why you should spend some time reading [how to ask](https://stackoverflow.com/help/how-to-ask) and how to create an [mcve](https://stackoverflow.com/help/mcve). This was two lines of code that really wouldn't have been too difficult to get right before releasing the question into the wild. While we may be able to iteratively get to a solution, these downvotes will count against your account so please do take some time to read through those guides.
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51527379

http://stackoverflow.com/a/51566087
score: 5
downvote count: 0
type: Answer
has body: Yes. Try: tesseract input_image out tsv txt It's not necessary to specify -l eng as it's the default language.
answers question: http://stackoverflow.com/q/51533254
has comment: http://stackoverflow.com/comment/90245556
has comment: http://stackoverflow.com/comment/90190425
upvote count: 5

http://stackoverflow.com/comment/90057183
type: Comment
comment on: http://stackoverflow.com/q/51530094
type: QuestionComment
score: 0
has text: Sample data has been added to the question.

http://stackoverflow.com/comment/90054181
has text: Can you provide your confirmation?
type: Comment
comment on: http://stackoverflow.com/q/51542203
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90097949
has text: Thanks, that works. Is there a more elegant way to achieve this though?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51565358

http://stackoverflow.com/comment/89967693
has text: I changed name. Now error is : Traceback (most recent call last): File "./proj2/__init__.py", line 5, in <module> from .celery import app as celery_app ImportError: No module named celery
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51499649
score: 0

http://stackoverflow.com/comment/90054553
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51543140
has text: Note that 0 for the slice start value is the default so you could write `str[:3]`.
score: 0

http://stackoverflow.com/q/51544577
has comment: http://stackoverflow.com/comment/90076139
score: 3
tagged with: ipywidgets
has comment: http://stackoverflow.com/comment/90062599
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/51551891
favorite count: 0
has answer: http://stackoverflow.com/a/51554585
answer count: 1
has title: ipywidgets with seaborn PairGrid plots
upvote count: 3
has body: In a Jupyter Notebook I am visualizing the Iris dataset with seaborn in combination with ipywidgets. That works fine, except that is not that fast because the plots have to be rendered every time you select a new combination of the species 'versicolor', 'virginica' and 'setosa'. See first code block. So I tried to speed up the interaction by pre-processing the plots for each combination of species and storing them in a dictionary. See second code block. The dictionary seems to contain all plots, but they don't show. Any suggestions how to fix this? First code block: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from ipywidgets import * sns.set(style="white") iris = sns.load_dataset("iris") def iris_pg(species): g = sns.PairGrid(iris[iris.species.isin(species)], diag_sharey=False) g.map_lower(sns.kdeplot) g.map_upper(sns.scatterplot) g.map_diag(sns.kdeplot, lw=3) return plt.show() interact(iris_pg, species = widgets.SelectMultiple(options=iris.species.unique(), value=tuple(iris.species.unique()[-2:]), rows=len(iris.species.unique()), description='species', disabled=False)) Second code block: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from ipywidgets import * from itertools import combinations sns.set(style="white") iris = sns.load_dataset("iris") all_combinations = list() for i in range(1, len(iris.species.unique()) + 1): for combi in combinations(iris.species.unique(), i): all_combinations.append(combi) all_plots = dict() for i in all_combinations: all_plots[i] = sns.PairGrid(iris[iris.species.isin(i)], diag_sharey=False) all_plots[i].map_lower(sns.kdeplot) all_plots[i].map_upper(sns.scatterplot) all_plots[i].map_diag(sns.kdeplot, lw=3) def iris_pg(species): all_plots[species] return plt.show() options = iris.species.unique() value = tuple(iris.species.unique()[-2:]) rows = len(iris.species.unique()) interact(iris_pg, species = widgets.SelectMultiple(options=options, value=value, rows=rows, description='spec…
tagged with: seaborn
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/127874969
score: 0
type: Comment
type: QuestionComment
has text: [This answer](https://stackoverflow.com/questions/57299968/python-how-to-reuse-a-mock-to-avoid-writing-mock-patch-multiple-times) explains how to do it in the `setUp` method of your test class. Slightly more detail than the existing answers below.
comment on: http://stackoverflow.com/q/51637925

http://stackoverflow.com/q/51623355
accepted answer: http://stackoverflow.com/a/51623370
answer count: 2
downvote count: 0
favorite count: 0
tagged with: tuples
has title: Sort list of lists of lists based on sum of Nth element of inner lists
has answer: http://stackoverflow.com/a/51623369
tagged with: python
type: AnsweredQuestion
tagged with: list
score: 1
upvote count: 1
type: Question
has body: If I have: a = [[['Q1', 20], ['R1', 14]], [['Q2', 18], ['R2', 17]], [['Q3', 24], ['R1', 14]]] how do I sort a so that I get: [[['Q3', 24], ['R1', 14]], [['Q2', 18], ['R2', 17]], [['Q1', 20], ['R1', 14]]] because the sum of the second elements of the lists within those tuples are 38, 35 and 34, respectively (in the second, sorted version)? Also, there has to be a better way to have this all organized so a suggestion regarding that would be gladly accepted!
possible better answer: http://stackoverflow.com/a/51623369
tagged with: sorting
has answer: http://stackoverflow.com/a/51623370

http://stackoverflow.com/comment/90426571
score: 0
type: AnswerComment
has text: I'd also suggest to run the import line with `gdb` to get some error stacktrace before filing the issue, but am unsure whether/how one can install and use `gdb` on Windows.
type: Comment
comment on: http://stackoverflow.com/a/51724121

http://stackoverflow.com/a/51567115
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51567058
has body: You don't actually need to read the file as text to replace the image URLs. Those values don't appear anywhere else in the file but in the current column of the current row. So you don't need to call replace on the contents of the whole file, just on the current column of the current row. This means you can just transform the CSV row by row. Writing to a temporary file and then moving it over the original is better than overwriting the file in-place. That way, if you, say, trip over the power cord in the middle of a write, you either have the complete original file, or the complete new file, not half the new file and everything else is lost forever. It's also more efficient—we can have both files open at once, and never have to store more than the current row in memory. And it's simpler—no need to worry about any conflicts between two handles to the same file, because you never have two handles to the same file. While we're at it, you don't even need replace here. Your column 1 is the original images piped together. You split them up into separate strings. You want to replace one of those strings completely with a different string. You can do that without replace—just use the different string instead of the original one. So, what you want is something like this: with open("row_data.csv") as fin, open("row_data.csv.tmp", "w") as fout: csv_in = csv.reader(fin) csv_out = csv.writer(fout) for row in csv_in: desktop_images_link = row[1] desktop_images = desktop_images_link.split('|') replacement_images = [hosted_url for desktop_image in desktop_images] row[1] = '|'.join(replacement_images) csv_out.writerow(row) os.replace('row_data.csv.tmp', 'row_data.csv') That's it. If you really did need to globally replace the images, because they could appear arbitrarily in other columns of other rows anywhere in the file, you could still improve your code—making it simpler, and also fixing a serious problem with it. The problem is that, in the middle of a loop over the rows in row_…
downvote count: 0
score: 1

http://stackoverflow.com/comment/90222115
comment on: http://stackoverflow.com/q/51628828
score: 0
has text: Please try steps mentioned at https://stackoverflow.com/questions/40845304/runtimewarning-numpy-dtype-size-changed-may-indicate-binary-incompatibility
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90135193
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51584734
type: QuestionComment
has text: Why not? at column 'Adj Close', i calculate row 1 with row 2, and i need to store the calculation result in column Up or Down. then i jump to calculate row 2 with row 3, and store this result in column Up or down, below the previous results, and so on, until the last row.

http://stackoverflow.com/comment/90076338
type: AnswerComment
score: 0
type: Comment
has text: Did this answer your question?
comment on: http://stackoverflow.com/a/51544898

http://stackoverflow.com/comment/90022415
has text: Try putting parenthesis around your `IN` parameters? `AND P_T in (?) AND ID in (?)`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51526720

http://stackoverflow.com/q/51525534
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90020260
type: Question
has comment: http://stackoverflow.com/comment/90019938
score: 0
has title: making executable using pyinstaller
tagged with: python-3.x
linked to: http://stackoverflow.com/q/41870727
tagged with: pyinstaller
has body: I am converting my code to executable using pyinstaller. The problem I am facing is that the program needs an excel file to be complete and the executable keeping saying it can't find it. I placed the excel file in the same directory as the executable yet I get not found. Before converting the program to the executable, the excel file was placed in the same directory as the program and it works. Is there a way to add the excel file to the executable(preferably) or where should I store it so that it can find it? wb2 = load_workbook('file.xlsx')
tagged with: python
answer count: 0

http://stackoverflow.com/q/51519728
has comment: http://stackoverflow.com/comment/90009317
upvote count: 0
has comment: http://stackoverflow.com/comment/90010376
score: -1
has comment: http://stackoverflow.com/comment/90009190
has body: I would like to clear stdout of a sub process under ssh. Please see the following simplified code which does not have much meaning but it regenerates the phenomenon. import shlex import subprocess import pickle # *** I cannot modify the pre_defined_func() *** print_func_py = 'def pre_defined_func():\n' \ ' print("I want to clear this message but I could not.")\n' \ ' return "answer" \n' \ '\n' \ 'result = pre_defined_func() \n' \ 'import os \n' \ 'import pickle \n' \ 'import io \n' \ 'bytes = io.BytesIO() \n' \ 'byte_stream = pickle.dumps(result) \n' \ 'os.system(\'cls\' if os.name == \'nt\' else \'clear\') \n' \ 'print(byte_stream)' print_func_py_sh = shlex.quote(print_func_py) get_value_command = ['ssh', 'localhost', 'python3', '-c', print_func_py_sh] get_value_process = subprocess.run(get_value_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print("stdout = {0}".format(get_value_process.stdout)) print("stderr = {0}".format(get_value_process.stderr)) The outputs are following, stdout = b"I wat to clear this message but I could not.\nb'\\x80\\x03X\\x06\\x00\\x00\\x00answerq\\x00.'\n" stderr = b'TERM environment variable not set.\n' I expected that "stdout = b'\x80\x03X\x06\x00\x00\x00answerq\x00.'" which is a serialized data by pickle. However 'stdout' contains extra binary, 'I want to clear this message but I could not.\n'. Before the line of 'print(byte_stream)', I tried to clear stdout by 'os.system(\'cls\' if os.name == \'nt\' else \'clear\') \n' but it failed. How can I clear stdout of sub process under ssh? And what does message of stderr means? Please tell me it. Thank you very much.
type: Question
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90008623
tagged with: subprocess
type: UnansweredQuestion
has title: How can I clear stdout of sub-process under ssh in Python?
has answer: http://stackoverflow.com/a/51520196
tagged with: python

http://stackoverflow.com/q/51592560
favorite count: 0
has comment: http://stackoverflow.com/comment/90150852
accepted answer: http://stackoverflow.com/a/51654870
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/90152086
has comment: http://stackoverflow.com/comment/90152135
type: AnsweredQuestion
tagged with: performance
has comment: http://stackoverflow.com/comment/90150416
has title: Python - Entire PC network gets slower during repeated request
upvote count: 1
has body: First of all, I am new to the network (HTTP communication) and Python. I am currently using requests and threading module to periodically send or receive data with a specific site. The target site is 'https://api.coinone.co.kr' but I think it does not matter here. By the example code below, I let Python fetch data every 1 second. At first, it works pretty well. Each request takes about 0.07 s in my computer. import requests import time import threading url0 = 'https://api.coinone.co.kr/ticker/' class Fetch: def __init__(self): self.thread = threading.Thread(target=self.fcn) self.t0 = time.perf_counter() self.period = 1 self.req0 = None def fcn(self): while True: # headers = None headers = {'Connection': 'close'} # requests t0 = time.perf_counter() req0 = requests.get(url0, headers=headers, params={'currency': 'all'}) resp0 = req0.json() self.req0 = req0 reqTimeInt0 = time.perf_counter() - t0 # prints print('elapsed time: %0.3f' % t0) # print(req0.request.headers) print(resp0['result']) print('requests time interval: %0.3f' % reqTimeInt0) print('') # timer self.t0 += self.period now = time.perf_counter() sleepInterval = self.t0 - now if sleepInterval &gt; 0: time.sleep(sleepInterval) else: while self.t0 - now &lt;= 0: self.t0 += self.period f1 = Fetch() f1.thread.start() But as time passes, the time needed for each 'http get' increases. After about 3 hours, one request takes 0.80 s where it is 10 times larger than it took in the initial state. Furthermore, not only does Python request get slower, but also the entire PC network gets slower (including internet browsing) without any increase in CPU, RAM resources, and network usage. Closing the console does not get back the network speed to normal and I have to reboot the PC. Anyway, after rebooting, the network is completely recovered and the internet works fine. It seems like some burdens in the network connection are accumulated at each Python request. So I tried adding 'Connection: close' to the header, but it didn'…
tagged with: http
tagged with: https
type: Question
answer count: 1
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51654870

http://stackoverflow.com/comment/90123116
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51578522
has text: Also, `await reader.read(length)` should really be `await reader.readexactly(length)`. The argument to [`StreamReader.read`](https://docs.python.org/3/library/asyncio-stream.html#asyncio.StreamReader.read) is the _maximum_, not exact number of bytes to read.
type: Comment

http://stackoverflow.com/comment/90216896
type: Comment
has text: @MarkTolonen: it was my first idea, but the errors occurs while decoding `barcode_stf` which is not the first field.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51595760

http://stackoverflow.com/q/51575498
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/70880834
tagged with: python
answer count: 4
upvote count: 1
downvote count: 1
type: Question
has body: I'm trying to write a script which deletes the C:\Windows\System32\Macromed and the C:Windows\SysWOW64\Macromed (basically adobe flash manual uninstall files). What I'm running into is permissions issues from windows due to it needing elevated permissions to delete these folders. However, Windows isn't prompting me to agree to permissions nor asking for my admin username/password to allow me to delete those folders. I've tried looking online and saw how the shutil.rmtree() works but like I said, running into the permissions wall thing.
has answer: http://stackoverflow.com/a/56722398
has title: Python: Script to delete folders from system32 or SysWOW64
score: 0
has comment: http://stackoverflow.com/comment/124192117
has answer: http://stackoverflow.com/a/51575691
has answer: http://stackoverflow.com/a/73703079

http://stackoverflow.com/comment/90049581
comment on: http://stackoverflow.com/a/51539819
score: 0
type: Comment
has text: @DocDriven - Sorry, I think need changed `all` with `any`.
type: AnswerComment

http://stackoverflow.com/a/51563155
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51562808
has body: As an attempted reproducer (which will be deleted as soon as the question is edited with a MCVE): # create a temporary directory tempdir=$(mktemp -d "${TMPDIR:-/tmp}/repro.XXXXXX") || exit # create our "first" script cat &gt;"$tempdir/first" &lt;&lt;'EOF' #!/usr/bin/env bash date=$1 p=$2 (cd ./scripts/ &amp;&amp; ./second "$p") EOF # create a "scripts" directory mkdir "$tempdir/scripts" || exit # create our "second" script cat &gt;"$tempdir/scripts/second" &lt;&lt;'EOF' #!/usr/bin/env bash ./third $1 EOF # create our "third" script cat &gt;"$tempdir/scripts/third" &lt;&lt;'EOF' #!/usr/bin/env python import sys p = sys.argv[1] print("I got " + p) EOF chmod +x "$tempdir"/{first,scripts/{second,third}} # make the scripts all executable... cd "$tempdir" &amp;&amp; ./first 20180716 0.5 # and actually run the first one ...properly emits 0.5.

http://stackoverflow.com/q/51604174
tagged with: python
type: AnsweredQuestion
score: 2
has title: beautifulsoup to seperate &nbsp and ; within a tag of html
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51604288
has body: My code html = "&lt;td&gt;1.08&amp;nbsp; 8.00&amp;nbsp; 151.00&lt;/td&gt;" from bs4 import BeautifulSoup print BeautifulSoup(html,"lxml").renderContents() The output: &lt;html&gt;&lt;body&gt;&lt;td&gt;1.08 8.00 151.00&lt;/td&gt;&lt;/body&gt;&lt;/html&gt; Desired output: 1.08 ; 8.00 ; 151.00 ;
accepted answer: http://stackoverflow.com/a/51604288
answer count: 1
favorite count: 0
tagged with: beautifulsoup
upvote count: 2

stream
tags question: http://stackoverflow.com/q/51485656
tags question: http://stackoverflow.com/q/51585110
tags question: http://stackoverflow.com/q/51611500
type: Tag
tag name: stream

http://stackoverflow.com/a/51499641
answers question: http://stackoverflow.com/q/51499366
type: Answer
downvote count: 0
score: 1
has body: Try this: import os import webbrowser import requests webbrowser.open(s) if os.path.isfile(s) or requests.get(s) else exec("raise Exception")
upvote count: 1

http://stackoverflow.com/comment/90083913
type: Comment
has text: I was missing the second part [1] ok now it works as I am after :)
type: AnswerComment
comment on: http://stackoverflow.com/a/51558361
score: 0

http://stackoverflow.com/q/51576868
type: Question
has answer: http://stackoverflow.com/a/51576880
has body: In my Django model, I have this model with 3 attributes with same foreign key type. employee = models.ForeignKey(Employee) approved_by = models.ForeignKey(Employee) created_by = models.ForeignKey(Employee) However, it complains on this after doing "makemigrations". Here is the errors: SystemCheckError: System check identified some issues: ERRORS: railercomapp.Leave.approved_by: (fields.E304) Reverse accessor for 'Leave.approved_by' clashes with reverse accessor for 'Leave.created_by'. HINT: Add or change a related_name argument to the definition for 'Leave.approved_by' or 'Leave.created_by'. railercomapp.Leave.approved_by: (fields.E304) Reverse accessor for 'Leave.approved_by' clashes with reverse accessor for 'Leave.employee'. HINT: Add or change a related_name argument to the definition for 'Leave.approved_by' or 'Leave.employee'. railercomapp.Leave.created_by: (fields.E304) Reverse accessor for 'Leave.created_by' clashes with reverse accessor for 'Leave.approved_by'. HINT: Add or change a related_name argument to the definition for 'Leave.created_by' or 'Leave.approved_by'. railercomapp.Leave.created_by: (fields.E304) Reverse accessor for 'Leave.created_by' clashes with reverse accessor for 'Leave.employee'. HINT: Add or change a related_name argument to the definition for 'Leave.created_by' or 'Leave.employee'. railercomapp.Leave.employee: (fields.E304) Reverse accessor for 'Leave.employee' clashes with reverse accessor for 'Leave.approved_by'. HINT: Add or change a related_name argument to the definition for 'Leave.employee' or 'Leave.approved_by'. railercomapp.Leave.employee: (fields.E304) Reverse accessor for 'Leave.employee' clashes with reverse accessor for 'Leave.created_by'. HINT: Add or change a related_name argument to the definition for 'Leave.employee' or 'Leave.created_by'. models.py class Leave(models.Model): leavedate = models.DateField() employee = models.ForeignKey(Employee) company = models.ForeignKey(Company) reason = models.IntegerField(defaul…
score: -2
downvote count: 2
answer count: 1
favorite count: 0
tagged with: model
tagged with: foreign-keys
type: UnansweredQuestion
tagged with: django
tagged with: python
upvote count: 0
has title: Django - attributes with same foreign key type is not allowed, how to solve this?

http://stackoverflow.com/comment/89940836
type: QuestionComment
score: 0
has text: Thanks for the replies. How can I use fuzzy-wuzzy between 3 columns?
comment on: http://stackoverflow.com/q/51485167
type: Comment

http://stackoverflow.com/a/63253642
has comment: http://stackoverflow.com/comment/111882481
type: Answer
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/51503851
downvote count: 0
has body: Just read this answer: https://stackoverflow.com/a/63271002/1601580 OLD I think the simplest answer is the one from the cifar10 tutorial: total = 0 with torch.no_grad(): net.eval() for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total)) so: acc = (true == pred).sum().item() If you have a counter don't forget to eventually divide by the size of the data-set or analogous values. I've used: N = data.size(0) # since usually it's size (batch_size, D1, D2, ...) correct += (1/N) * correct Self contained code: # testing accuracy function # https://discuss.pytorch.org/t/calculating-accuracy-of-the-current-minibatch/4308/11 # https://stackoverflow.com/questions/51503851/calculate-the-accuracy-every-epoch-in-pytorch import torch import torch.nn as nn D = 1 true = torch.tensor([0,1,0,1,1]).reshape(5,1) print(f'true.size() = {true.size()}') batch_size = true.size(0) print(f'batch_size = {batch_size}') x = torch.randn(batch_size,D) print(f'x = {x}') print(f'x.size() = {x.size()}') mdl = nn.Linear(D,1) logit = mdl(x) _, pred = torch.max(logit.data, 1) print(f'logit = {logit}') print(f'pred = {pred}') print(f'true = {true}') acc = (true == pred).sum().item() print(f'acc = {acc}') Also, I find this code to be good reference: def calc_accuracy(mdl, X, Y): # reduce/collapse the classification dimension according to max op # resulting in most likely label max_vals, max_indices = mdl(X).max(1) # assumes the first dimension is batch size n = max_indices.size(0) # index 0 for extracting the # of elements # calulate acc (note .item() to do float division) acc = (max_indices == Y).sum().item() / n return acc Explaining pred = mdl(x).max(1)see this https://discuss.pytorch.org/t/how-does-one-get-the-predicted-classification-label-from-a-pytorch-model/91649 the main thing is that y…

http://stackoverflow.com/a/51556064
type: Answer
has body: names=['A','B','C'] cars=['mercedes','porshe','hyundai'] numbers=[1,2,3] for name in names: file_name=name+".txt" # leave 4 spaces for the outermost level text_file = open(file_name, "w") for car in cars: print(cars) # leave 8 spaces for the innermost level for number in numbers: txt2write=name+" has "+str(number)+" "+car print(name+" has "+str(number)+" "+car) text_file.write("%s \n" %(txt2write)) text_file.close() print("That's all.") Get the indentation correct for the for loops. Also file_name=names+".txt" is supposed to be file_name=names+".txt" For reference - https://www.python.org/dev/peps/pep-0008/
has comment: http://stackoverflow.com/comment/90079376
has comment: http://stackoverflow.com/comment/90078797
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90078928
answers question: http://stackoverflow.com/q/51555889

http://stackoverflow.com/a/51632290
has comment: http://stackoverflow.com/comment/90229032
score: 0
has body: Using re.sub Ex: import re l = ['0.089*"apple" + 0.089*"mango" + 0.089*"orange"','0.205*"apple" +0.167*"mango" + 0.167*"apple"','0.056*"orange" + 0.056*"apple" + 0.056*"orange"'] for i in l: print( re.sub(r"[^A-Za-z\s]", "", i) ) res = [re.sub(r"[^A-Za-z\s]", "", i) for i in l] # ['apple mango orange', 'apple mango apple', 'orange apple orange'] Output: apple mango orange apple mango apple orange apple orange
answers question: http://stackoverflow.com/q/51632204
type: Answer

http://stackoverflow.com/a/51504727
has comment: http://stackoverflow.com/comment/89980158
has comment: http://stackoverflow.com/comment/89979102
has comment: http://stackoverflow.com/comment/89978938
has comment: http://stackoverflow.com/comment/89978539
has comment: http://stackoverflow.com/comment/89980116
has comment: http://stackoverflow.com/comment/89978494
accepted answer of: http://stackoverflow.com/q/51504684
has comment: http://stackoverflow.com/comment/89980218
has comment: http://stackoverflow.com/comment/89978556
answers question: http://stackoverflow.com/q/51504684
score: 0
has comment: http://stackoverflow.com/comment/89978819
has comment: http://stackoverflow.com/comment/89978912
has comment: http://stackoverflow.com/comment/89978737
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89980903
has body: The tarfile module is for tar files, including tar.bz2. if your file is not tar you should use bz2 module directly. Also, try using os.walk instead of multiple listdir as it can traverse the tree import os import bz2 import shutil for path, dirs, files in os.walk(path): for filename in files: basename, ext = os.path.splitext(filename) if ext.lower() != '.bz2': continue fullname = os.path.join(path, filename) newname = os.path.join(path, basename) with bz2.open(fullname) as fh, open(newname, 'wb') as fw: shutil.copyfileobj(fh, fw) This will uncompress all .bz2 files in all subfolders, in the same place they are. All other files will stay the same. If the uncompressed file already exists it will be overwritten. Please backup your data before running destructive code
has comment: http://stackoverflow.com/comment/89979038
type: Answer

http://stackoverflow.com/comment/90003918
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51512461
has text: Then use `(b.min() + 24).to_timestamp()`, check [docs](http://pandas.pydata.org/pandas-docs/stable/timeseries.html#converting-between-representations)
score: 1

http://stackoverflow.com/q/51600013
score: -3
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90166182
downvote count: 3
tagged with: loops
type: Question
answer count: 2
tagged with: for-loop
upvote count: 0
possible better answer: http://stackoverflow.com/a/51600699
has body: I am intrigued why the following Python code outputs numbers 10..29 (with step 1). Tested with both Python 2.7 and 3. for i in range(20): i += 10 print(i) So i += 10 is executed, but executed only once despite it is in the loop. That's a very confusing behavior. Why does Python behave this confusing way?
has comment: http://stackoverflow.com/comment/90166242
has answer: http://stackoverflow.com/a/51600699
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51600059
has title: Confusing behavior when assigning to the for loop variable in Python
favorite count: 0
accepted answer: http://stackoverflow.com/a/51600059
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90166251

http://stackoverflow.com/a/51576038
has body: Simple way to do it is remove every comma: np.array([v.replace(',', '') for v in arr], dtype=np.float32) If you have pandas, to_numeric is a good option. It gracefully handles any invalid values that may creep in post replacement. pd.to_numeric([v.replace(',', '') for v in arr], errors='coerce', downcast='float') Both methods return a float array as output.
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51576008
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90012196
comment on: http://stackoverflow.com/q/51521615
score: 0
has text: You want to find 2 closest to 1 on the left and 2 closest to 1 on the right?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51597284
downvote count: 3
has comment: http://stackoverflow.com/comment/90160739
favorite count: 0
has answer: http://stackoverflow.com/a/51597588
tagged with: python
has answer: http://stackoverflow.com/a/51613612
has body: I have a list of booleans like l = [False, False, False, True, True, True, False, False, True, False, False] and want to invert every edge value that is False like [True, True, True, True, True, True, False, False, True, True, True] What is the most pythonic way to achieve that?
has comment: http://stackoverflow.com/comment/90160691
answer count: 4
has answer: http://stackoverflow.com/a/51597478
has comment: http://stackoverflow.com/comment/90160644
has answer: http://stackoverflow.com/a/51598022
has comment: http://stackoverflow.com/comment/90161064
accepted answer: http://stackoverflow.com/a/51597478
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90160694
linked to: http://stackoverflow.com/q/9537543
type: Question
score: -1
has title: invert edge values in python boolean list
has comment: http://stackoverflow.com/comment/90161243
possible better answer: http://stackoverflow.com/a/51598022
upvote count: 2

http://stackoverflow.com/comment/90478842
score: 0
has text: Sorry for not following up. Did you figure it out? If not, I'm sure there's another solution.
type: Comment
comment on: http://stackoverflow.com/a/51637386
type: AnswerComment

http://stackoverflow.com/a/51618016
has body: The power of numpy is that it allows you to operate on entire array in a single operation. This is called vectorization or vectorizing. Under the hood there are loops to do this of course, but they are written in the C language and highly optimized so they run orders of magnitude faster than anything you can achieve with pure python. So when you write a function using numpy, your number one goal is to have numpy do all the work. Ideally there should be no explicit loops, only calls that operate on entire arrays all at once. Fortunately, numpy provides all the necessary utilities to make this possible in your case. Here is a step by step guide then: First, convert your input into an array. Arrays are just like lists in many ways, with the difference that you can do vectorized operations on them. Most numpy functions will silently convert their inputs to an array if you pass in a list, but we will do it explicitly: def numpy_fun_list(list_, x): arr = np.array(list_) So far so good. All further operations will be done to arr instead of list_. Next you'll want to filter out the even elements. The easiest way to do this is by masking the array. When you index a numpy array with a Boolean array of the same size, it will select the elements that are True in the Boolean array and discard the rest. For example: &gt;&gt;&gt; data = np.array([1, 2, 3, 4]) &gt;&gt;&gt; mask = np.narray([True, False, False, True]) &gt;&gt;&gt; data[mask] array([1, 4]) All the conditional and comparison operators create such Boolean arrays. In your case, you want to check if a number is odd, so you use modulo just like in Python, except that modulo operates on each element of the array: mask = (arr % 2) == 1 The operator == is what turns the result of the modulo operation into a Boolean mask: arr = arr[mask] Now we need to raise each element of the remaining arr to the power x. As you guessed, that's what np.power does: arr = np.power(arr, x) That's it. Now you can return or print your result. Ac…
has comment: http://stackoverflow.com/comment/90206774
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/90206650
downvote count: 1
has comment: http://stackoverflow.com/comment/90206755
score: 1
answers question: http://stackoverflow.com/q/51617421

http://stackoverflow.com/comment/89981218
comment on: http://stackoverflow.com/a/51505814
score: 0
type: Comment
has text: Great, thanks! That definitely does it, I'll have to read into the documentation to understand the usage better.
type: AnswerComment

http://stackoverflow.com/q/51586059
type: Question
answer count: 2
favorite count: 0
upvote count: 3
tagged with: http://stackoverflow.com/tag/html
downvote count: 1
tagged with: python
has title: Website always hangs using python requests library
score: 2
has body: I am trying to use the python requests library to get the html from this url https://www.adidas.com/api/products/EF2302/availability?sitePath=us However every time I run my code it hangs when making the get request header = BASE_REQUEST_HEADER url = 'https://www.adidas.com/api/products/EF2302/availability?sitePath=us' r = requests.get(url, headers = header) I checked the network tab in chrome and copied all the headers used including user agent so that is not the issue. I was also able to load the page in chrome with javascript and cookies disabled. This code works fine with other websites. I simply cant get a response from any of the adidas websites (including https://www.adidas.com/us). Any suggestions are greatly appreciated.
has answer: http://stackoverflow.com/a/51587255
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90137799
has answer: http://stackoverflow.com/a/51586148
tagged with: python-requests

http://stackoverflow.com/comment/89980110
comment on: http://stackoverflow.com/a/51505179
type: AnswerComment
has text: Is another method to go to the beginning to find the max and min for each columns, then perform that calculation you provided for the rows with continuous variables using the max and min for the respective column?
score: 0
type: Comment

http://stackoverflow.com/comment/90052044
comment on: http://stackoverflow.com/q/51541712
type: QuestionComment
type: Comment
score: 1
has text: @madjaoue: I guess, i made this silly mistake of directly assigning it to class, you code was helpful. Thank you so much man!

http://stackoverflow.com/comment/90153621
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51593857
has text: @RafaelC Inside the same dataframe, if I understand your question correctly. In total there will be 5 columns.

http://stackoverflow.com/comment/90164471
type: QuestionComment
has text: Hi @DannyG - could you please share examples of what are you talking about?
score: 0
comment on: http://stackoverflow.com/q/51548211
type: Comment

http://stackoverflow.com/q/51567751
has body: I'm trying so simulate coin tosses and profits and plot the graph in matplotlib: from random import choice import matplotlib.pyplot as plt import time start_time = time.time() num_of_graphs = 2000 tries = 2000 coins = [150, -100] last_loss = 0 for a in range(num_of_graphs): profit = 0 line = [] for i in range(tries): profit = profit + choice(coins) if (profit < 0 and last_loss < i): last_loss = i line.append(profit) plt.plot(line) plt.show() print("--- %s seconds ---" % (time.time() - start_time)) print("No losses after " + str(last_loss) + " iterations") The end result is --- 9.30498194695 seconds --- No losses after 310 iterations Why is it taking so long to run this script? If I change num_of_graphs to 10000, the scripts never finishes. How would you optimize this?
tagged with: performance
score: 5
has answer: http://stackoverflow.com/a/51576444
upvote count: 5
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51567919
answer count: 3
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90101979
accepted answer: http://stackoverflow.com/a/51567919
tagged with: python
possible better answer: http://stackoverflow.com/a/51567812
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51567812
linked to: http://stackoverflow.com/q/34682463
has title: Why is this Python script with Matplotlib so slow?
type: Question

http://stackoverflow.com/q/51605036
has answer: http://stackoverflow.com/a/51608308
type: Question
answer count: 2
tagged with: nltk
downvote count: 0
has answer: http://stackoverflow.com/a/51608403
tagged with: nlp
has comment: http://stackoverflow.com/comment/90175614
favorite count: 0
type: UnansweredQuestion
has title: Predicting the POS tag of the upcoming word
upvote count: 1
tagged with: python
has body: Is there a way in python (by using NLTK or SpaCy or any other library) that I can predict the POS tag of the word that are likely to follow the words so far I have entered. Eg- If i input I am going to It shows the POS tag of the next most likely word eg NN, becuase college can come after this
score: 1

http://stackoverflow.com/q/51500540
tagged with: python
has answer: http://stackoverflow.com/a/51500990
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/89970158
accepted answer: http://stackoverflow.com/a/51614150
type: Question
tagged with: psychopy
has answer: http://stackoverflow.com/a/51614150
possible better answer: http://stackoverflow.com/a/51500990
tagged with: python-2.7
has title: Why can I not include a "£" symbol in my psychopy.visual.TextStim?
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/89970411
favorite count: 0
has body: I am currently trying to print a text stimulus using python 2.7.15 and Psychopy 1.90.2. Unfortanately the "£" symbol is causing the initialisation of visual.TextStim to throw an error: money = 2 text_to_print = "£" + str(money) bonus = visual.TextStim(win, text=text_to_print, pos=[0.7,-0.35], height=TEXT_STIM_HEIGHT, font="Arial", bold=True) bonus.setColor('GoldenRod') bonus.wrapWidth=1 The error reads: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128) I would like to know how I can incorporate a "£" symbol at the start of my text stimuli. Thank you.

http://stackoverflow.com/a/51599021
type: Answer
has body: Since the default is None, you should just check it is not that. if categorical_values is not None: ... But that if block is a no-op anyway; it would be better to reverse it: if categorical_values is None: categorical_values = pd.qcut(series, q = 5) and you don't need an else block at all.
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/90164348
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90164006
accepted answer of: http://stackoverflow.com/q/51598961
answers question: http://stackoverflow.com/q/51598961

http://stackoverflow.com/a/60046022
type: Answer
has body: The easiest way to do this is to first reshape your tensor to be a 1D tensor, then use tf.unique (which currently only accepts 1D tensors, not sure why!) or tf.unique_with_counts (depending on whether you also need the counts of the unique elements), and then, if you also need the indices of the unique values to have the same shape as the original tensor, you can reshape also the indices. The following TensorFlow 2.1 program illustrates this. import tensorflow as tf # TF 2.1 def get_uniques(t): t1d = tf.reshape(t, shape=(-1,)) # or tf.unique, if you don't need counts uniques, idx, counts = tf.unique_with_counts(t1d) return uniques, tf.reshape(idx, shape=tf.shape(t)), counts if __name__ == '__main__': my_tensor = tf.constant([[1, 2, 1], [3, 4, 1], [5, 6, 1], [1, 2, 1]]) uniques, idx, counts = get_uniques(my_tensor) tf.print("tf.shape(uniques) =", tf.shape(uniques)) tf.print("tf.shape(idx) =", tf.shape(idx)) tf.print("tf.shape(counts) =", tf.shape(counts)) tf.print("uniques =", uniques)
downvote count: 4
score: 2
has comment: http://stackoverflow.com/comment/109830699
answers question: http://stackoverflow.com/q/51487990
upvote count: 6
has comment: http://stackoverflow.com/comment/113906741

http://stackoverflow.com/comment/90080942
type: Comment
has text: Sorting means I am increasing the complexity, is there any better way?
comment on: http://stackoverflow.com/a/51556807
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90027238
has text: If you run `document.querySelector('.post-subject')` on that page, that will also return none. Where do you see elements with a class of `post-subject`? Do you have to run a search or interact with the page first? If so, you'll need to do that before calling BeautifulSoup...
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51529482

http://stackoverflow.com/q/51547183
type: Question
tagged with: thread-safety
has body: Let's say you have a class that you intend to share among multiple threads. Python example: class ConcurrentClass: lock = threading.Lock() data1 = 1 data2 = 2 def modify_values(self, a, b): self.data1 = a self.data2 = b Is it best to acquire the lock inside the method modify_values()? # class method def modify_values(self, a, b): with self.lock: self.data1 = a self.data2 = b # calling code co = ConcurrentClass() co.modify_values(1, 2) Or should you let whoever's calling the function handle that? # class method def modify_values(self, a, b): self.data1 = a self.data2 = b # calling code co = ConcurrentClass() with co.lock: co.modify_values(1, 2)
tagged with: concurrency
tagged with: locking
has comment: http://stackoverflow.com/comment/90062307
downvote count: 0
has title: Should you acquire a lock inside or outside an API method?
favorite count: 0
has comment: http://stackoverflow.com/comment/90062166
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
upvote count: 2

http://stackoverflow.com/a/51494669
downvote count: 0
has body: import re def substring(string): output = {} name = string.split()[0] for i in range(1,len(string.split())): if len(re.findall('\d', string.split()[i]))==0: name = name + " " + string.split()[i] else: quantity = " ".join(string.split()[i:]) break output["Name"] = name output["Quantity"] = quantity return output Then put strings into this function like: substring("Fresh Value Raw Papaya 1 U (units) (300g-400g)") And you will get: {'Name': 'Fresh Value Raw Papaya', 'Quantity': '1 U (units) (300g-400g)'}
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51491656

http://stackoverflow.com/comment/118362105
has text: Thanks so much for this, helped me! For newer versions of spacy (3.0.5) you need to add `@Language.component("my_pipeline_component")` before the function definition and then add it to the pipe like so: `nlp.add_pipe("my_pipeline_component", after='ner')`
type: Comment
comment on: http://stackoverflow.com/a/56727426
score: 1
type: AnswerComment

http://stackoverflow.com/comment/100156988
comment on: http://stackoverflow.com/q/51577441
score: 1
type: Comment
type: QuestionComment
has text: https://docs.djangoproject.com/en/2.2/howto/initial-data/ this documentation will help you for initial data

http://stackoverflow.com/a/51513051
has body: Improving the for It is possible to directly store the sums at the first go in the dictionary with complexity O(N) regions_dict_sums = {x.region_name:0 for x in sales_data} for x in sales_data: regions_dict_sums[x.region_name]+=x.quantity So the total regions where sales are greater than zero will be hashed in the dictionary as keys and their values are the total sales for that region, accessible at constant time.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51512931
downvote count: 0
score: 1

http://stackoverflow.com/a/51565299
answers question: http://stackoverflow.com/q/51553625
downvote count: 0
type: Answer
upvote count: 9
score: 9
accepted answer of: http://stackoverflow.com/q/51553625
has body: griddata is based on the Delaunay triangulation of the provided points. Data is then interpolated on each cell (triangle). For example, for a 2D function and a linear interpolation, the values inside the triangle are the plane going through the three adjacent points. rbf works by assigning a radial function to each provided points. 'Radial' means that the function is only dependent on distance to the point. The value at any point is obtained by the sum of the weighted contribution of all the provided points. The method is applicable regardless of the dimension of the variable space, as soon as a distance function can be defined. The graph is an example of a Gaussian based interpolation, with only two data points (black dots), in 1D. The two Gaussian (dashed line) are the basis function used. The interpolation function (solid red) is the sum of the these two curves. The weights for each points are internally determined by a system of linear equations, and the width of the Gaussian function is taken as the average distance between the points. Here is the code to generate the graph: import numpy as np from matplotlib import pyplot as plt %matplotlib inline from scipy.interpolate import Rbf x, y = [0, 1], [1, 2] x_fine = np.linspace(-1, 2, 71) interp_fun = Rbf(x, y, function='gaussian') y_fine = interp_fun(x_fine) for x0, weight in zip( x, interp_fun.nodes ): plt.plot(x_fine, weight*interp_fun._function(x_fine-x0), '--k', alpha=.7) plt.plot(x_fine, y_fine, 'r', label='RFB Gaussian') plt.plot(x, y, 'ok'); plt.xlabel('x'); plt.ylabel('y'); plt.legend();
type: AcceptedAnswer

http://stackoverflow.com/comment/90220586
has text: @MohseMalka if this works for you, please accept the answer. That is the way to let others know this has a accepted answer/solution (without reading the comments). That then also shows up in search pages, etc.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51582171
type: AnswerComment

http://stackoverflow.com/comment/89939626
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51485295
type: AnswerComment
has text: Your code gives the same error for me in python 2.7.12. `Traceback (most recent call last): File "test.py", line 8, in <module> pool.map(factorint, L) File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map return self.map_async(func, iterable, chunksize).get() File "/usr/lib/python2.7/multiprocessing/pool.py", line 567, in get raise self._value AssertionError: daemonic processes are not allowed to have children`

google-colaboratory
tags question: http://stackoverflow.com/q/51523821
type: Tag
tags question: http://stackoverflow.com/q/51545539
tag name: google-colaboratory
tags question: http://stackoverflow.com/q/51576756
tags question: http://stackoverflow.com/q/51524964

http://stackoverflow.com/a/51531079
answers question: http://stackoverflow.com/q/51527979
type: Answer
upvote count: 1
score: 1
has body: You can use the attributes useCurveColor and curveColor to change the key colors. This will change the keys to blue on selected objects: for obj in cmds.ls(sl=True): anim_curves = cmds.listConnections(obj, type="animCurve") or [] if anim_curves: cmds.setAttr("{}.useCurveColor".format(anim_curves[0]), True) cmds.setAttr("{}.curveColor".format(anim_curves[0]), 0, 1, 1) # Must be values between 0.0 - 1.0 Just note that this will change ALL keys from a given attribute. As far as I know you can't change them individually.
downvote count: 0

http://stackoverflow.com/q/51507285
tagged with: keras
favorite count: 0
upvote count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51518400
tagged with: python
has body: I am using keras-rl to train my network with the D-DQN algorithm. I am running my training on the GPU with the model.fit_generator() function to allow data to be sent to the GPU while it is doing backprops. I suspect the generation of data to be too slow compared to the speed of processing data by the GPU. In the generation of data, as instructed in the D-DQN algorithm, I must first predict Q-values with my models and then use these values for the backpropagation. And if the GPU is used to run these predictions, it means that they are breaking the flow of my data (I want backprops to run as often as possible). Is there a way I can specify on which device to run specific operations? In a way that I could run the predictions on the CPU and the backprops on the GPU.
tagged with: tensorflow
type: Question
has title: Keras with Tensorflow backend - Run predict on CPU but fit on GPU
tagged with: keras-rl
has answer: http://stackoverflow.com/a/51570129
answer count: 2
score: 5
downvote count: 0

http://stackoverflow.com/comment/120381565
has text: How strange that the "from" and "to" scopes are the exact same. Could this have been the result of a bug at Google's end?
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51499034

http://stackoverflow.com/q/51552584
type: Question
upvote count: 2
tagged with: python-venv
has comment: http://stackoverflow.com/comment/90102908
downvote count: 0
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/90100973
has comment: http://stackoverflow.com/comment/90583210
has body: Okay, I'm at a bit of a loss here. I'm fairly new to Python and wanted to do a simple REST-app with Flask and SQLAlchemy. Obviously I have missed some step, but I cannot see it, can someone please have a look and see what I'm missing? These are the steps I have done so far: Create a folder for my project Create a setup.py inside my project folder with the following content from setuptools import setup setup( name='pyrecipe', version='0.0.1', packages=['pyrecipe'], include_package_data=True, install_requires=[ 'click', 'flask', 'sqlalchemy', 'flask-sqlalchemy', 'gunicorn', 'itsdangerous', 'jinja2', 'markupsafe', 'werkzeug', ], ) Creating a venv with python -m venv venv and activating it with source venv/bin/active Installing packages with pip install -e . Setting up the flask env with export FLASK_APP=pyrecipe && export FLASK_ENV=dev Running the app with flask run I get the following output Error: While importing "pyrecipe", an ImportError was raised: Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/flask/cli.py", line 235, in locate_app __import__(module_name) File "/home/cvelin/code/python/pyrecipe/pyrecipe/init.py", line 4, in from pyrecipe.database import init_db File "/home/cvelin/code/python/pyrecipe/pyrecipe/database.py", line 1, in from sqlalchemy import create_engine ModuleNotFoundError: No module named 'sqlalchemy' init.py content from flask import Flask app = Flask(__name__) from pyrecipe.database import init_db init_db() import pyrecipe.views database.py content from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('postgresql://postgres:postgres@localhost/postgres', convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = db_session.query_property() def init_db(): # import all modules here that might define models so that…
answer count: 0
has comment: http://stackoverflow.com/comment/90075105
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90138972
tagged with: setuptools
has title: python venv setup ModuleNotFoundError: No module named 'sqlalchemy' despite verifying it is available in virtual environment
tagged with: sqlalchemy

http://stackoverflow.com/comment/90022599
has text: Good idea - no objections from me. :)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51483333

http://stackoverflow.com/comment/89939778
has text: @hop. It even seems to work subclassing `dict` and then implement `__iter__()` to make the class "castable" to `tuple`.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51484937

http://stackoverflow.com/q/51491617
tagged with: ms-word
tagged with: text
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/89951845
type: Question
has comment: http://stackoverflow.com/comment/89951773
downvote count: 3
has title: trying to find a way to delete or reveal similar references with python
has answer: http://stackoverflow.com/a/51492077
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/89951962
favorite count: 0
has comment: http://stackoverflow.com/comment/89951999
linked to: http://stackoverflow.com/q/9835762
has body: I have a question and I need your help. I have a word file which contains many references like: [1] M.-H. Han, Y. Li, and C.-H. Hwang, "The impact of high-frequency characteristics induced by intrinsic parameter fluctuations in nano-MOSFET device and circuit," Microelectronics Reliability, vol. 50, pp. 657-661, 2010. [2] E. Maricau and G. Gielen, "Computer-aided analog circuit design for reliability in nanometer CMOS," Emerging and Selected Topics in Circuits and Systems, IEEE Journal on, vol. 1, pp. 50-58, 2011. . . . It would be possible that some of these references are similar but their numbers be different. do you have any idea to find a way to delete or reveal similar references with #python? thanks
tagged with: python

http://stackoverflow.com/comment/90196227
type: QuestionComment
has text: You can't return values from bound functions. The code that runs the function mostly ignores the return values.
score: 0
comment on: http://stackoverflow.com/q/51611929
type: Comment

http://stackoverflow.com/comment/125336614
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51494619
has text: did you ever resolve this issue?
score: 0

http://stackoverflow.com/comment/90130940
comment on: http://stackoverflow.com/a/51582058
has text: Worked like a charm. Appreciate the help. But i am having one issue, In Column J i need to put date and time ex., 2017-01-01 16:32:31. The result of subtraction should be in this format: 00:01:37
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51488974
has title: Decrease run time for program to generate random data
has comment: http://stackoverflow.com/comment/89946924
has comment: http://stackoverflow.com/comment/89946896
upvote count: 2
type: Question
tagged with: performance
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51489194
has body: I am required to generate 10GB of random data. I wrote the following python script to generate required number of bytes by writing string containing printable ASCII characters of random length to each line of file It takes 3 command line arguments. 1) Size 2) Minimum Length of string (optional parameter, defaults to 4) 3) Maximum Length of string (optional parameter, defaults to 10) This program is neither using memory or doing a lot of IO. What strategy can I use to increase the amount of bytes written per unit time. import random import sys K_SIZE = 1000 class Generator: def __init__(self,low=4,high=10): self.table = {i:chr(i) for i in range(33,127)} self.low = low self.high = high def create_n_bytes(self,total_bytes): bytes_created = 0 """Hack at the moment, this condition will fail only after more than n bytes are written """ while bytes_created &lt; total_bytes: bytes_to_create = random.randint(self.low,self.high) bytes_created = bytes_created+bytes_to_create+1 word=[""]*bytes_to_create for i in range(bytes_to_create): word[i] = self.table[random.randint(33,126)] text = "".join(word) #print(str(hash(text))+"\t"+text) print(text) def get_file_size_from_command_line(): size = sys.argv[1] return size def get_min_word_len_from_command_line(): if len(sys.argv) &gt; 2: low = sys.argv[2] return int(low) def get_max_word_len_from_command_line(): if len(sys.argv) &gt; 3: high = sys.argv[3] return int(high) def get_file_size_in_bytes(size): multiplier = 1 size_unit = size[-1] if size_unit == 'M' or size_unit == 'm': multiplier = K_SIZE*K_SIZE elif size_unit == 'K' or size_unit == 'k': multiplier = K_SIZE elif size_unit == 'G' or size_unit == 'g': multiplier = K_SIZE*K_SIZE*K_SIZE elif size_unit in ('0','1','2','3','4','5','6','7','8','9'): multiplier = 1 else: print("invalid size") exit() total_bytes = 0 if multiplier == 1: total_bytes = int(size) else: total_bytes = multiplier*int(size[:len(size)-1]) return total_bytes def main(): if len(sys.argv) == 2: gen = Generator(…
tagged with: python
score: 2

http://stackoverflow.com/q/51520746
accepted answer: http://stackoverflow.com/a/51520814
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51520814
score: 0
has title: reshape pandas dataframe column with delimiter
tagged with: pandas
answer count: 1
has body: I have the following dataframe (tab file with 2 columns-str) : id1 id2 g1 ID:05434 g1 ID:05434 g1 NaN g1 ID:05434|ID:38720|ID:33345 After doing df1 = df[df['id2'].notnull()] df2 = df1.drop_duplicates(['id1','id2']) I got df2, id1 id2 g1 ID:05434 g1 ID:05434|ID:38720|ID:33345 I am aiming to expand this to make it only 2 columns, say id1 id2 g1 ID:05434 g1 ID:05434 g1 ID:38720 g1 ID:33345 Is there any expand function for this ? Thanks in advance.
tagged with: python

http://stackoverflow.com/comment/90015885
type: Comment
comment on: http://stackoverflow.com/a/51521887
has text: Interesting. Sometimes I have had trouble downloading via direct link because the site expects certain headers to be present in the request. Looking at your info in your question, maybe the site wants the `Referer` header to be correctly set to `http://eoddata.com/download.aspx`? Couldn't hurt to try. You can add headers to the request by adding a `headers` keyword argument to the `requests.get()` call, passing in a dictionary of header name, header value pairs. It's also possible that the cookies are required.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/89963311
type: Comment
comment on: http://stackoverflow.com/q/51497682
type: QuestionComment
score: 1
has text: Right before the line 36 where the error appears, do `print(len(number))`, `print(len(guess))` and `print(a)`. You should see that `a` is probably too large to index one of the two lists (note that length-1 is the largest possible index)

http://stackoverflow.com/a/51724000
answers question: http://stackoverflow.com/q/51541610
has body: One possible thing you are missing is a prefetch. Add a prefetch of 1 at the end of your data pipeline like so: data_set = tf.data.Dataset.from_tensor_slices((training_inputs, training_labels)) data_set = data_set.repeat(n_epochs) data_set = data_set.batch(batch_size).prefetch(1) Adding a prefetch of 1 at the end of your dataset pipeline means you try and fetch 1 batch of data while training is happening. This way you wont be waiting around while the batch is prepared, it should be ready to go as soon as each train iteration is done.
score: 6
downvote count: 0
type: Answer
upvote count: 6

http://stackoverflow.com/comment/90057523
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51544246
type: QuestionComment
has text: What do you mean/use when you write that you are converting it to a Windows 10 executable.

http://stackoverflow.com/comment/90196745
type: QuestionComment
has text: The data is int16 binary data, how can I post that?
comment on: http://stackoverflow.com/q/51613143
score: 0
type: Comment

http://stackoverflow.com/comment/90173429
score: 0
type: Comment
type: QuestionComment
has text: When a node has children, you immediately stop considering any siblings to its right. (Also, you should really try to be consistent with your capitalization.)
comment on: http://stackoverflow.com/q/51603749

http://stackoverflow.com/a/51622927
has comment: http://stackoverflow.com/comment/90241673
type: Answer
answers question: http://stackoverflow.com/q/51622756
has body: Just combine your if conditions. I did not understand what you mean by "if direction is N or E, insert Dir__NB_or into field Count" the bold terms if (Direction == "N") or (Direction == "E"): return Dir__NB_or elif (Direction == "S") or (Direction == "W"): return Dir_SB_or else: return "0000"
score: 0

http://stackoverflow.com/comment/90009128
type: QuestionComment
type: Comment
has text: `obj = factories.EventFactory.create(title='Event title 1', date=date(2018, 7, 24), event_from=datetime(2018, 8, 22, 10, 0, 0, 0), event_to=datetime(2018, 8, 24, 10, 0, 0, 0)) self.assertContains(response, obj)` This code is not working for me
score: 0
comment on: http://stackoverflow.com/q/51517273

http://stackoverflow.com/comment/90172513
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51602145
score: 1
has text: `sitepackagApex` is definitely not a normal thing to see in a `sys.path`.

http://stackoverflow.com/a/51505881
answers question: http://stackoverflow.com/q/51505727
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89982515
type: Answer
accepted answer of: http://stackoverflow.com/q/51505727
has comment: http://stackoverflow.com/comment/89981536
score: 1
upvote count: 1
has body: Looks like you want a function that takes two parameters, combines them into a vector, and calls f: def g1(x, y): return f([x, y]) As a more general solution, the function g2 takes any number of parameters, combines them into a vector, and calls f: def g2(*x): return f(x) Finally, since the first two elements of the vector are required for f, this function takes at least two parameters: def g3(x, y, *rest): return f((x, y) + rest)

http://stackoverflow.com/a/51528233
has comment: http://stackoverflow.com/comment/90085938
has comment: http://stackoverflow.com/comment/90025037
has comment: http://stackoverflow.com/comment/90025505
answers question: http://stackoverflow.com/q/51527980
type: Answer
has comment: http://stackoverflow.com/comment/90085706
score: 1
has body: You code is a bit hard to re-work but here is a working example of how one can monitor a file. Say I have a file that contains 4 lines and we call this file my_file: 1 test 2 testing 3 more testing 4 test again All we want to do is update the labels ever 4 seconds so we can use the after() method to keep us going. Take a look at this below code. import tkinter as tk window = tk.Tk() window.title("Notifications") file_to_monitor = "./my_file.txt" def read_notifications(): with open(file_to_monitor, "r") as f: x = f.read() string_list = x.split("\n") lbl1.config(text=string_list[0]) lbl2.config(text=string_list[1]) lbl3.config(text=string_list[2]) lbl4.config(text=string_list[3]) window.after(4000, read_notifications) lbl1 = tk.Label(window, text="") lbl1.grid(column=0, row=0, stick="w") lbl2 = tk.Label(window, text="") lbl2.grid(column=0, row=1, stick="w") lbl3 = tk.Label(window, text="") lbl3.grid(column=0, row=2, stick="w") lbl4 = tk.Label(window, text="") lbl4.grid(column=0, row=3, stick="w") read_notifications() window.mainloop() What we start out with on the first read: Then after I have made a change to the file and saved from my notepad:
has comment: http://stackoverflow.com/comment/90025048
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90025231
has comment: http://stackoverflow.com/comment/90088149
has comment: http://stackoverflow.com/comment/90085606

http://stackoverflow.com/comment/90093990
score: 0
comment on: http://stackoverflow.com/a/51528564
type: Comment
type: AnswerComment
has text: yeah thats what i ended up doing

http://stackoverflow.com/comment/89974214
comment on: http://stackoverflow.com/a/51502776
has text: can you please edit your answer explaining that the '2' is rounding to the second decimal?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51573331
possible better answer: http://stackoverflow.com/a/51581214
score: 2
downvote count: 0
type: Question
type: AnsweredQuestion
tagged with: graphviz
has answer: http://stackoverflow.com/a/51581214
upvote count: 2
answer count: 2
accepted answer: http://stackoverflow.com/a/51778742
has body: I'm currently trying to represent a graph with Graphviz, in which the edges have 2 colors. Ideally, I'd like to have each edge cut in two, one half colored in each color. Another constraint is that I have to use the RGB encoding, like in color="#4a52ff". I can't use the color="black" way. I've tried to separe the color tags with a :, but the result I obtain is a double edge. Here is a minimal example : import graphviz as gv color1, color2 = "#3f7f3f", "#ff7f3f" g = gv.Graph(format="png") g.node("1", color=color1) g.node("2", color=color2) g.edge("1", "2", color="%s:%s" % (color1, color2)) g.render("tmp", view=True) I obtain a small graph with 2 nodes and 1 edge, but the single edge seems to have been doubled, one version in each color. What I'd like to have is one orange end, connected to the orange node, and one green end connected to the green one.
favorite count: 0
tagged with: colors
has answer: http://stackoverflow.com/a/51778742
has title: How can I draw a bicolor edge?
tagged with: python

http://stackoverflow.com/comment/90229428
type: QuestionComment
has text: Don't ask us to download a huge file when your problem can be reproduced by only the first 2-3 lines and 2-3 columns. Just make the smallest example input and give it to us as plain text.
score: 1
comment on: http://stackoverflow.com/q/51632283
type: Comment

http://stackoverflow.com/comment/89976781
comment on: http://stackoverflow.com/q/51503997
has text: e.g. using xpath
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90225311
type: Comment
type: QuestionComment
has text: Please include your code, so that the error might get reproduced.
comment on: http://stackoverflow.com/q/51630571
score: 0

http://stackoverflow.com/comment/127904341
type: QuestionComment
type: Comment
has text: Solution is here; https://stackoverflow.com/questions/31420817/convert-excel-row-column-indices-to-alphanumeric-cell-reference-in-python-openpy
comment on: http://stackoverflow.com/q/51544241
score: 0

http://stackoverflow.com/comment/90185801
has text: Did you try this on less orderly input?
comment on: http://stackoverflow.com/a/51610600
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90208438
type: Comment
type: QuestionComment
has text: Can you show the expected output?
comment on: http://stackoverflow.com/q/51621190
score: 0

http://stackoverflow.com/q/51506691
upvote count: 1
tagged with: python
tagged with: tensorflow
type: Question
answer count: 1
downvote count: 0
tagged with: keras
has answer: http://stackoverflow.com/a/51506975
has body: I'm trying to use the output of a tf.keras.layers.Lambda function as the last layer in a tf.keras model, but tf is interpreting the lambda layer's output as a Tensor(as opposed to a Layer) object. The error is: "ValueError: Output tensors to a Model must be the output of a TensorFlow Layer (thus holding past layer metadata). Found: Tensor("Discriminator/mullayer/mul:0", shape=(2, 2), dtype=float32)" and the code is attached below from tensorflow.contrib.keras import layers, models #lots of stuff up here, all working fine... logits = layers.Dense(1, name=name+'fc')(x)# x works fine mullayer = layers.Lambda(lambda x: x * self.alphaVal,name = "mullayer") test = tf.constant([1.0],shape = (2,2)) testOut = mullayer(test) outputs = [logits, testOut] self.disc = models.Model(inputs=inp, outputs=outputs) 'self.alphaVal' is not a keras variable, just a float, which I suspect may be part of the problem. If so, what is the equivalent of keras' backend K in tf.keras? Thanks
score: 1
has title: ValueError: Output tensors to a Model must be the output of a TensorFlow Layer with tf.keras Lambda layer
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90095053
comment on: http://stackoverflow.com/q/51563985
score: 0
has text: It works! Thank you so much. The other answers I found only said to do `element.copy()` so I was confused.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51639569
score: 0
has body: Numpy gives that error when it encounters a line of data that's longer than it was expecting. You specified 11 column names and 11 columns types, but the lines reported as having 12 columns instead of 11 have 11 commas in them. So when numpy is searching for the , delimiter it finds 12 entries rather than 11. You'll need to open the csv in some text editor and take a look at those lines.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90243833
type: Answer
has comment: http://stackoverflow.com/comment/90243896
accepted answer of: http://stackoverflow.com/q/51638943
answers question: http://stackoverflow.com/q/51638943
has comment: http://stackoverflow.com/comment/90243668

http://stackoverflow.com/q/51518682
tagged with: django-rest-framework
score: 0
tagged with: python
type: AnsweredQuestion
has body: 1.models.py class User(AbstractUser, BaseModel): full_name = models.CharField(max_length=64) addresss=models.CharField(max_length=40) phoneno=models.IntegerField(null=True, blank=True) email=models.EmailField() gender=models.IntegerField(choices=gender_choice,default='0') class Student(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) father_name=models.CharField(max_length=64) mother_name=models.CharField(max_length=60) date_of_birth=models.DateField(null=True) def __str__(self): return self.user.full_name 2.Serializers.py class UserPostSerializer(serializers.ModelSerializer): class Meta: model=User fields=('full_name','addresss','gender','id') ##Serializer Class for Student class StudentSerializer(serializers.HyperlinkedModelSerializer): user = UserPostSerializer() class Meta: model=Student fields=( 'id', # 'father_name', # 'mother_name', # 'date_of_birth', 'user', ) 4.Views.py class StudentViewset(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerializer http_methods = ['get', 'post','put','delete'] def create(self, request): serializer=StudentSerializer(data=request.data) serializer.is_valid() row = serializer.data user = row['user'] full_name = user['full_name'] first_name = full_name.split(' ')[0] # email = first_name + '@schoolX.com' # _e = User.objects.filter(email=email) # if _e: # email = first_name + str(+count) + '@schoolX.com' emailpattern = '{}(\d*)@schoolx.com'.format(first_name) count = User.objects.filter(email__iregex=emailpattern).count() if count &gt; 0: email = '{}{}@schoolx.com'.format(first_name, str(count)) user,created = User.objects.get_or_create(email= email, defaults={'full_name':row['user']['full_name'],'addresss':row['user']['addresss']}) student = Student.objects.create(user_id=user.id) return Response({'email':email}) 4.Urls.py router.register(r'students', views.StudentViewset) when i try to add student it shows error like this;; Internal Server Error: /students/ Traceback (most r…
type: Question
has answer: http://stackoverflow.com/a/51518830
accepted answer: http://stackoverflow.com/a/51518830
has title: UnboundLocalError: local variable 'email' referenced before assignment
answer count: 1

floating-point
tags question: http://stackoverflow.com/q/51502747
type: Tag
tags question: http://stackoverflow.com/q/51554088
tags question: http://stackoverflow.com/q/51539460
tags question: http://stackoverflow.com/q/51617318
tags question: http://stackoverflow.com/q/51615174
tags question: http://stackoverflow.com/q/51601146
tag name: floating-point
tags question: http://stackoverflow.com/q/51602582

http://stackoverflow.com/q/51565154
score: 0
answer count: 3
has body: Suppose I have a below text file called file1.txt: Adam male John male Mike male Sue female and I have the below list fullname=['John Smith', 'Sue Hunt'] I want to be able go though the text file, and if it there is any matching there, amend the line with the word found, output should look like below: Adam male John male found Mike male Sue female found so I got this code, but the replace function don;t seem to be right f=open(file1.txt,'a') for line in f: for name in fullname: firstname,lastname=name.split('--') if firstname in line: line.replace('\n', 'found\n')
has answer: http://stackoverflow.com/a/51566771
has comment: http://stackoverflow.com/comment/90097240
type: UnansweredQuestion
tagged with: python
has title: python match string and add words to end of the line
has answer: http://stackoverflow.com/a/51565244
type: Question
has answer: http://stackoverflow.com/a/51565182
has comment: http://stackoverflow.com/comment/90097450

http://stackoverflow.com/comment/90166232
has text: It seems like you just need to call `type` or `isinstance` on `args[0]` instead of `cls` in your `__new__(cls, *args)`. Is that the only problem you're having here? In case it isn't clear: the `cls` parameter will get the class that you're trying to construct an instance of (which will be `Foo`, or a subclass of `Foo`); the other parameters will get the arguments passed to the constructor.
score: 0
comment on: http://stackoverflow.com/q/51586711
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51529615
score: 3
has comment: http://stackoverflow.com/comment/90028241
has answer: http://stackoverflow.com/a/51529674
upvote count: 3
has title: How can I access the Django server using WSL (Windows Subsystem for Linux)?
has answer: http://stackoverflow.com/a/63366836
favorite count: 0
has answer: http://stackoverflow.com/a/64407986
has body: I'm using Bash on Ubuntu on Windows 10 and installed django within a python virtual environment. I'm able to start the django server successfully, but when I type in "http://127.0.0.1:8000/" in my windows 10 browser I don't get a response. I've tried changing the port number to something else (eg. python3 manage.py runserver 127.0.0.1:7171) and I still get nothing. I don't think it's a firewall issue, as WSL and the browser and all running on the same Windows 10 laptop. Do you know what the issue might be? (env) $ python3 manage.py runserver Performing system checks... System check identified no issues (0 silenced). July 26, 2018 - 00:50:25 Django version 2.0.7, using settings 'portfolio.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Windows Version: Windows 10 build 1709 (16299.492) Ubuntu Version: Ubuntu 16.04.5 LTS
tagged with: python
answer count: 4
tagged with: windows-subsystem-for-linux
has answer: http://stackoverflow.com/a/54015096
downvote count: 0
type: UnansweredQuestion
tagged with: django
type: Question

http://stackoverflow.com/comment/89973933
score: 0
has text: @RafaelC Got it
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51502263

http://stackoverflow.com/comment/90056916
type: QuestionComment
comment on: http://stackoverflow.com/q/51544141
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/176820/discussion-between-bob-sacamento-and-joel).
score: 0
type: Comment

http://stackoverflow.com/comment/90141720
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51587960
score: 1
has text: Is you vector dense (how much 1's)?

http://stackoverflow.com/q/51571112
has comment: http://stackoverflow.com/comment/90109092
has body: I'm an in python. I'm trying to learn using functions. My code block and error are below. Could you help me please How can I use "def" word to describe a function. How can I fix the problem? Thanks. File "C:/Users/tCLARABUL/PycharmProjects/test/WScall.py", line 8 url == "http://zzzz:80/xxx/yyy?WSDL" ^ IndentationError: expected an indented block import requests def inka(ntfid): url = "http://zzzz:80/xxx/yyy?WSDL" headers = yyy body = "xxx"" response = requests.post(url, data=body, headers=headers) return response.text print(inka(122727))
has comment: http://stackoverflow.com/comment/90108217
duplicate of: http://stackoverflow.com/q/45621722
has answer: http://stackoverflow.com/a/51571148
has comment: http://stackoverflow.com/comment/90128203
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51571148
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/45621722
tagged with: function
has title: IndentationError: expected an indented block error in python when use "def"
has comment: http://stackoverflow.com/comment/90108729
score: 0
has answer: http://stackoverflow.com/a/51571128
accepted answer: http://stackoverflow.com/a/51571128
tagged with: python

http://stackoverflow.com/a/51504287
answers question: http://stackoverflow.com/q/51502595
type: Answer
has body: You can also create a pivot to do what you want in one line. Note that the output format is different -- it's a pandas.DataFrame.pivot rather than a standard pandas data frame. But if you're not especially fussed about that (depends on how you intend to use the final table), the following code does the job. df = pd.DataFrame({'Product':['A','B','C','D','E','F'], 'Customer':[1,1,2,3,3,3], 'Amount':[4,5,3,1,1,2]}) pivot_df = df.pivot(index='Product', columns='Customer', values='Amount').fillna(0).astype('int') Output: Customer 1 2 3 Product A 4 0 0 B 5 0 0 C 0 3 0 D 0 0 1 E 0 0 1 F 0 0 2 df.pivot creates NaN values when there are no corresponding entries in the original df (it creates a NaN value for Product A and Customer 2, for instance). NaNs are float values, so all the 'Amounts' in the pivot are implicitly converted into floats. This is why I use fillna(0) to convert the NaN values into 0s, and then finally change the dtype back to int.
score: 0

http://stackoverflow.com/a/51695669
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/92412404
downvote count: 0
has comment: http://stackoverflow.com/comment/116190875
score: 10
answers question: http://stackoverflow.com/q/51503199
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/115821884
accepted answer of: http://stackoverflow.com/q/51503199
has body: First, if you only need polyglot for language detection, you'd better use pycld2 directly, that is what used behind the scenes. It has much cleaner API. Saying that, the error you state comes from one of the values in your Text column, which is a real number. So you will have to convert values like that into strings. The next problem you will stumble upon is minimal text length. polyglot will throw exception if the text is too short. You have to silence the exception by passing quiet=True. Now, applying Detector will return an object. So you will have to parse it to extract the information you want. To extract language names, you will have to import icu module (it is a dependency of polyglot, so you have it installed already): import icu df.Text = df.Text.astype(str) df['poly_obj'] = df.Text.apply(lambda x: Detector(x, quiet=True)) df['Text-lang'] = df['poly_obj'].apply(lambda x: icu.Locale.getDisplayName(x.language.locale)) df['Text-LangConfidence'] = df['poly_obj'].apply( lambda x: x.language.confidence) After that you can drop the poly_obj column.

http://stackoverflow.com/comment/90124965
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51579854
type: Comment
has text: @JoeDoe you don't, as that's not explicit (which exceptions will you handle? What do you expect your code to raise? Etc.). [Explicit is better than implicit](https://www.python.org/dev/peps/pep-0020/). In general, however, if you catch [`BaseException`](https://docs.python.org/2/library/exceptions.html#exception-hierarchy), all other exceptions should be caught also.

http://stackoverflow.com/q/51548198
has body: I am using a recurrent neural network to make hourly wind predictions based on previous wind data. I am trying to shift my data 1 hour back using the .shift to generate this. My DateFrame looks like [this][1] My code is: import numpy as np import pandas as pd from pandas import DataFrame wind_p = [0, 0.03454225, 0.02062136, 0.00186715, 0.01517354, 0.0129046, 0.02231125, 0.01492537, 0.09646542, 0.28444476] Speed = [0, 2.25226244, 1.44078451, 0.99174488, 0.71179491, 0.92824542, 1.67776948, 2.96399534, 5.06257161, 7.06504245] Date = ['2012-01-01 01:00:00' ,'2012-01-01 02:00:00', '2012-01-01 03:00:00', '2012-01-01 04:00:00', '2012-01-01 05:00:00', '2012-01-01 06:00:00', '2012-01-01 07:00:00', '2012-01-01 08:00:00', '2012-01-01 09:00:00', '2012-01-01 10:00:00'] df = pd.DataFrame({'date':Date,'wind_P':wind_p,'Speed':Speed}) dates=[datetime.strptime(x,'%Y-%m-%d %H:%M:%S') for x in Date] df['t']= [x for x in range(10)] df['t+1'] = df[Speed].shift(-1) print(df) The error message I am getting from this is: KeyError Traceback (most recent call last) &lt;ipython-input-1-bb88ddb20ff4&gt; in &lt;module&gt;() 18 19 df['t']= [x for x in range(10)] ---&gt; 20 df['t+1'] = df[Speed].shift(-1) 21 print(df) ~/anaconda3_501/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key) 1956 if isinstance(key, (Series, np.ndarray, Index, list)): 1957 # either boolean or fancy integer index -&gt; 1958 return self._getitem_array(key) 1959 elif isinstance(key, DataFrame): 1960 return self._getitem_frame(key) ~/anaconda3_501/lib/python3.6/site-packages/pandas/core/frame.py in _getitem_array(self, key) 2000 return self.take(indexer, axis=0, convert=False) 2001 else: -&gt; 2002 indexer = self.loc._convert_to_indexer(key, axis=1) 2003 return self.take(indexer, axis=1, convert=True) 2004 ~/anaconda3_501/lib/python3.6/site-packages/pandas/core/indexing.py in _convert_to_indexer(self, obj, axis, is_setter) 1229 mask = check == -1 1230 if mask.any(): -&gt; 1231 raise KeyError('%s not in …
favorite count: 0
has title: KeyError when shifting column data back 1
possible better answer: http://stackoverflow.com/a/51548229
score: 6
has answer: http://stackoverflow.com/a/51548229
tagged with: python
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/51548326
type: Question
tagged with: neural-network
upvote count: 6
has answer: http://stackoverflow.com/a/51548326
answer count: 2
tagged with: pandas

http://stackoverflow.com/a/51617126
upvote count: 4
downvote count: 0
has body: Using to_dict with 'records' df['New c']=df'C','D'.to_dict('records') df Out[580]: A B C D \ 0 0.578095 -1.985742 -0.269517 -0.180319 1 -0.618431 -0.937284 0.556290 -1.416877 2 1.695109 0.122219 0.182450 0.411448 3 0.228466 0.268943 -1.249488 3.227840 4 0.005990 -0.805618 -1.941092 -0.146649 5 -1.116451 -0.649854 1.272314 1.422760 New c 0 {'C': -0.269517, 'D': -0.180319} 1 {'C': 0.55629, 'D': -1.416877} 2 {'C': 0.18245, 'D': 0.411448} 3 {'C': -1.249488, 'D': 3.22784} 4 {'C': -1.9410919999999998, 'D': -0.146649} 5 {'C': 1.272314, 'D': 1.42276}
has comment: http://stackoverflow.com/comment/90200620
score: 4
answers question: http://stackoverflow.com/q/51616996
type: Answer

http://stackoverflow.com/q/51567059
type: Question
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/90100735
has comment: http://stackoverflow.com/comment/90100755
has comment: http://stackoverflow.com/comment/90100785
tagged with: tuples
tagged with: typeerror
has comment: http://stackoverflow.com/comment/90100725
answer count: 1
has comment: http://stackoverflow.com/comment/90101088
has title: Python3: TypeError: 'list' object is not callable
has body: I am trying to build up a Huffman tree for a practice, and my code building a tuple keeps telling me that I got a TypeError: 'list' object is not callable for this following code: def buildTree(mylist) : while len(mylist) &gt; 1 : leastTwo = tuple(mylist[0:2]) &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; problematic line theRest = mylist[2:] combFreq = leastTwo[0][0] + leastTwo[1][0] mylist = theRest + [(combFreq,leastTwo)] mylist.sort() return mylist[0] Update: The input Mylist would be a list with tuples like this: [(1, 'b'), (1, 'd'), (1, 'g'), (2, 'c'), (2, 'f'), (3, 'a'), (5, 'e')] I have been trying to debug for a while yet none of my solutions really works. I am following the instruction from http://www.openbookproject.net/py4fun/huffman/huffman.html, which does exactly the same thing as I did, so I am not sure what went wrong especially for me. Thank you so much for your help!
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90100716
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/90100760
has comment: http://stackoverflow.com/comment/90100780
has answer: http://stackoverflow.com/a/51567146
has comment: http://stackoverflow.com/comment/90100729
has comment: http://stackoverflow.com/comment/90118114
tagged with: list
has comment: http://stackoverflow.com/comment/90100776
has comment: http://stackoverflow.com/comment/90100732

http://stackoverflow.com/comment/90102131
has text: Can you post the output of `df.head().to_dict()` instead, so that I can create it directly with all the columns?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51567859

http://stackoverflow.com/a/59229237
has body: A better way would be calculating correct right after optimization step for epoch in range(num_epochs): correct = 0 for i, (inputs,labels) in enumerate (train_loader): ... output = net(inputs) ... optimizer.step() correct += (output == labels).float().sum() accuracy = 100 * correct / len(trainset) # trainset, not train_loader # probably x in your case print("Accuracy = {}".format(accuracy))
type: Answer
answers question: http://stackoverflow.com/q/51503851
has comment: http://stackoverflow.com/comment/112041107
has comment: http://stackoverflow.com/comment/111851301
upvote count: 28
score: 27
has comment: http://stackoverflow.com/comment/111853847
downvote count: 1

http://stackoverflow.com/a/51651798
score: 0
answers question: http://stackoverflow.com/q/51626343
type: Answer
has body: Please check this once: I could not find a single expression that could do this. So did it in a bit elaborate way. Will update if I can find a better way(Python 3) import re st = "3,SIN-Audio,\"AAA - Audio, xxxx, yyyy\",\"Orbis, PC\",\"13, 22\",Open" found = re.findall(r'\"(.*)\"',st)[0].split("\",\"") final = "" for word in found: final = final + (" &amp;").join(word.split(","))+"," result = re.sub(r'\"(.*)\"',final[:-1],st) print(result)

http://stackoverflow.com/comment/89976819
score: 0
has text: @Siegmeyer: **as long as there is a reference to an object** their id won't change. Storing objects in a dictionary means there is at least one reference to that object, the dictionary.
type: AnswerComment
comment on: http://stackoverflow.com/a/51503803
type: Comment

http://stackoverflow.com/a/51581048
has body: To set the grid via rcParameters you can use the grid.linestyle parameter. Set this to any value you want. import matplotlib.pyplot as plt plt.rcParams["axes.grid"] = True plt.rcParams["grid.linestyle"] = (5,9) plt.gca() plt.show() It's currently not possible to use such tuples in an external matplotlibrc file.
accepted answer of: http://stackoverflow.com/q/51580820
score: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51580820
upvote count: 3

http://stackoverflow.com/q/51575931
answer count: 17
has answer: http://stackoverflow.com/a/58525728
has answer: http://stackoverflow.com/a/73095470
has answer: http://stackoverflow.com/a/77686601
has answer: http://stackoverflow.com/a/59972855
upvote count: 334
has body: I'm currently trying my hands on the new dataclass constructions introduced in Python 3.7. I am currently stuck on trying to do some inheritance of a parent class. It looks like the order of the arguments are botched by my current approach such that the bool parameter in the child class is passed before the other parameters. This is causing a type error. from dataclasses import dataclass @dataclass class Parent: name: str age: int ugly: bool = False def print_name(self): print(self.name) def print_age(self): print(self.age) def print_id(self): print(f'The Name is {self.name} and {self.name} is {self.age} year old') @dataclass class Child(Parent): school: str ugly: bool = True jack = Parent('jack snr', 32, ugly=True) jack_son = Child('jack jnr', 12, school = 'havard', ugly=True) jack.print_id() jack_son.print_id() When I run this code I get this TypeError: TypeError: non-default argument 'school' follows default argument How do I fix this?
has answer: http://stackoverflow.com/a/68040649
has answer: http://stackoverflow.com/a/63220524
possible better answer: http://stackoverflow.com/a/69822584
linked to: http://stackoverflow.com/q/49908182
has answer: http://stackoverflow.com/a/53085935
has answer: http://stackoverflow.com/a/69822584
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/68942137
has comment: http://stackoverflow.com/comment/124239206
score: 333
tagged with: python-3.7
has answer: http://stackoverflow.com/a/58130805
type: Question
has answer: http://stackoverflow.com/a/51595616
has answer: http://stackoverflow.com/a/68946815
accepted answer: http://stackoverflow.com/a/53085935
has answer: http://stackoverflow.com/a/54653255
tagged with: python
has answer: http://stackoverflow.com/a/71197919
has comment: http://stackoverflow.com/comment/139515260
has answer: http://stackoverflow.com/a/66186678
tagged with: python-dataclasses
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/55796971
has answer: http://stackoverflow.com/a/75936241
downvote count: 1
has title: Class inheritance in Python 3.7 dataclasses

http://stackoverflow.com/q/51594556
has body: I need to get a commission of execution in TWS. I connect to them through ib_insync library for python. I do abt: ib = IB() ib.connect('127.0.0.1', 7497, 1) ib.placeOrder(contract, order) for e in ib.executions(): print(e) The question is - where is the commissions for this executions is flying? how can i catch them all?
tagged with: python-3.x
has title: How can I get a commission of execution in ib_insync TWS
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51603796
type: Question
answer count: 2
score: 0
possible better answer: http://stackoverflow.com/a/51597094
has answer: http://stackoverflow.com/a/51597094
tagged with: tws
has answer: http://stackoverflow.com/a/51603796

http://stackoverflow.com/comment/90064457
has text: @SeanPianka Unfortunately that didn't seem to work empirically. I'm not sure WHY, but c'est la vie. It's actually the first thing I looked at.
comment on: http://stackoverflow.com/q/51548206
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51523029
upvote count: 16
accepted answer of: http://stackoverflow.com/q/51522848
type: AcceptedAnswer
downvote count: 0
has body: This is where your graph is disconnected (uconv2 is not defined when you are calling it): # 32 -&gt; 64 deconv2 = Conv2DTranspose(start_neurons * 2, (3, 3), strides=(2, 2), padding="same")(uconv3) uconv2 = Conv2D(start_neurons * 2, (3, 3), activation="relu", padding="same")(uconv2)
has comment: http://stackoverflow.com/comment/92182389
type: Answer
answers question: http://stackoverflow.com/q/51522848
has comment: http://stackoverflow.com/comment/90014942
score: 16

http://stackoverflow.com/comment/90206230
score: 1
comment on: http://stackoverflow.com/q/51620139
type: Comment
type: QuestionComment
has text: It's also possible you have a mismatch between your pip and python versions (i.e. you are still pointing to pip for python2, so it thinks flask_sqlalchemy is installed, but then running with python3). Hard to judge without seeing your environment what is going on here

http://stackoverflow.com/a/51629636
has body: Please make sure that your pip version is up to date with: pip install -U pip Then, as per the comments and edited question, execute: pip install -U tensorflow==1.5.0 --ignore-installed six This will ignore the six related error and the slightly downgraded tensorflow package will install and be useable without the Illegal Instruction error. To check if the installation was successfull, execute: python -c "import tensorflow as tf; print(tf.__version__)"
has comment: http://stackoverflow.com/comment/90223711
has comment: http://stackoverflow.com/comment/90224730
has comment: http://stackoverflow.com/comment/90224457
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51629358
has comment: http://stackoverflow.com/comment/90224523
has comment: http://stackoverflow.com/comment/90223969
has comment: http://stackoverflow.com/comment/90223807
type: Answer
has comment: http://stackoverflow.com/comment/90223722
score: 1
has comment: http://stackoverflow.com/comment/90224263
upvote count: 1
has comment: http://stackoverflow.com/comment/90224090
accepted answer of: http://stackoverflow.com/q/51629358

http://stackoverflow.com/q/51501231
downvote count: 0
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/89972524
has comment: http://stackoverflow.com/comment/89974689
has comment: http://stackoverflow.com/comment/89974654
has title: Query params on detail view return a list instead of json nested serializers Django Rest Framework
has comment: http://stackoverflow.com/comment/89974984
favorite count: 0
has comment: http://stackoverflow.com/comment/89973904
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: django
tagged with: output
tagged with: python
has comment: http://stackoverflow.com/comment/89974890
has comment: http://stackoverflow.com/comment/89971095
has comment: http://stackoverflow.com/comment/89971499
has comment: http://stackoverflow.com/comment/89974821
score: 1
tagged with: http://stackoverflow.com/tag/json
has body: I'm rather new to Django Rest Framework and I'm having a problem I don't quite understand. If I setup a APIView to return all the objects in a particular model I get an array of data as expected class ProcedureListView(APIView): def get(self, request, format=None): procedures = AutomationProcedure.objects.all() serializer = AutomationProcedureSerializer(procedures, many=True) return Response(serializer.data) My api call to this endpoint looks like $ http --json GET http://localhost:8000/api/procedures/ And the response [ { ... ... } ] But if I write a detail view that takes query parameters the single object still returns as a list class ProcedureDetail(generics.ListAPIView): def get_queryset(self): queryset = AutomationProcedure.objects.all() display_name = self.request.query_params.get('display_name', None) if display_name is not None: queryset = queryset.filter(display_name=display_name) return queryset And then if I make an API call in this manner: $ http --json GET http://localhost:8000/api/procedures/ display_name="jenkins" The response still comes back as a list. [ { ... ... } ] Now I know that Detailview is inheiriting from ListAPIView which it would make sense that it would come back as a List. But what am I supposed to do here? Override the serializer method to represent it as json or something? Thanks for your help in advance this has been a tough one The desired output would be something like { ... ... # Various nested objects } The data comes out exactly the way I want with the exception of the the surrounding [] for the detail view. If I rewrite the method and do something like return Response(serializer.data[0]) This works out perfectly. But seems kind of hacky Here are my serializers class AutomationTemplateParameterSerializer(serializers.ModelSerializer): class Meta: model = AutomationTemplateParameter fields = ['sys_automation_template_parameter_id', 'sys_automation_template_id', 'parameter_name', 'parameter_value', 'default_value', 'description', …
has comment: http://stackoverflow.com/comment/89973418
has comment: http://stackoverflow.com/comment/89974964
type: Question

http://stackoverflow.com/comment/90001421
type: Comment
has text: please post your df not image
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51516494

http://stackoverflow.com/a/51619237
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51619160
downvote count: 0
has body: If you read the documentation of pd.Series.count, you will see it does not do what you think it does: Series.count(level=None) Return number of non-NA/null observations in the Series You've provided a pandas Series as the level argument, which is invalid, and is why you are getting the error. For your use, try this instead: df['counter'] = df.apply(lambda x: x.Text.count(x.Object), axis=1) Object Text counter 0 Banana Banana Banana Banana 3 1 Banana Apple Apple Apple 0 2 Apple Banana Apple 1 If you care about performance, you can also use a simple list comprehension here: df['counter'] = [i.count(j) for i, j in zip(df.Text, df.Object)] Timings (Use the list comprehension :D) df = pd.concat([df]*10000) %timeit df.apply(lambda x: x.Text.count(x.Object), axis=1) 1.14 s ± 14.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit [i.count(j) for i, j in zip(df.Text, df.Object)] 6.71 ms ± 25 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

http://stackoverflow.com/comment/114284748
score: 2
has text: I’m voting to close this question because the crucial information is no longer accessible so no one can benefit from seeing what was wrong.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51568529

http://stackoverflow.com/comment/90153707
score: 0
type: Comment
has text: I can't thank you enough! Sorry if my question was complicated or not explained well enough, you've given me the resources I need!
type: AnswerComment
comment on: http://stackoverflow.com/a/51583106

http://stackoverflow.com/q/51516644
type: Question
has body: I was surprised when i found that python scipy.ndimage.zoom automatically add new channel when the zoom is performed: from scipy.misc import imread from scipy.ndimage import zoom img = imread('lena.jpg') img=imread('lena.jpg') img.shape (468, 792, 3) x = zoom(img, 1.0) x.shape (468, 792, 3) x = zoom(img, 1.5) x.shape (702, 1188, 4) x = zoom(img, 2) x.shape (936, 1584, 6) The width, height dimension are correct, i was not able to understand from where came from the other dimensions. This strange behavior manifests only for colored image: x = zoom(img[:, :, 0], 2) x.shape (936, 1584)
tagged with: image
accepted answer: http://stackoverflow.com/a/51523451
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: zooming
has title: Why scipy.ndimage zoom add new channel?
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/51523451
tagged with: scipy

http://stackoverflow.com/a/51637363
type: Answer
has body: Your issue comes from the view code, where you instantiate your new model. If you want to create a new model you don't need to pass the insance argument, just edit the lines to get the following : pic = PictureForm(request.POST, request.FILES) pic.save() See https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/#the-save-method To be able to set only a few fields you should update your model declaration, with for example null=True, Blank=True, default=None in the optional fields arguments. PS : the django documentation is transalated in many languages, but if you don't find yours try the IRC channels.
answers question: http://stackoverflow.com/q/51637195
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/51638194
answers question: http://stackoverflow.com/q/51638005
has body: You only need to check if all the edges of the path are valid. def accepts(g, path): return all([(path[i],path[i+1]) in g.edges() for i in range(len(path)-1)]) Example: g=nx.DiGraph() g.add_edge("Q1","Q1") g.add_edge("Q1","Q2") g.add_edge("Q2","Q2") print(accepts(g, ["Q1", "Q1", "Q2"])) print(accepts(g, ["Q2", "Q2", "Q2"])) print(accepts(g, ["Q2", "Q2", "Q1"])) print(accepts(g, ["Q1", "Q2", "Q1"])) print(accepts(g, ["Q1", "Q1", "Q2", "Q1"]))
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/51560637
has answer: http://stackoverflow.com/a/51561221
tagged with: python
tagged with: kivy
type: AnsweredQuestion
tagged with: popup
type: Question
has body: I want to have a popup for confirming that the user really wants to quit the app. Now when I try to bind commands to the two buttons, I can only add the dismiss directly inside the function, not via a callback. That may be ok. But I can only call my closing routine through a callback, not inside the function. When I bind quit_app() inside this function it gets directly executed when opening the popup. Why? It just should bind, not execute. (Old script deleted.) I have updated my script a bit and included a minimum kv file. It works basically (like previously) but looks a bit odd. UI-Test.py: #!/usr/bin/python # -*- coding: utf-8 -*- import sys # Kivy imports: import kivy from kivy.app import App from kivy.uix import popup from kivy.uix.widget import Widget from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty from kivy.uix.tabbedpanel import TabbedPanel VersionString = "DRAFT" AppName = 'UI-Test' def CloseProgram(Message, Level): print('Closing, level {} ({})'.format(Level, Message)) sys.exit() def OnClosing(self): print('Closing...') # ToDo: call popup def init(): print('Starting {} Version {}.'.format(AppName, VersionString)) print('You are using Python version: {}'.format(sys.version)) class TestApp(App): title = AppName + ' ' + VersionString def on_pause(self): return True def quit_app(self,btn): CloseProgram('Normal Closing', 'Debug') class Pop(BoxLayout): def __init__(self, **kwargs): super(Pop, self).__init__(**kwargs) self.up() def callback(instance): if instance.id == 'quit': TestApp.quit_app(TestApp, 1) def up(self): print('popup') qbutton = Button(text='Quit', id='quit') abutton = Button(text='Return to Program', id='return') blayout = BoxLayout() blayout.add_widget(qbutton) blayout.add_widget(abutton) self.popup = kivy.uix.popup.Popup(title='Quit Program?', content=blayout, size_hint=(None, None), size=(400, 400)) abut…
accepted answer: http://stackoverflow.com/a/51561221
has comment: http://stackoverflow.com/comment/90088308
score: 0
answer count: 1
has title: Python Kivy: bind a command inside popup executes command
has comment: http://stackoverflow.com/comment/90088243

odoo
tags question: http://stackoverflow.com/q/51491217
tags question: http://stackoverflow.com/q/51530507
tags question: http://stackoverflow.com/q/51493106
tags question: http://stackoverflow.com/q/51518500
tags question: http://stackoverflow.com/q/51523212
tags question: http://stackoverflow.com/q/51602049
tags question: http://stackoverflow.com/q/51626461
tags question: http://stackoverflow.com/q/51483896
tags question: http://stackoverflow.com/q/51564243
tags question: http://stackoverflow.com/q/51535808
tags question: http://stackoverflow.com/q/51580882
type: Tag
tags question: http://stackoverflow.com/q/51612811
tags question: http://stackoverflow.com/q/51620113
tags question: http://stackoverflow.com/q/51504133
tags question: http://stackoverflow.com/q/51555312
tags question: http://stackoverflow.com/q/51630239
tags question: http://stackoverflow.com/q/51595334
tags question: http://stackoverflow.com/q/51613748
tags question: http://stackoverflow.com/q/51557048
tag name: odoo
tags question: http://stackoverflow.com/q/51605392

http://stackoverflow.com/q/51552229
has comment: http://stackoverflow.com/comment/90072074
tagged with: python
tagged with: python-3.x
tagged with: geometry
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90072729
tagged with: plot
has body: For a cylinder (or a cylinder-like object) with height h and radius r, I have a numpy array A which specifies the cylinder's 6 degrees of motion in 3D space (translation along x, y, z axes &amp; rotation about x, y, z axes) in time. I would like to create animation for the cylinder using A, and to be able to save it as a video file. The following code is where I got so far. Is there any way to achieve what my code already does in a faster, more efficient way? Also, how can I add to or modify my code to save the animation as video file? # My Animation Code import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection def RotZ(x): return np.array([[np.cos(x), -np.sin(x), 0, 0], [np.sin(x), np.cos(x), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) def RotY(x): return np.array([[np.cos(x), 0, np.sin(x), 0], [0, 1, 0, 0], [-np.sin(x), 0, np.cos(x), 0], [0, 0, 0, 1]]) def RotX(x): return np.array([[1, 0, 0, 0], [0, np.cos(x), -np.sin(x), 0], [0, np.sin(x), np.cos(x), 0], [0, 0, 0, 1]]) def Trans(x,y,z): return np.array([[1, 0, 0, x], [0, 1, 0, y], [0, 0, 1, z], [0, 0, 0, 1]]) # Translation and Rotation Matrix in 3D space def Matrix_Transform(x, y, z, qx, qy, qz): return np.matmul(np.matmul(np.matmul(Trans(x,y,z), RotX(qx)), RotY(qy)), RotZ(qz)) # Translate and Rotate in 3D space def Transform(Obj, Transform_Matrix): transformed_vertex = np.zeros((3,len(Obj.vertex))) # array initialization for i in range(0, len(Obj.vertex)): arr = np.append(Obj.vertex[i],0) vertex_rotated = np.matmul(Transform_Matrix, arr) vertex_rotated_translated = vertex_rotated + Transform_Matrix[:,3] transformed_vertex[:,i] = vertex_rotated_translated[:3] return transformed_vertex class AniObj: def __init__(self, r, h): self.vertex = np.array([[r , 0 , -h/2], [r*np.cos(2 *np.pi/8), r*np.sin(2 *np.pi/8), -h/2], [r*np.cos(4 *np.pi/8), r*np.sin(4 *np.pi/8), -h/2], [r*np.cos(6 *np.pi/8), r*np.sin(6 *np.pi/8), -h/2], [r*np.cos(8 *np.…
has comment: http://stackoverflow.com/comment/90072461
tagged with: matplotlib
type: Question
has title: What is the most efficient way to make a 3D animation of moving cylinder in Python?
has comment: http://stackoverflow.com/comment/90072814
has comment: http://stackoverflow.com/comment/90072598
score: 0

http://stackoverflow.com/comment/90087738
type: Comment
has text: a database is what you want to use for this type of problem ...
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51560417

http://stackoverflow.com/comment/90240581
score: 0
comment on: http://stackoverflow.com/q/51633309
type: Comment
type: QuestionComment
has text: I'll experiment with nested loops

http://stackoverflow.com/q/51539844
has comment: http://stackoverflow.com/comment/90052120
favorite count: 0
has comment: http://stackoverflow.com/comment/90053922
has comment: http://stackoverflow.com/comment/90055836
type: UnansweredQuestion
has title: Cython realloc error: incorrect checksum for freed object
tagged with: python
has comment: http://stackoverflow.com/comment/90051697
upvote count: 2
score: 1
tagged with: malloc
tagged with: cython
has answer: http://stackoverflow.com/a/52476994
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/13970091
has comment: http://stackoverflow.com/comment/90055633
has body: I have been using cython for some time now without any problem. I make extensive use of malloc functions in most modules of my project, yet in this particular module realloc fails me in a strange way. Here is the faulty function: cdef MeshFace* addFace(self, cVector* p1, cVector* p2, cVector* p3, cVector* normal): cdef cVector* pts[3] cdef MeshFace* f = NULL cdef void* ptr = NULL pts[0] = p1 pts[1] = p2 pts[2] = p3 if(self._facenum >= self._facemem - 2): self._facemem = &lt;int&gt;(&lt;double&gt;self._facemem*1.25) ptr = realloc(self._faceList, self._facemem*sizeof(MeshFace)) if ptr == NULL: return NULL self._faceList = ptr f = &self._faceList[self._facenum] MFace_init2(f, &pts[0], 3, NULL) self._facenum += 1 This function gets called multiple times to add faces to the mesh. Yet when the "facenum" values reaches somewhere around 600, python raises a memory error: error for object 0x100bef800: incorrect checksum for freed object - object was probably modified after being freed. Other places I do use malloc without ANY problem. BTW: I run the program on a MacBook Pro (8GB RAM) What am I doing wrong? NB: the variable "_faceList" is initialized further up in the code using a malloc on 512 unit of struct MeshFace
answer count: 2
has answer: http://stackoverflow.com/a/51546263

http://stackoverflow.com/a/51498582
answers question: http://stackoverflow.com/q/51498521
accepted answer of: http://stackoverflow.com/q/51498521
has body: Edit: As explained by @Mr.T, itertools is a C library. This means that calling itertools.permutations first, then filtering may be faster than implementing your own "optimized" function in python. Ideally, you'd implement your "optimized" function in C, and call it from python. For the sake of completeness, here's an equivalent source code from itertools that you can modify according to your needs : def permutations(iterable, r=None): # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC # permutations(range(3)) --> 012 021 102 120 201 210 pool = tuple(iterable) n = len(pool) r = n if r is None else r if r > n: return indices = list(range(n)) cycles = list(range(n, n-r, -1)) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return Details : https://docs.python.org/3/library/itertools.html#itertools.permutations If you feel like implementing C code and using it in python : Any code that we write using any compiled language like C, C++, or Java can be integrated or imported into Python. This code is considered as an “extension.” A Python extension module is nothing more than a normal C library. On Unix machines, these libraries usually end in .so (for shared object). On Windows machines, you typically see .dll (for dynamically linked library). details : https://medium.com/practo-engineering/execute-python-code-at-the-speed-of-c-extending-python-93e081b53f04
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/90086175
has text: install https://pypi.org/project/pyqt5-tools/
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51559628
score: 0

http://stackoverflow.com/a/51507427
score: 1
downvote count: 0
type: Answer
has body: I don't think it's likely at all that pygame could miss a key event. I think the problem is that you're not setting isJumping to false anywhere, which stops the changing of yChange forever after the first press. If I'm interpreting this correctly, the following code should work: if event.type == pygame.KEYDOWN: ... # Your other code if event.key == pygame.K_UP and not isJumping: # "== False" is not necessary yChange -= 10 isJumping = True if event.type == pygame.KEYUP: ... # Your other code if event.key == pygame.K_UP and isJumping: yChange = 0 isJumping = False # &lt;-- This is the addition to the code One thing to keep in mind is that this jumping system won't look very natural. Look to @SamHolloway's answer for more clarification on this.
upvote count: 1
answers question: http://stackoverflow.com/q/51507113

http://stackoverflow.com/comment/90049678
comment on: http://stackoverflow.com/q/51540800
score: 0
has text: Are you sure that `favicon.ico` is getting called in the first place? I'd try placing a debug-print statement there, and trying to ping it with a web browser - maybe use the dev console of the browser, as well, to figure out the root of the problem.
type: Comment
type: QuestionComment

jpype
tag name: jpype
tags question: http://stackoverflow.com/q/51505655
type: Tag
tags question: http://stackoverflow.com/q/51515222

http://stackoverflow.com/a/51496541
has body: Use dropna for remove NaNs rows and then left join with merge: df1 = df.dropna(subset=['prsn_id']) #if possible duplicates #df1 = df.dropna(subset=['prsn_id']).drop_duplicates(['ID','name', 'surname']) df = df.drop('prsn_id', axis=1).merge(df1, on=['ID','name', 'surname'], how='left') print (df) ID name surname prsn_id 0 A john smith prsn_01 1 A john smith prsn_01 2 A john smith prsn_01 3 A john smith prsn_01 4 B mary jane prsn_02 5 B mary jane prsn_02 6 B mary jane prsn_02 7 B mary jane prsn_02 8 B mary jane prsn_02 9 B mary jane prsn_02 10 B mary jane prsn_02 11 C Barry willis prsn_03 12 C Barry willis prsn_03 13 C Barry willis prsn_03 14 C Barry willis prsn_03 15 C Barry willis prsn_03 Detail: print (df1) ID name surname prsn_id 0 A john smith prsn_01 4 B mary jane prsn_02 11 C Barry willis prsn_03
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51496429
upvote count: 2
answers question: http://stackoverflow.com/q/51496429
type: Answer

http://stackoverflow.com/comment/90201824
has text: i am getting error mdf = mdf.loc[mdf.first <= mdf.last] in this function that is key error true.
type: Comment
comment on: http://stackoverflow.com/a/51600796
score: 0
type: AnswerComment

http://stackoverflow.com/q/51611500
has comment: http://stackoverflow.com/comment/90188256
has answer: http://stackoverflow.com/a/51611702
accepted answer: http://stackoverflow.com/a/51611702
has comment: http://stackoverflow.com/comment/90188484
has comment: http://stackoverflow.com/comment/90188614
has comment: http://stackoverflow.com/comment/90187737
tagged with: slurp
has answer: http://stackoverflow.com/a/51643048
favorite count: 0
has title: how to make my json formatted using python
has answer: http://stackoverflow.com/a/51628561
tagged with: python
has comment: http://stackoverflow.com/comment/90188267
has answer: http://stackoverflow.com/a/51626870
has comment: http://stackoverflow.com/comment/90188617
answer count: 4
type: AnsweredQuestion
has body: i have json that looks like this: { "message": ".replace(commentRegExp, '')", "report_id": 1961272 }{ "message": ".replace(currDirRegExp, '')", "report_id": 1961269 }{ "message": ".replace(jsSuffixRegExp, '');", "report_id": 1961270 } how to make it into correct format using python i want the json data to look like this: [ { "message": ".replace(commentRegExp, '')", "report_id": 1961272 }, { "message": ".replace(currDirRegExp, '')", "report_id": 1961269 }, { "message": ".replace(jsSuffixRegExp, '');", "report_id": 1961270 } ]
downvote count: 2
tagged with: stream
has comment: http://stackoverflow.com/comment/90188187
upvote count: 1
type: Question
tagged with: http://stackoverflow.com/tag/json
score: -1
tagged with: formatting
possible better answer: http://stackoverflow.com/a/51626870

http://stackoverflow.com/a/70283539
upvote count: 1
has body: dataclass-wizard is a modern option that can alternatively work for you. It supports complex types such as date and time, generics from the typing module, and a nested dataclass structure. Other "nice to have" features such as implicit key casing transforms - i.e. camelCase and TitleCase, which are quite common in API responses - are likewise supported out of box. The "new style" annotations introduced in PEPs 585 and 604 can be ported back to Python 3.7 via a __future__ import as shown below. from __future__ import annotations from dataclasses import dataclass from dataclass_wizard import fromdict, asdict, DumpMeta @dataclass class Two: f_three: str | None f_four: list[One] @dataclass class One: f_one: int f_two: str data = {'f_three': 'three', 'f_four': [{'f_one': 1, 'f_two': 'two'}, {'f_one': '2', 'f_two': 'something else'}]} two = fromdict(Two, data) print(two) # setup key transform for serialization (default is camelCase) DumpMeta(key_transform='SNAKE').bind_to(Two) my_dict = asdict(two) print(my_dict) Output: Two(f_three='three', f_four=[One(f_one=1, f_two='two'), One(f_one=2, f_two='something else')]) {'f_three': 'three', 'f_four': [{'f_one': 1, 'f_two': 'two'}, {'f_one': 2, 'f_two': 'something else'}]} You can install Dataclass Wizard via pip: $ pip install dataclass-wizard
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51564841
type: Answer
has comment: http://stackoverflow.com/comment/130183925

http://stackoverflow.com/q/51521794
upvote count: 1
downvote count: 1
type: Question
score: 0
has answer: http://stackoverflow.com/a/51522225
has body: I am trying to add command line options to program. The program should accept both a list of numbers, and parse options. For instance a call to the program could look like: python3 ./parsetest.py 4 3 v=100 The 4 and the 3 will be processed in one way whereas the v=100 command will set the internal variable v to 100. I found the getopt library is supposed to have this functionality: http://stackabuse.com/command-line-arguments-in-python/ Is there a better/simpler way to do this? When I try to parse the input like the above, I believe getopt should place arguments which trigger its keywords into a special list, and those which do not trigger are placed elsewhere. However, when I try to use getopt following the example above, no matter what I do, the v=100 option does not appear to trigger the special arguments list. When passed to getopt, I expected the 'v=100' string to be split up into argument v and value 100. For instance, the print(arguments,values) command below results in: [] ['4', '3', 'v=100']. There are values, but there are no arguments. Here is my code: import sys,getopt v = 1e100 fullCmdArguments = sys.argv argumentList = fullCmdArguments[1:] unixOptions = "v:" gnuOptions = ["v="] print(argumentList) try: arguments, values = getopt.getopt(argumentList, unixOptions, gnuOptions) except getopt.error as err: # output error, and return with an error code print (str(err)) sys.exit(2) print(arguments, values) for currentArgument, currentValue in arguments: print (currentArgument, currentValue) if currentArgument in ("-v", "v"): v = currentValue else: #Its an integer then, do something with it print()
answer count: 1
has comment: http://stackoverflow.com/comment/90013110
favorite count: 0
has comment: http://stackoverflow.com/comment/90013148
has title: Python parse numbers and options with getopt
tagged with: python
has comment: http://stackoverflow.com/comment/90013156
tagged with: getopt
accepted answer: http://stackoverflow.com/a/51522225
type: AnsweredQuestion

http://stackoverflow.com/comment/90106806
has text: I see.. smart... !
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51570329
type: Comment

http://stackoverflow.com/a/51549419
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51549363
has body: What is happening is that NumPy is calling high quality numerical libraries (BLAS for instance) which are very good at vector arithmetic. I imagine you could specifically call the exact libraries used by NumPy, however, NumPy would likely know best which to use.
downvote count: 0

http://stackoverflow.com/q/51564071
score: 1
has body: I'm new in Python, and didn't find a similar previous question here. My question is how can I see the real contents of the list node_list here, instead the memory address?? (which actually includes node1, node2 names and its neighbors) class node: def __init__(self, name): self.name=name self.neighbors={} def update(self, name, weight): if name in self.neighbors: self.neighbors[name]=max(int(weight),int(self.neighbors[name])) elif self.name==str(name): print ("this is prohibited to add a key name as an existed name") else: self.neighbors[name] = str(weight) node_list = [] node1 = node('1') node_list.append(node1) node1.update('2',10) node1.update('4',20) node1.update('5',20) node2 = node('2') node_list.append(node2) node2.update('3',5) node2.update('4',10) print(node1.name) # That's OK - prints: 1 print(node1.neighbors) # That's OK - prints: {'2': '10', '4': '20', '5': '20'} print(node_list) # Not OK: prints:[&lt;__main__.node object at 0x7f572f860860&gt;, &lt;__main__.node object at 0x7f572f860dd8&gt;]
upvote count: 1
type: Question
tagged with: object
has answer: http://stackoverflow.com/a/51564134
tagged with: class
has title: Python - How to print a list's contents that have class objects inside?
downvote count: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/1535327
type: UnansweredQuestion
tagged with: python
tagged with: list
tagged with: oop

http://stackoverflow.com/a/51567669
answers question: http://stackoverflow.com/q/51567648
type: Answer
has comment: http://stackoverflow.com/comment/90103701
has body: I assume you have a directory structure: app/update_handler.py and get_updates inside update_handler.py file In case yes, then you need to add __init__.py file inside app directory as well.
score: 0
has comment: http://stackoverflow.com/comment/90101763

http://stackoverflow.com/comment/89940847
comment on: http://stackoverflow.com/a/51485188
type: Comment
has text: Hello, I am getting this error when running the code. Will update in edit: ValueError: No objects to concatenate
score: 0
type: AnswerComment

http://stackoverflow.com/q/51586625
has answer: http://stackoverflow.com/a/51586754
type: Question
score: 0
has body: So I am trying to build a very basic scraper that pulls information from my server, using that information it creates a link which it then yields a request for, after parsing that, it grabs a single link from the parsed page, uploads it back to the server using a get request. The problem i am encountering is that it will pull info from the server, create a link, and then yield the request, and depending on the response time there (which is unreliably consistent) it will dump out and start over with another get request to the server. The way that my server logic is designed is that it is pulling the next data set that needs worked on, and until a course of action is decided with this data set, it will continuously try to pull it and parse it. I am fairly new to scrapy and in need of assistance. I know that my code is wrong but I haven't been able to come up with another method of approach without changing a lot of server code and creating unnecessary hassle, and I am not super savvy with scrapy, or python unfortunately My start requests method: name = "scrapelevelone" start_urls = [] def start_requests(self): print("Start Requests is initiatied") while True: print("Were looping") r = requests.get('serverlink.com') print("Sent request") pprint(r.text) print("This is the request response text") print("Now try to create json object: ") try: personObject = json.loads(r.text) print("Made json object: ") pprint(personObject) info = "streetaddress=" + '+'.join(personObject['address1'].split(" ")) + "&amp;citystatezip=" + '+'.join(personObject['city'].split(" ")) + ",%20" + personObject['state'] + "%20" + personObject['postalcodeextended'] nextPage = "https://www.webpage.com/?" + info print("Creating info") newRequest = scrapy.Request(nextPage, self.parse) newRequest.meta['item'] = personObject print("Yielding request") yield newRequest except Exception: print("Reach JSON exception") time.sleep(10) And everytime the parse function gets called it does all the logic, creates a…
accepted answer: http://stackoverflow.com/a/51586754
answer count: 1
tagged with: while-loop
tagged with: python
has title: Scraper getting stuck in request loop
tagged with: request
tagged with: scrapy
type: AnsweredQuestion

http://stackoverflow.com/comment/90171654
has text: Great. Happy to help.
comment on: http://stackoverflow.com/a/51601084
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90221268
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51628258
score: 0
has text: Have had any success without using `path_to_file` and hard coding in the source?

http://stackoverflow.com/comment/90230911
comment on: http://stackoverflow.com/a/51633095
type: Comment
has text: exist a possibility to get the number of items in array, for example I want the number of sub arrays with data_type = "s", in my case, the count = 2 ?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90091665
type: Comment
type: QuestionComment
has text: How did you load the picture into `mongodb` in the first place?
comment on: http://stackoverflow.com/q/51562015
score: 0

http://stackoverflow.com/comment/90141838
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51585285
has text: I can't reproduce the error. Try to run the program from the command-line. And please post the complete traceback (error message).

http://stackoverflow.com/a/51618715
answers question: http://stackoverflow.com/q/51618323
has comment: http://stackoverflow.com/comment/90282661
has body: I could not recreate your issue. The below code is works fine, sorts the given bunch of numbers correctly and writes to file. Also you are sorting array twice, I just corrected it. values = [] sorted_values = [] data = 1 while data: data = input('Enter the values. Press enter to confirm values:') if data: values.append(data) else: data = data # here you are sorted it first and second outside of while loop sorted_values = sorted(values) print(sorted_values) print(sorted_values) with open("sortedvalues.txt", "a+") as name: name.write('\n' + str(sorted_values)) with open("sortedvalues.txt", "r") as open1: print('reading') print (open1.read()) inputs: 5 3 4 2 1 0 inside file: [1, 2, 3, 4, 5]
has comment: http://stackoverflow.com/comment/90385387
has comment: http://stackoverflow.com/comment/90281297
has comment: http://stackoverflow.com/comment/90281349
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90312236

http://stackoverflow.com/q/51626943
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: python
has body: I am trying to impute missing values in one of the columns in my dataset using the 'loc' function of Panda library but the code is not executing successfully. The line of code is as below. # Impute missing data by mean weight of each sub-category in 'Item_Weight' column data.loc[miss_bool,'Item_Weight'] = data.loc[miss_bool,'Item_Identifier'].apply(lambda x: item_avg_weight[x]) The error that is being generated is as follows, data.loc[miss_bool,'Item_Weight'] = data.loc[miss_bool,'Item_Identifier'].apply(lambda x: item_avg_weight[x]) Traceback (most recent call last): File "&lt;ipython-input-3-168be6231060&gt;", line 1, in &lt;module&gt; data.loc[miss_bool,'Item_Weight'] = data.loc[miss_bool,'Item_Identifier'].apply(lambda x: item_avg_weight[x]) File "C:\Users\Arnab\Anaconda3\lib\site-packages\pandas\core\series.py", line 3192, in apply mapped = lib.map_infer(values, f, convert=convert_dtype) File "pandas/_libs/src\inference.pyx", line 1472, in pandas._libs.lib.map_infer File "&lt;ipython-input-3-168be6231060&gt;", line 1, in &lt;lambda&gt; data.loc[miss_bool,'Item_Weight'] = data.loc[miss_bool,'Item_Identifier'].apply(lambda x: item_avg_weight[x]) File "C:\Users\Arnab\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2685, in __getitem__ return self._getitem_column(key) File "C:\Users\Arnab\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2692, in _getitem_column return self._get_item_cache(key) File "C:\Users\Arnab\Anaconda3\lib\site-packages\pandas\core\generic.py", line 2486, in _get_item_cache values = self._data.get(item) File "C:\Users\Arnab\Anaconda3\lib\site-packages\pandas\core\internals.py", line 4115, in get loc = self.items.get_loc(item) File "C:\Users\Arnab\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3065, in get_loc return self._engine.get_loc(self._maybe_cast_indexer(key)) File "pandas\_libs\index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\index.pyx", line 162, in pandas._libs.index.In…
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/60826617
tagged with: machine-learning
upvote count: 1
has answer: http://stackoverflow.com/a/61215020
type: Question
has comment: http://stackoverflow.com/comment/90222762
has title: Error while trying to impute missing values using Panda's 'loc' functionin Python
answer count: 2
has comment: http://stackoverflow.com/comment/90221990

http://stackoverflow.com/a/51632164
has comment: http://stackoverflow.com/comment/90233285
upvote count: 5
answers question: http://stackoverflow.com/q/51632003
score: 5
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90229339
has comment: http://stackoverflow.com/comment/90229280
has body: You do not need this line json_obj = json.loads(r) . r.json() returns you a json response. Ex: json_obj = r.json() for ord in json_obj["order"]: print("id:", ord["id"]) print("status_id:", ord["status_order_id"]) print('---') cursor.execute("INSERT INTO table_test (id, status_order_id, customer_id) VALUES (%s,%s,%s)", (ord["id"], ord["status_order_id"], ord["customer_id"])) #close the connection to the database. mydb.commit() cursor.close()

http://stackoverflow.com/q/51519133
duplicate of: http://stackoverflow.com/q/27152904
has answer: http://stackoverflow.com/a/51519872
has comment: http://stackoverflow.com/comment/90007494
has body: I have this code: import cv2 from matplotlib import pyplot as plt import numpy as np img = cv2.imread('forklift2.jpg') A = cv2.rectangle(img, (180, 90), (352, 275), (255,0,0), 2) B = cv2.rectangle(img, (100, 220), (300, 275), (155,122,100), 2) cv2.imshow('Object detector', img) cv2.waitKey(0) cv2.destroyAllWindows() I need to detect the intersection beetween the 2 rectangle A &amp; B like as swown in the picture: So I need to have a boolean variable that should be true if the 2 rectangles have some common area. How can I do that?
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90008830
favorite count: 0
has comment: http://stackoverflow.com/comment/90009545
linked to: http://stackoverflow.com/q/27152904
type: UnansweredQuestion
tagged with: python
has title: OpenCV - Python - detect object inside a rectangle
has comment: http://stackoverflow.com/comment/90008150
downvote count: 0
score: 1
type: Question
tagged with: opencv3.0

http://stackoverflow.com/comment/90129031
type: QuestionComment
has text: *"And I can say myObject.x which will be 5."* No you can't. You're thinking of JavaScript. (Though I guess in JS you'd have to omit the quotation marks around the keys.)
comment on: http://stackoverflow.com/q/51581886
score: 7
type: Comment

http://stackoverflow.com/comment/90130933
score: 1
has text: @G.LC I don't think it's incorrect to say it's underfitting. The fact that both sets have such poor scores overshadows the fact that they are 1% apart. There is probably a model that fits the data better
type: AnswerComment
comment on: http://stackoverflow.com/a/51582794
type: Comment

http://stackoverflow.com/q/51569216
has comment: http://stackoverflow.com/comment/90104838
has comment: http://stackoverflow.com/comment/90104578
tagged with: python
favorite count: 0
has body: My questions are: How can I stop the program when it detects a randomly chosen class from 'CLASSES' using 'CLASSES_RANDOM' (by generating a random index with randint) How do I make a function that detects that the program is running? Code: #hoangAI #DIKY STACKOVERFLOW JSEM SE NAUCIL OOP V PYTHONU DIKY &lt;3 #TENTO SCRIPT JE PRO DETEKCI OBJEKTU SPECIFIKOVANYCH V CLASSES[] #omlouvam se za anglicke nazvy promennych, prislo mi blby to jmenovat cesky # importujeme vsechny potrebne knihovny(dekuji moc stackoverflow :3) from imutils.video import VideoStream from imutils.video import FPS import numpy as np import argparse import imutils import time import cv2 import random #prikazove argumenty ap = argparse.ArgumentParser() ap.add_argument("-p", "--prototxt", required=True, help="pridej k argumentu -p path k prototxt souboru") ap.add_argument("-m", "--model", required=True, help="pridej path k trenovacimu modelu") ap.add_argument("-c", "--confidence", type=float, default=0.2, help="minimalni sance (na odstraneni tzv slabych detekci") args = vars(ap.parse_args()) #"nacteni" hoangAI :D print("Loading hoangAI(TM) V.1.0.0") time.sleep(2.0) # nacteme si list stitku veci, ktere byly pouzity pri detekcnim treningu hoangAI, a pak nahodne vybereme barvu pro objektove ramecky CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"] CLASSES_RANDOM = CLASSES[random.randint(0,len(CLASSES) - 1)] print("vygoogli si" + CLASSES_RANDOM) COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3)) # nacteme si serializovany model caffe print("[INFO] nacitani modelu...") net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"]) # zacatek video snimani # a take zacneme pocitat fps print("[INFO] video snimani zacina...TED") vs = VideoStream(src=0).start() time.sleep(2.0) fps = FPS().start() # cyklus/smycka pres ramecek vystupu vide…
has answer: http://stackoverflow.com/a/51569391
has comment: http://stackoverflow.com/comment/90107194
downvote count: 2
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90104629
type: Question
accepted answer: http://stackoverflow.com/a/51569391
upvote count: 0
score: -2
answer count: 1
tagged with: caffe
has title: How do i make this program stop if it detects a randomly generated class?

azure-virtual-machine
tags question: http://stackoverflow.com/q/51617438
tags question: http://stackoverflow.com/q/51546073
tags question: http://stackoverflow.com/q/51564708
type: Tag
tag name: azure-virtual-machine
tags question: http://stackoverflow.com/q/51599828

http://stackoverflow.com/q/51523618
tagged with: server
has body: I am trying to call a POST API that would schedule a recording for a TV channel. The call works on SoapUI, but I can't seem to replicate the success in python (I can check whether it succeeds or not by checking my TV if a recording is scheduled). Here is the call in SoapUI: 1 2 3 Here is the call in Python (using pydev): print("Record") url1 = "http://10.10.120.48:8080/api/CreateRecordSchedule" { "type": "SERIES_PROGRAM", "matchingID": "SH00000000131221", "channelID": 11, "padIn": 0, "padOut": 0, "persistedRecordings": 5, "hd": False, "rerun": True } rsp = s.post(url1) print (rsp.status_code) Other api calls with the same server work fine, so I was wondering what I am doing wrong. Thank you!
score: 0
tagged with: api
answer count: 1
tagged with: soapui
type: UnansweredQuestion
tagged with: python
has title: Performing SoapUI API Calls with Python
tagged with: python-requests
has answer: http://stackoverflow.com/a/51737913
type: Question

http://stackoverflow.com/comment/90222313
type: Comment
has text: Also a switch between `not_compat_options` and `not_comp_options`.
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/51629021

http://stackoverflow.com/a/51561156
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51557531
accepted answer of: http://stackoverflow.com/q/51557531
upvote count: 1
has body: You can use re.findall(r"(?ms) see below"): (1) "^[\w.]+\s\((\d+-\d+)\)" matches the ID, from start of a line; (3) "(Anticodon:.+?)$" matches from "Anticodon" until the line end, '^' and '$' match not only the start/end of the string but each line start/end, too, according the 'm' in (?ms); (2) ".+?" matches anything from the end of the ID to the "Anticodon", and . matches new line, too, according to 's' in "(?ms)". You can assemble the expression:-)
score: 1

http://stackoverflow.com/q/51528266
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51528570
score: 0
upvote count: 1
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/9627686
has title: converting time data which is saved as a string to an integer in seconds
tagged with: matplotlib
duplicate of: http://stackoverflow.com/q/9627686
tagged with: numpy
answer count: 1
has body: I have some time data that I read into a numpy array as a string. It's in the format x = ['11:13:01.337 AM', '11:13:03.337 AM', '11:13:05.337 AM'] I want to be able to plot this cleanly over an indefinite amount of time, let's say the data goes for 4 hours. How can I convert this into a reasonable form to plot? I am not sure what form would be best so suggestions would be helpful. As you can probably tell I'm a noob, my boss and I appreciate the help!
favorite count: 0

http://stackoverflow.com/q/51484970
has answer: http://stackoverflow.com/a/51485188
accepted answer: http://stackoverflow.com/a/51485188
favorite count: 0
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
score: 2
has title: Do you have to create dummy variables for ordinal variables? Also getting error with conversion
downvote count: 0
has body: For the dataset that I am working with, the categorical variables are ordinal, ranging from 1 to 5 for three columns. I am going to be feeding this into XGBoost. Would I be okay to just run this command and skip creating dummy variables: ser = pd.Series([1, 2, 3], dtype='category') ser = ser.to_frame() ser = ser.T I would like to know conceptually, since the categorical data is ordinal, would simply converting that to type category be adequate for the model? I tried creating dummy variables but all the values become a 1. As for the code now, it runs but this command returns: 'numpy.int64'. type(ser[0][0]) Am I going about this correctly? Any help would be great! Edit: updated code Edit2: Normalizing the numerical data values. Is this logic correct?: r = [1, 2, 3, 100 ,200] scaler = preprocessing.StandardScaler() r = preprocessing.scale(r) r = pd.Series(r) r = r.to_frame() r = r.T Edit3: This is the dataset.
type: Question
upvote count: 2
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/135340557
comment on: http://stackoverflow.com/a/51643134
type: AnswerComment
score: 0
type: Comment
has text: Using FastAPI, I noticed that catching the `Warning` object and printing it, would only print `Scope has changed from... etc.`, while using `jsonable_encoder` returns the whole credentials object, with old and new scopes. So I ended up catching the `Warning`, returning the json encoded warning as a response. I'm guessing that's how they intended it to work?

http://stackoverflow.com/q/51580727
downvote count: 1
type: Question
answer count: 1
tagged with: http://stackoverflow.com/tag/r
score: 0
has title: Count rows dynamically based on some criteria in R/python
has answer: http://stackoverflow.com/a/51580854
tagged with: python
has comment: http://stackoverflow.com/comment/90127351
has comment: http://stackoverflow.com/comment/90127732
favorite count: 0
tagged with: dynamic
has body: I have a Dataset with 2.5 million data with the following sample data. id status count webiste source 1 True 0 www.test.com Accurate 2 True 1 www.true.com Need Test 3 False 2 Null Accurate 4 False 100 Null Need Test id - unique value Status - True/False Count - 0-10000 Webiste - contains url else null source - Accurate / Need to be tested It also other columns with number range from 0-1000 and so. I want to show the options of slider for number columns and dropdown for other columns to the user. I want to select count of subset of data with the specifications from user. Eg : count with Status as True and contains website and contains website. These specifications will be given by user. These need to be done in R or python?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90127157
upvote count: 1

http://stackoverflow.com/a/51488990
answers question: http://stackoverflow.com/q/51487797
score: 8
downvote count: 0
has comment: http://stackoverflow.com/comment/103161786
upvote count: 8
type: AcceptedAnswer
has body: I managed to group the duplicate UserApns into the following queryset: UserApn.objects.all().difference(UserApn.objects.distinct('user', 'player_id')) Note that passing multiple arguments to distinct() only works on PostgreSQL.
accepted answer of: http://stackoverflow.com/q/51487797
type: Answer

http://stackoverflow.com/q/51601249
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/51600485
has comment: http://stackoverflow.com/comment/90169873
tagged with: python
has comment: http://stackoverflow.com/comment/90168873
linked to: http://stackoverflow.com/q/1207406
type: AnsweredQuestion
score: 3
has body: When answering this question, I came across something I never thought about in Python (pointed by a user). Basically, I already know (here's an interesting thread about it) that I have to make a copy when iterating while mutating a list in Python in order to avoid strange behaviors. Now, my question is, is using enumerate overcoming that problem ? test_list = [1,2,3,4] for index,item in enumerate(test_list): if item == 1: test_list.pop(index) Would this code be considered safe or I should use, for index,item in enumerate(test_list[:]):
possible better answer: http://stackoverflow.com/a/51601630
tagged with: list
has title: Should I create a copy when iterating over a list using enumerate in Python
has comment: http://stackoverflow.com/comment/90168830
has answer: http://stackoverflow.com/a/51601650
upvote count: 3
has answer: http://stackoverflow.com/a/51601630
linked to: http://stackoverflow.com/q/38546951
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90169185
has comment: http://stackoverflow.com/comment/90169774
tagged with: iteration
accepted answer: http://stackoverflow.com/a/51601650

http://stackoverflow.com/comment/123166652
type: AnswerComment
comment on: http://stackoverflow.com/a/52242947
type: Comment
has text: This blocks time updates in the progress bar, is there a way to fix it?
score: 0

http://stackoverflow.com/comment/90222781
comment on: http://stackoverflow.com/q/51629256
score: 0
type: Comment
type: QuestionComment
has text: Please include the code and the error in the question, NOT an image. It really makes it difficult for anyone to reproduce your error. Also, include an example of the dataframe.

http://stackoverflow.com/a/51501604
downvote count: 0
score: 1
has body: Use a list comprehension. Replace the , then convert to float then round that value. [round(float(x.replace(',','.')),2) for x in b] [1.37, 6.98, 3.99]
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51501469

http://stackoverflow.com/comment/90112659
comment on: http://stackoverflow.com/q/51572463
has text: Related: https://stackoverflow.com/a/45390635/2449192 and https://stackoverflow.com/q/51515313/2449192
type: Comment
type: QuestionComment
score: 0

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/51584778
tags question: http://stackoverflow.com/q/51612604
tags question: http://stackoverflow.com/q/51523212
type: Tag

http://stackoverflow.com/comment/90271474
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51634576
has text: gotcha. just tested. `senton` is part of pywintypes and mirrors `SentOn`. it looks like many or maybe all of the object members are replicated, e.g., `m.body` and `m.Body`, etc.
score: 0

http://stackoverflow.com/comment/90068484
has text: I'm not sure how seeing my models will help, but sure.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51550581

http://stackoverflow.com/q/51518103
upvote count: 2
has comment: http://stackoverflow.com/comment/90009354
has title: Seaborn FacetGrid error
answer count: 1
has answer: http://stackoverflow.com/a/51522711
favorite count: 0
has body: Inspired by examples on this page, I would like to make a seaborn facetgrid with the Iris dataset with 6 facets: 3 species x 2 types (petal or sepal). In each facet I need a histogram of length (or width). But the code I tried gives a ValueError: color kwarg must have one color per dataset. Any suggestions how to solve this? import pandas as pd import matplotlib.pyplot as ply import seaborn as sns iris = sns.load_dataset('iris') iris_petal = pd.DataFrame(iris.iloc[:,-3:].values, columns=['length', 'width', 'species']) iris_petal['type'] = 'petal' iris_sepal = pd.DataFrame(iris.iloc[:,[0, 1, -1]].values, columns=['length', 'width', 'species']) iris_sepal['type'] = 'sepal' iris = pd.concat([iris_sepal, iris_petal]) iris.sample(n=10) g = sns.FacetGrid(iris, col="species", row="type") g = g.map(plt.hist, "length", color = 'b')
has comment: http://stackoverflow.com/comment/90013496
tagged with: seaborn
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90007765
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/90011440
accepted answer: http://stackoverflow.com/a/51522711

communication
tag name: communication
tags question: http://stackoverflow.com/q/51543839
type: Tag
tags question: http://stackoverflow.com/q/51590277

http://stackoverflow.com/a/51524289
score: 1
has comment: http://stackoverflow.com/comment/90017651
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90017604
type: Answer
answers question: http://stackoverflow.com/q/51523938
has body: Better Read the image with the 'I'. Like imread('imageName.imgFormat',"I") That will resolve the issue. It will read image in uint8 format, which i think you desire.
accepted answer of: http://stackoverflow.com/q/51523938
has comment: http://stackoverflow.com/comment/90017398
upvote count: 1
has comment: http://stackoverflow.com/comment/90017687

http://stackoverflow.com/comment/90032358
score: 0
comment on: http://stackoverflow.com/q/51531741
type: Comment
type: QuestionComment
has text: I'm not sure what you expect. An external entity cannot produce a list of filenames from a directory. That is not how it works. `file:///home/` is not a file that contains text.

http://stackoverflow.com/a/51634476
has comment: http://stackoverflow.com/comment/90295828
answers question: http://stackoverflow.com/q/51613673
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 6
has body: The MultiPolygon can be directly constructed from a list of polygons. Also, one can directly iterate over the polygons which comprise given multipolygon: from shapely.geometry import Polygon, MultiPolygon P1 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]) P2 = Polygon([(2, 2), (3, 2), (3, 3), (2, 3)]) M = MultiPolygon([P1, P2]) for P in M.geoms: print(P) Now, these two properties enable to use list comprehension in order to filter out only polygons satisfying a certain condition some_condition: M2 = MultiPolygon([P for P in M if some_condition(P)])
upvote count: 6
accepted answer of: http://stackoverflow.com/q/51613673

http://stackoverflow.com/q/51535479
has title: TensorFlow eigenvalues and eigenvectors
has comment: http://stackoverflow.com/comment/90046244
downvote count: 0
has answer: http://stackoverflow.com/a/72557452
has body: I want to use eigenvalues in TensorFlow but it gives wrong eigenvalues/eigenvectors using 'tf.self_adjoint_eig’ In the code below I'm trying to recover the original matrix but the output differs from the original, Any idea, how to fix it? `A11 = tf.constant([[1, 3],[1, 1]], dtype=tf.float32) [e1, W1] = tf.self_adjoint_eig(A11) e1 = tf.diag(e1) A11r = tf.matmul(tf.matmul(W1, e1), tf.matrix_inverse(W1)) A11: [[1. 3.] [1. 1.]] A11r: [[0.9999999 0.9999999] [0.9999999 0.9999999]]`
has comment: http://stackoverflow.com/comment/90067611
tagged with: eigenvalue
tagged with: eigenvector
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90075289
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/121218974
score: 3
upvote count: 3
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/90183170
has text: Can you add an example of what you would expect to get out for a few different inputs?
comment on: http://stackoverflow.com/q/51608846
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51609962
favorite count: 0
score: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/51610164
type: AnsweredQuestion
tagged with: variable-declaration
has answer: http://stackoverflow.com/a/51610114
accepted answer: http://stackoverflow.com/a/51610114
has title: Python best practices: initializing variables
type: Question
has comment: http://stackoverflow.com/comment/90184689
answer count: 2
downvote count: 0
has body: When you have a variable (say, a dict) which is set by a method, what is Python's best practices recommendations: Should I initialise my_var first: my_var = {} my_var = do_something_and_return_var() or set it straight away: my_var = do_something_and_return_var() The advantage of setting it first is that you can tell staight away what type my_var should be (and although I don't use an IDE, I guess it could help when you do). But on the other hand it my seem a bit useless to set it to an emtpy dict right before you set it to it's actual value. Thanks
has answer: http://stackoverflow.com/a/51610164
tagged with: python

http://stackoverflow.com/a/51625799
has body: Create a new list in the __init__ method, which automatically gets called after instantiation.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51625775
type: Answer
downvote count: 0

http://stackoverflow.com/q/51494218
tagged with: matplotlib
score: 0
linked to: http://stackoverflow.com/q/9707676
has title: How to replicate the pseudo 3D plot of gnuplot in matplotlib, for secondary structure assignment of a protein over time?
has answer: http://stackoverflow.com/a/51504619
has comment: http://stackoverflow.com/comment/89960979
answer count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51504619
tagged with: gnuplot
type: Question
has body: I'm trying to replicate a plot, created in gnuplot, using matplotlib. The type of plot used by gnuplot (below) is called a pseudo 3D plot. What this is showing is secondary structure assignment for each residue of a peptide/protein over time. So, at each time step (column) you're seeing the secondary structure assignment for a single peptide. For each residue (row) you're seeing how that residue's secondary structure assignment changes over time. I want to adapt this type of plot to matplotlib. What would be an appropriate type of plot in matplotlib to do this? The most rudimentry solution I could think of was to simply use patches to draw rectangles at the correct coordinates, but I was hoping to use an existing matplotlib plot type that's more flexible and robust to customisation. The data is structured like so: data = [[x1, y1, z11], [x1, y2, z12], [x1, y3, z13], ..., [xn, ym, znm]] Where n is the total number of time steps and m is the total number of residues. Z values are categorical data for secondary structure assignment at the xy coordinates. Some actual data you could use to test this where there is a peptide with three residues over three time steps: data = [[1, 1, 0], [1, 2, 0], [1, 3, 0], [2, 1, 6], [2, 2, 6], [2, 3, 6], [3, 1, 6], [3, 2, 0], [3, 3, 0]]

http://stackoverflow.com/q/51590357
tagged with: ttk
downvote count: 0
has title: Appending values to TTK Combobox['values'] without reloading combobox
possible better answer: http://stackoverflow.com/a/63566278
answer count: 3
has answer: http://stackoverflow.com/a/63566278
accepted answer: http://stackoverflow.com/a/51590472
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/75063491
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: tkinter
has body: I need to add values to a ttk.combobox without reloading the whole thing. The current selection on the GUI should not be reloaded when values are added to it. I need something like this: for string in listofstrings: if string not in self.combobox1['values']: self.combobox1['values'].append(string) When I try it like this, I get this error: AttributeError: 'tuple' object has no attribute 'append' (as expected). Thanks in advance for the help.
upvote count: 3
has answer: http://stackoverflow.com/a/51590472
type: Question

http://stackoverflow.com/comment/90235328
has text: These attributes are inherited from the [`pygame.Rect`](http://www.pygame.org/docs/ref/rect.html) class. Because the `MovingRect` is a subclass of `pygame.Rect`, it has all the attributes and methods of a normal rect.
type: AnswerComment
comment on: http://stackoverflow.com/a/51625757
type: Comment
score: 1

http://stackoverflow.com/comment/90216973
has text: I won't answer "why" since I don't have the expertise. But I can ask: why do you absolutely want to use lambdas? If you need assignments, and lambdas won't let you do it, just define a regular function...
comment on: http://stackoverflow.com/q/51626124
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90025931
has text: Try `//ul[@class="check-list"][3]/li[2]/text()`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51528556
score: 0

http://stackoverflow.com/q/51610821
possible better answer: http://stackoverflow.com/a/51611719
score: 0
has body: I am trying to run PCA on my dataset. I came across a tutorial by Ritchie Ng: https://www.ritchieng.com/machine-learning-project-customer-segments/ and i am trying to recreate it on my dataset. However, the blog uses a package called "renders" which i am unable to find in Anaconda. How and where do i get and enable this package from? I have searched for this package in Anaconda navigator and google but i cant seem to find it.
has answer: http://stackoverflow.com/a/51610883
tagged with: python
tagged with: jupyter
favorite count: 0
type: AnsweredQuestion
tagged with: pca
accepted answer: http://stackoverflow.com/a/51610883
has title: import renders statement throws "No such module" error
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51611719
answer count: 2

http://stackoverflow.com/a/51586462
answers question: http://stackoverflow.com/q/51586364
has comment: http://stackoverflow.com/comment/90138296
has body: See the Returns section in the docs: (N-K+1)-dimensional tensor populated by entries in tensor corresponding to True values in mask. where N is the dimension of src and K is the dimension of mask, when N=K, the return is always 1D, which is your case.
has comment: http://stackoverflow.com/comment/90138248
upvote count: 2
has comment: http://stackoverflow.com/comment/90138280
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90138313
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51586364

http://stackoverflow.com/q/51577228
tagged with: beautifulsoup
score: 0
tagged with: python
tagged with: python-3.x
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/90120020
type: AnsweredQuestion
has title: Using Beautiful Soup find_all() to find only when align=right
type: Question
has answer: http://stackoverflow.com/a/51577858
accepted answer: http://stackoverflow.com/a/51577858
has body: I'm using BeautifulSoup to webscrape. I am trying to gather data from ESPN and save it to a file. Eventually, I want to parse the data so that each stat remains with the player. But every 10 players or so, three extra tags are used which makes it hard to parse the data correctly. When I use find_all i try to use 'td' and then I want to get the data ONLY when align="right" (this is the data I want and removes the three extra tags). However, when I try to add that to the function it does not work. This is the website: url_base = "http://www.espn.com/nhl/statistics/player/_/stat/points/sort/points/year/" + str(yr) + '/count/' This is my code: def player_count(page_nums): player_list = [''] num_start = 1 for i in range(1, page_nums + 1): num_start += 40 player_list.append(num_start) return player_list def num_pages(num_strings): list_ = num_strings.split(" ") return list_[2] year = [] for i in range(2001, 2019): year.append(i) for yr in year: if yr == 2005: continue url_base = "http://www.espn.com/nhl/statistics/player/_/stat/points/sort/points/year/" + str(yr) + '/count/' for i in player_count_list: url = url_base + str(i) print(url) with urlopen(url) as page: html_doc = bS(page, 'html5lib') table_string = html_doc.find_all('td', {'align': 'right'}) print(table_string) new_strings = [] for td in table_string: new_strings.append(td.text) yr_file.append(new_strings) After going through the documentation, it seems as though this should work: html_doc.find_all('td', {'align': 'right'}) But i havent been able to get it.
answer count: 1

http://stackoverflow.com/q/51502959
tagged with: pandas
linked to: http://stackoverflow.com/q/25189575
has comment: http://stackoverflow.com/comment/89976196
score: 9
tagged with: python
has comment: http://stackoverflow.com/comment/89978584
type: AnsweredQuestion
upvote count: 9
has answer: http://stackoverflow.com/a/51505109
tagged with: multi-index
type: Question
linked to: http://stackoverflow.com/q/44610766
answer count: 2
has body: I'm trying to use query on a MultiIndex column. It works on a MultiIndex row, but not the column. Is there a reason for this? The documentation shows examples like the first one below, but it doesn't indicate that it won't work for a MultiIndex column. I know there are other ways to do this, but I'm specifically trying to do it with the query function import numpy as np import pandas as pd df = pd.DataFrame(np.random.random((4,4))) df.index = pd.MultiIndex.from_product([[1,2],['A','B']]) df.index.names = ['RowInd1', 'RowInd2'] # This works print(df.query('RowInd2 in ["A"]')) df = pd.DataFrame(np.random.random((4,4))) df.columns = pd.MultiIndex.from_product([[1,2],['A','B']]) df.columns.names = ['ColInd1', 'ColInd2'] # query on index works, but not on the multiindexed column print(df.query('index &lt; 2')) print(df.query('ColInd2 in ["A"]'))
has title: Python/Pandas - Query a MultiIndex Column
downvote count: 0
duplicate of: http://stackoverflow.com/q/44610766
favorite count: 0
has comment: http://stackoverflow.com/comment/89975345
possible better answer: http://stackoverflow.com/a/51503233
has answer: http://stackoverflow.com/a/51503233
accepted answer: http://stackoverflow.com/a/51505109

http://stackoverflow.com/comment/133903986
type: Comment
comment on: http://stackoverflow.com/a/75909038
has text: Yes, deprecated doesn't mean broken. It just means that it will not receive any further updates. I'm the maintainer of both libraries. I deprecated PyPDF2 after merging the updates to pypdf
score: 4
type: AnswerComment

http://stackoverflow.com/q/51548902
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: series
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/51549151
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has title: Using pandas dataframe to write values to a new csv file error
accepted answer: http://stackoverflow.com/a/51549151
has body: import pandas as pd import csv basefileread = pd.read_csv('50.csv', encoding='latin-1') basefilevalue = basefileread.loc[basefileread['Customer'].str.contains("Lam Dep", na=False), 'Jul-18\nQty'] basefilevalue.to_csv('data.csv', sep='\t') with open('data.csv', 'w') as f: writer = csv.writer(f, delimiter=',') writer.writerows(basefilevalue) So I am running this code to take these specific values out of one csv file, and wish to print it to another. I am however receiving this error: csv.Error: iterable expected, not float The answer posted below helps run my code without error, however no data is printing to my csv file. Is this an issue with my code or something else?

http://stackoverflow.com/q/51607214
score: 0
has body: I'm using PythonDjango with Celery and Redis and I want to catch two erros: The first error OperationalError means the server is down If app.control.inspect().active() is None, the workers are down Functionality: If there is not an OperationalError it should check also app.control.inspect().active() If there is an OperationalError it shouldn't check app.control.inspect().active() because Celery will hang/freeze The Celery task will not work in both cases but just the Redis server down will have an exception Code: if not error: try: send_email_task.delay(subject=subject, ..., html_content=html_content) except OperationalError as e: # do something if not app.control.inspect().active(): # do something else: ...... My issue, if I have an OperationalError the condition if not app.control.inspect().active() will hang the code If I add the code app.control.inspect().active() inside try will hang/freeze, will indefinitely check status if is an OperationalError.
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51607437
tagged with: celery
type: Question
has title: Django - Celery catch(try-except block) errors - issues with freezing/hang code

tcp
type: Tag
tags question: http://stackoverflow.com/q/51483896
tags question: http://stackoverflow.com/q/51590277
tags question: http://stackoverflow.com/q/51592992
tags question: http://stackoverflow.com/q/51527846
tags question: http://stackoverflow.com/q/51549719
tag name: tcp

http://stackoverflow.com/q/51554189
answer count: 1
tagged with: python
has body: Trying to install autologin on macOS 10.13.6 with pip3 install -U --upgrade autologin My Python version: Python 3.5.3 My pip3 version: pip 18.0 from /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip (python 3.5) I should be up to date concerning python and pip so that answers like this or that should not apply to my problem. When I run curl https://bootstrap.pypa.io/get-pip.py | sudo python3 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 1604k 100 1604k 0 0 312k 0 0:00:05 0:00:05 --:--:-- 299k The directory '/Users/xx/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/xx/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting pip Downloading https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3af41213346e5b6c221c9e086a166f3703d2ddaf940/pip-18.0-py2.py3-none-any.whl (1.3MB) 100% |████████████████████████████████| 1.4MB 728kB/s Installing collected packages: pip Found existing installation: pip 18.0 Uninstalling pip-18.0: Successfully uninstalled pip-18.0 Successfully installed pip-18.0 May I have overseen anything? what else can solve the problem?
has answer: http://stackoverflow.com/a/51560398
tagged with: pip
linked to: http://stackoverflow.com/q/49748063
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49768770
has title: still cannot install autologin - TLSV1_ALERT_PROTOCOL_VERSION
tagged with: ssl
accepted answer: http://stackoverflow.com/a/51560398
type: Question
score: 0
tagged with: autologin

http://stackoverflow.com/q/51639563
tagged with: python
tagged with: matlab
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
tagged with: numpy
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51640950
has title: Syntax error when plotting in Matplotlib
score: 0
answer count: 1
has body: I am working on translating some code from Matlab into Python. I am a little bit confused in terms of understanding this Matlab code: plot(m_true(1,[1:p 1]), m_true(2,[1:p 1]),'*', 'Color',[0 0 0]) When I try to translate that into Python it looks something like this: plot(m_true[1,(1:p, 1)], m_true[2,(1:p 1)],'*', 'Color',[0, 0, 0]) The colon causes a syntax error. Can anyone who has plotting experience in Matlab (I am new to this language) explain the matlab syntax (in terms of what the indexing of 1:p is doing) and perhaps how to fix the syntax error? Thanks!
linked to: http://stackoverflow.com/q/49211607
favorite count: 0
accepted answer: http://stackoverflow.com/a/51640950

http://stackoverflow.com/comment/89948556
has text: @Skam Running the code with `print(getMax4([-1, 4]))` returns 4 and not 0
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51489978
type: AnswerComment

http://stackoverflow.com/q/51534912
type: Question
has comment: http://stackoverflow.com/comment/90037934
has title: How to link to Jupyter notebook from a local HTML page
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90042586
has comment: http://stackoverflow.com/comment/90037978
has answer: http://stackoverflow.com/a/51537439
has comment: http://stackoverflow.com/comment/90038322
tagged with: python
accepted answer: http://stackoverflow.com/a/51537439
has body: I am learning Jupyter Notebooks at the moment. Is it possible to link a Jupyter Notebook to an HTML page. For example, say I have an HTML page which is on my computer. Can I use this to link to a Jupyter Notebook, so when the link is clicked it loads the notebook in a viewer to be run? Thanks, BJR
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/90037610
type: AnsweredQuestion

http://stackoverflow.com/comment/90201078
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51578685
has text: Once try with django-ckeditor==5.3.0. Any other package doesn't seem to create an error.
type: AnswerComment

http://stackoverflow.com/comment/90191009
score: 0
has text: @NilsWerner dpkg --get-selections | grep hold is not giving any output.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51611458

http://stackoverflow.com/comment/90145085
has text: I am using ROS Kinetic and my publisher is used only as shown above. Velocities is also an array, and strangely enough, when I cast it as a numpy array, the serialization error gets thrown there, when I make it a list instead, the error gets thrown at the last line as before, and when I take it out completely everything else works. I'm not sure why one numpy array would work but not both.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51561527
score: 0

http://stackoverflow.com/comment/90214877
type: Comment
comment on: http://stackoverflow.com/a/51624934
has text: If this is Python 3, you don't need to explicitly call `sys.stdout.flush()` at all, you can just change the `print` to `print(i, flush=True)` and it will perform both printing and flushing as a single call.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51605570
has body: I'm trying to modify the Advanced Convolutional Neural Networks tutorial of Tensorflow, which originally uses the CIFAR-10 dataset (https://www.tensorflow.org/tutorials/images/deep_cnn) to work with unsigned 16-bit integer data. I would read the data from a binary format, similar to the CIFAR-10 dataset. The original code reads the unsigned 8-bit integer data from a binary format. I managed to create 8-bit samples from my own dataset with various dimensions (the result.depth variable below) and the training worked without any problem. But my own data is an unsigned 16-bit integer dataset. It would loose important information if I would resample it into 8 bit. Therefore, I would like to feed the unsigned 16-bit data into the graph for training. The first 2 byte contains the label for the data and the rest (height x width x depth x 2 bytes) contains the data for a record. I use this method to write the binary file to disc: out = np.array(outp, dtype = np.uint16) #this variable contains the data out.tofile("d:\\TF\\my_databatch_0.bin") This part tend to be OK. If I read it back to memory with this: in = np.fromfile("d:\\TF\\my_databatch_0.bin", dtype=np.uint16) It gives me exactly the same array, which was written to the disc. When I'm trying to feed it into the graph through this modified input function, it fails in a later step: import tensorflow as tf import numpy as np ##########################Reader for unsigned 16 bit numpy array############### def read_cifar10(filename_queue): class CIFAR10Record(object): pass result = CIFAR10Record() label_bytes = 2 result.height = 32 result.width = 32 result.depth = 1 result.bitdepth = 2 #2 if 16bit, 1 if 8bit image_bytes = result.height * result.width * result.depth * result.bitdepth record_bytes_ = label_bytes + image_bytes reader = tf.FixedLengthRecordReader(record_bytes=record_bytes_) result.key, value = reader.read(filename_queue) record_bytes__ = tf.decode_raw(value, tf.uint16, little_endian=True) result.label = tf.stri…
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51622002
type: Question
tagged with: visual-studio-2017
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/33849617
score: 2
has title: How to read unsigned 16 bit integer binary data with Tensorflow from a file queue?

http://stackoverflow.com/comment/89961261
has text: please I need your help guys, I still didn't reach out to a solution
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51488313

http://stackoverflow.com/comment/89978020
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51504268
has text: OK, you need to make it clearer what your decorator is supposed to accomplish. Is it supposed to just return the decorated class, but patches with a new `__repr__`? Return a wrapper class that delegates everything except `__repr__`? Return a class that, when called, actually returns an instance of the decorated class instead of an instance of itself, but prints out some custom message? …?
score: 0

http://stackoverflow.com/comment/89948324
score: 0
type: Comment
type: QuestionComment
has text: Oh yeah, I found it on here: https://stackoverflow.com/questions/39627006/python-tkinter-hiding-widget-after-showing-it-with-place-geometry-manager. Thanks for the suggestion :) And sorry for the duplication
comment on: http://stackoverflow.com/q/51489768

http://stackoverflow.com/q/51487737
has body: I would like to replace nan's in a list with values from a second list which has exactly same number of elements as the number of nan's in the first list. mylist1 = list([1, 2, 3, np.nan, np.nan, 4, np.nan, 5]) mylist2 = list([-10, -11, -12]) What I want is: mylist1 = [1, 2, 3, -10, -11, 4, -12, 5]
has title: Replace nan's for a list according to another list with different sizes python
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51487762
score: 2
downvote count: 0
answer count: 1
tagged with: nan
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/51487762
tagged with: data-cleaning
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51512216
has comment: http://stackoverflow.com/comment/89992922
has answer: http://stackoverflow.com/a/51512292
score: -1
tagged with: eof
has comment: http://stackoverflow.com/comment/89992951
upvote count: 0
answer count: 1
favorite count: 0
has body: numArr = [x for x in input().split()] for num in numArr: if num == '+' or num &gt;= 'a' and num &lt;= 'z': print("invalid") elif int(num) &gt;= 0 and int(num) &lt;= 1000: num_1 = str(num) count = 0 for i in num_1: if i == '3': count += 1 if int(num) % 3 == 0 and count &gt; 0: print("dumb") elif count &gt; 0: print("stupid") elif int(num) % 3 == 0: print("idiot") elif int(num) % 3 != 0 and count == 0: print("smart") else: print("invalid") Is the above code fine? I got an EOF Error in a different editor i used. But this code executed in the Codechef IDE. What might be the problem?
tagged with: python
has title: Python EOF Error in the code
type: UnansweredQuestion
downvote count: 1
type: Question

http://stackoverflow.com/comment/90036351
comment on: http://stackoverflow.com/q/51534312
score: 0
has text: Please add an expected result
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90062549
type: Comment
comment on: http://stackoverflow.com/a/51542040
score: 0
type: AnswerComment
has text: There is one issue some times if I click the button many times it allows me to bypass the login and go to that screen but, only for one button and its random what one it allows me to bypass the login screen. Why is this and is there a way to fix it?

http://stackoverflow.com/q/51489331
has comment: http://stackoverflow.com/comment/89947899
has comment: http://stackoverflow.com/comment/89948503
has comment: http://stackoverflow.com/comment/89947659
has comment: http://stackoverflow.com/comment/89948806
downvote count: 2
has answer: http://stackoverflow.com/a/51504212
has answer: http://stackoverflow.com/a/51490406
answer count: 3
tagged with: selenium
has comment: http://stackoverflow.com/comment/89948078
has comment: http://stackoverflow.com/comment/89947840
has body: Are preceding-sibling and following-sibling the only options for explicitly selecting siblings? Simplified Version of Markup &lt;ui-view&gt; &lt;descendant&gt; &lt;!-- 1 --&gt; &lt;descendant&gt; &lt;!-- 2 --&gt; &lt;descendant&gt; &lt;!-- 3 --&gt; &lt;descendant&gt; &lt;!-- 4 --&gt; &lt;descendant&gt; &lt;!-- 5 --&gt; &lt;sibling&gt; &lt;child&gt;&lt;/child&gt; &lt;!-- comments_author --&gt; &lt;child&gt;&lt;/child&gt; &lt;!-- comments_timestamp --&gt; &lt;/sibling&gt; &lt;sibling&gt;&lt;/sibling&gt; &lt;!-- comment (in comments_comment) --&gt; Script # 1. Select All Comment Threads comments_threads = browser.find_elements_by_xpath('//ui-view//div[@class="commentLayout"]') for thread in comments_threads: # 2. Select All Comments in Each Thread comments_comment = comments_threads.find_elements_by_xpath('./div[contains(@class, "commentLayout-text")]') for comment in comments_comment: # 3. Select Author of Each Comment # comments_author = comments_threads.find_element_by_xpath('./*[contains(@class, "commentLayout-account")]') # 4. Select Timestamp of Each Comment # comments_timestamp = comments_threads.find_element_by_xpath('./span[contains(@class, "commentNote")]') The issue is that 3 and 4 have to be selected in relation to each comment item of the nested loop, and I would like my code to be as flexible as possible. Selecting any sibling to match the desired node would be a lot more flexible than, say, using preceding-sibling to match the desired node. One solution would be to select the parent node and then select any child that matches a particular condition, but, if possible, using any sibling as a selector would certainly be more flexible and even more efficient. Is it not possible to select all siblings?
has comment: http://stackoverflow.com/comment/89948641
has comment: http://stackoverflow.com/comment/89948064
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89947719
has title: Select Any Sibling
has comment: http://stackoverflow.com/comment/89947960
has comment: http://stackoverflow.com/comment/89947939
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/89947855
type: Question
has comment: http://stackoverflow.com/comment/89947990
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/89948264
has answer: http://stackoverflow.com/a/51490164
tagged with: xpath

http://stackoverflow.com/a/51543543
score: 0
answers question: http://stackoverflow.com/q/51542884
type: Answer
has comment: http://stackoverflow.com/comment/90056334
has comment: http://stackoverflow.com/comment/90055068
has body: Use merge. df1 = pd.read_csv('1.csv') df2 = pd.read_csv('2.csv') df3 = df1.merge(df2, on = ['name','feature'],how = 'left') Then you can perform the subtraction for dates, depending on the data type of the timestamp columns.

http://stackoverflow.com/a/51524486
has comment: http://stackoverflow.com/comment/90018128
has comment: http://stackoverflow.com/comment/90018249
answers question: http://stackoverflow.com/q/51524421
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90018450
type: Answer
accepted answer of: http://stackoverflow.com/q/51524421
has comment: http://stackoverflow.com/comment/90017749
score: 3
upvote count: 3
has body: IIUC pd.Series(transactions).apply(pd.Series).stack().apply(pd.Series).reset_index(level=0) Out[431]: level_0 cost item 0 Customer A 1000 Item A 1 Customer A 20 Item B 0 Customer B 300 Item C 1 Customer B 1000 Item A

http://stackoverflow.com/comment/109538324
comment on: http://stackoverflow.com/a/51528497
score: 0
type: AnswerComment
type: Comment
has text: it seems enough indeed, to just use `np.array(self.sct.grab(monitor))[:, :, :3]`, thus removing the alpha channel from the tensor being passed on to `cv2.VideoWriter.write`.

flask-restplus
tag name: flask-restplus
type: Tag
tags question: http://stackoverflow.com/q/51546148
tags question: http://stackoverflow.com/q/51554561
tags question: http://stackoverflow.com/q/51488047
tags question: http://stackoverflow.com/q/51567716

http://stackoverflow.com/q/51594900
has title: Python vectorized operation involving data from a previous row
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51597969
has body: I have pretty good grasp of how to utilize pandas and numpy to vectorize operations on entire columns of data. However, I've come across a situation that I just can't seem to vectorize. When the calculation involves utilizing a value from a previous row to calculate the current row, I have to fall back to a for loop. Is it possible to vectorize this kind of thing? Here is a simple example of what I mean: # Test set of 20 random integers df = pd.DataFrame({'base': [15, 16, 2, 16, 14, 1, 18, 18, 4, 7, 4, 18, 19, 13, 16, 11, 1, 8, 1, 9]}) # Empty array to hold calculated values calc_data = np.empty((20, 1)) period = 14 for idx, value in enumerate(df.base): # Seeding the first element of the calculated array if idx == 0: calc_data[idx] = 5 else: calc_data[idx] = (calc_data[idx - 1] * (period - 1) + df.base.iloc[idx]) / period # Adding the column to the dataframe df['calculated'] = calc_data print(df) Output: base calculated 0 15 5.000000 1 16 5.785714 2 2 5.515306 3 16 6.264213 4 14 6.816769 5 1 6.401286 6 18 7.229765 7 18 7.999068 8 4 7.713420 9 7 7.662461 10 4 7.400857 11 18 8.157939 12 19 8.932372 13 13 9.222916 14 16 9.706994 15 11 9.799351 16 1 9.170826 17 8 9.087196 18 1 8.509539 19 9 8.544572
tagged with: vectorization
has comment: http://stackoverflow.com/comment/90156526
type: Question
has comment: http://stackoverflow.com/comment/90157921
has answer: http://stackoverflow.com/a/51597293
accepted answer: http://stackoverflow.com/a/51597293
has comment: http://stackoverflow.com/comment/90157958
has answer: http://stackoverflow.com/a/51594997
score: 4
upvote count: 4
tagged with: numpy
tagged with: pandas
has answer: http://stackoverflow.com/a/51597969
downvote count: 0
favorite count: 0
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/90156279

http://stackoverflow.com/q/51506698
has body: In Python Selectors module, there's a bitmask which can be EVENT_READ or EVENT_WRITE and the implementation is: EVENT_READ = (1 &lt;&lt; 0) EVENT_WRITE = (1 &lt;&lt; 1) Is there any specific reason for using 1 &lt;&lt; 0 and 1 &lt;&lt; 1 other than making sure EVENT_READ, EVENT_WRITE, EVENT_READ | EVENT_WRITE, EVENT_READ &amp; EVENT_WRITE will have different values?
type: AnsweredQuestion
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/89982636
has answer: http://stackoverflow.com/a/51507119
tagged with: python-3.x
score: 0
has title: Implementation of bitmask in Python Selectors module
answer count: 1
accepted answer: http://stackoverflow.com/a/51507119
has comment: http://stackoverflow.com/comment/89982613

http://stackoverflow.com/q/51590602
has comment: http://stackoverflow.com/comment/90146859
type: UnansweredQuestion
has title: Histogram show values of vertical lines in legends
has comment: http://stackoverflow.com/comment/90146585
has comment: http://stackoverflow.com/comment/90146479
downvote count: 1
tagged with: plot
has answer: http://stackoverflow.com/a/51591228
has comment: http://stackoverflow.com/comment/90147193
tagged with: matplotlib
score: -1
type: Question
upvote count: 0
has body: Can I show the values of vertical lines(dashed) in legends or annotate it somewhere, how? Here is the code for dashed line plt.hist(df['wt_avg_delay'], bins=50, color='lightblue', edgecolor='black') plt.axvline(df['wt_avg_delay'].mean(), color='orange', linestyle='dashed', linewidth=1) plt.axvline(-19, color='green', linestyle='dashed', linewidth=1) plt.axvline(27 color='red', linestyle='dashed', linewidth=1)
has comment: http://stackoverflow.com/comment/90146730
answer count: 1
linked to: http://stackoverflow.com/q/10499885
tagged with: histogram
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90147360
linked to: http://stackoverflow.com/q/50415578

http://stackoverflow.com/comment/90059769
type: QuestionComment
has text: Sounds like PM is a hash key, so only the last assigned value, etc..
comment on: http://stackoverflow.com/q/51545783
score: 0
type: Comment

http://stackoverflow.com/comment/90131760
type: QuestionComment
has text: you are comparing a string with a datetime object.Thats as if you would test if a real car is equal to its picture - they might look the same, but are not equal. either make both a string for comparison _or_ make both datetime.date - objects. If you are set upon not allowing the date to be changed, simply do not show a datetime fiels in your frontend, you got the id, change only the diarys text, and do not change the date at all
score: 1
comment on: http://stackoverflow.com/q/51582938
type: Comment

http://stackoverflow.com/comment/90008732
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51519942
type: AnswerComment
has text: I'm not sure but I think this misses the idea behind OPs question. It is evident that they simply want to consume the generator that `map` returns without: **1.** creating a list, either by a list comprehension or by `list(map(...))` **2.** writing an "explicit" loop

http://stackoverflow.com/q/51584223
answer count: 4
has title: Python3: What is the most efficient way to calculate all permutations of two lists summing to 100?
has comment: http://stackoverflow.com/comment/90134549
has answer: http://stackoverflow.com/a/51584327
upvote count: 3
type: UnansweredQuestion
has body: Imagine we have a list of stocks: stocks = ['AAPL','GOOGL','IBM'] The specific stocks don't matter, what matters is that we have n items in this list. Imagine we also have a list of weights, from 0% to 100%: weights = list(range(101)) Given n = 3 (or any other number) I need to produce a matrix with every possible combinations of weights that sum to a full 100%. E.g. 0%, 0%, 100% 1%, 0%, 99% 0%, 1%, 99% etc... Is there some method of itertools that can do this? Something in numpy? What is the most efficient way to do this?
has answer: http://stackoverflow.com/a/51584331
score: 3
has answer: http://stackoverflow.com/a/52130135
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/90135372
type: Question
tagged with: numpy
downvote count: 0
favorite count: 0
tagged with: combinatorics
linked to: http://stackoverflow.com/q/6284396
has answer: http://stackoverflow.com/a/51584389
tagged with: python

http://stackoverflow.com/a/51539404
has body: Use Counter with dictionary comprehension and assign to DataFrame: from collections import Counter df = pd.DataFrame({k:Counter(v) for k, v in d.items()}).T.fillna(0).astype(int) print (df) arylpolyene hserlactone hserlactone-arylpolyene nrps siderophore \ A 1 2 0 1 1 B 0 1 1 1 1 C 0 0 0 3 1 D 0 0 0 1 1 t1pks-nrps terpene thiopeptide transatpks-nrps A 1 1 1 1 B 0 0 1 0 C 2 0 0 0 D 1 0 0 0 EDIT: For indicator values use MultiLabelBinarizer: d = {'A': ['arylpolyene', 'hserlactone', 'hserlactone', 'nrps', 'siderophore', 't1pks-nrps', 'terpene', 'thiopeptide', 'transatpks-nrps'], 'B': ['hserlactone', 'hserlactone-arylpolyene', 'nrps', 'siderophore', 'thiopeptide'], 'C' :['nrps', 'nrps', 'nrps', 'siderophore', 't1pks-nrps', 't1pks-nrps'], 'D': ['nrps', 'siderophore', 't1pks-nrps']} from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer() df = pd.DataFrame(mlb.fit_transform(d.values()),columns=mlb.classes_, index=d.keys()) print (df) arylpolyene hserlactone hserlactone-arylpolyene nrps siderophore \ A 1 1 0 1 1 B 0 1 1 1 1 C 0 0 0 1 1 D 0 0 0 1 1 t1pks-nrps terpene thiopeptide transatpks-nrps A 1 1 1 1 B 0 0 1 0 C 1 0 0 0 D 1 0 0 0
accepted answer of: http://stackoverflow.com/q/51538480
score: 2
answers question: http://stackoverflow.com/q/51538480
downvote count: 0
has comment: http://stackoverflow.com/comment/90047120
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90046507
type: Answer

neural-network
tags question: http://stackoverflow.com/q/51616550
tags question: http://stackoverflow.com/q/51518585
tags question: http://stackoverflow.com/q/51586582
tags question: http://stackoverflow.com/q/51635187
tags question: http://stackoverflow.com/q/51545026
tags question: http://stackoverflow.com/q/51598437
tags question: http://stackoverflow.com/q/51602088
tags question: http://stackoverflow.com/q/51569005
tags question: http://stackoverflow.com/q/51634111
tags question: http://stackoverflow.com/q/51499231
type: Tag
tags question: http://stackoverflow.com/q/51482686
tags question: http://stackoverflow.com/q/51616078
tags question: http://stackoverflow.com/q/51548198
tags question: http://stackoverflow.com/q/51557972
tags question: http://stackoverflow.com/q/51497370
tags question: http://stackoverflow.com/q/51599229
tags question: http://stackoverflow.com/q/51602194
tags question: http://stackoverflow.com/q/51573277
tags question: http://stackoverflow.com/q/51603798
tags question: http://stackoverflow.com/q/51570785
tags question: http://stackoverflow.com/q/51585339
tag name: neural-network
tags question: http://stackoverflow.com/q/51503851
tags question: http://stackoverflow.com/q/51515232
tags question: http://stackoverflow.com/q/51634251
tags question: http://stackoverflow.com/q/51586563

http://stackoverflow.com/comment/89975635
type: QuestionComment
has text: Thanks @shevron, it worked and I like that idea. It's solved
comment on: http://stackoverflow.com/q/51484630
score: 0
type: Comment

http://stackoverflow.com/a/51633335
answers question: http://stackoverflow.com/q/51633309
has body: The context passed to render should be a dict return render(request, 'accounts/page.html', {'list': list})
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/90238231
score: 3
downvote count: 0

http://stackoverflow.com/comment/89985356
score: 1
comment on: http://stackoverflow.com/q/51508003
type: Comment
type: QuestionComment
has text: As a side note:`sys.exit`, like all functions, doesn't do anything unless you _call_ it, like `sys.exit()`. Also, to loop forever until you return/exit, just use a `while True:` loop around the function, don't recursively call the function from itself.

http://stackoverflow.com/a/62985928
score: 5
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/139381658
type: Answer
answers question: http://stackoverflow.com/q/51621307
has body: As answered by @daniel-kurniadi you need to adapt the values of the ngram_range parameter to use the n-gram. For instance by using (1, 2), the vectorizer will take into account unigrams and bigrams. The main advantages of ngrams over BOW i to take into account the sequence of words. For instance, in the sentences: "I love vanilla but I hate chocolate" "I love chocolate but I hate vanilla" The meaning is clearly different but a basic BOW representation will be the same in both cases. With n-grams (with n>=2), it will capture the order of the terms and thus the representations will be different.

http://stackoverflow.com/comment/90223719
type: QuestionComment
score: 1
has text: Try putting some "return True" You need it because you used that function in if statement.
comment on: http://stackoverflow.com/q/51629532
type: Comment

http://stackoverflow.com/q/51524840
downvote count: 0
answer count: 1
favorite count: 0
has title: python unit tests structure - how to better structure project with multiple packages and many tests files?
type: UnansweredQuestion
has body: I did some studies and it seems that many python projects with tests would have the structure like following: my_project: - package_1 - my_package_1_class_1.py - my_package_1_class_2.py - my_package_1_class_3.py - package_2 - my_package_2_class_1.py - my_package_2_class_2.py - my_package_2_class_3.py - my_package_2_class_4.py - package_3 - my_package_3_class_1.py - my_package_3_class_2.py - test - test_my_package_1_class_1.py - test_my_package_1_class_2.py - test_my_package_1_class_3.py - test_my_package_2_class_1.py - test_my_package_2_class_2.py - test_my_package_2_class_3.py - test_my_package_2_class_4.py - test_my_package_3_class_1.py - test_my_package_3_class_2.py The testing files from all packages are in the same test folder. This is a bit different from the normal Java structure, which each package has a corresponding folder for its own tests. I feel this python structure is getting messy when we try to put a lot of testing files from different packages into the same test folder ... How would an experienced python architecture/programmer structure their projects with many packages and testing files? Thanks!
has answer: http://stackoverflow.com/a/56193394
tagged with: python
tagged with: unit-testing
type: Question
upvote count: 4
score: 4

http://stackoverflow.com/a/51626217
upvote count: 2
type: Answer
score: 2
has body: There's a python inbuilt to find combinations. It's itertools.combinations. This will give you a generator at which you can iterate over to get all the combinations - import itertools for combi in itertools.combinations(str1, 8): print combi Or do a list in front of it to get a list of tuples of all the combinations - combi = list(itertools.combinations(str1, 8))
downvote count: 0
answers question: http://stackoverflow.com/q/51626090

http://stackoverflow.com/q/51496550
has comment: http://stackoverflow.com/comment/90198550
type: UnansweredQuestion
tagged with: python
has body: I am running a module which can be found here: https://github.com/danieliu/play-scraper My code inside python file is as follows: import play_scraper print(play_scraper.collection( collection='TOP_FREE', category='COMMUNICATION', results=5, page=1)) I do not quite follow the error message in the terminal and I am unsure on how to or where to search to proceed forward. File "app-store-scraper.py", line 1, in &lt;module&gt; import play_scraper ImportError: No module named play_scraper Sams-MacBook-Air-2:cm-leadgen samframpton$ python3 app-store-scraper.py /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: greenlet.greenlet size changed, may indicate binary incompatibility. Expected 144, got 128 return f(*args, **kwds) /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: greenlet.greenlet size changed, may indicate binary incompatibility. Expected 144, got 128 return f(*args, **kwds) /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: greenlet.greenlet size changed, may indicate binary incompatibility. Expected 144, got 128 return f(*args, **kwds) /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: greenlet.greenlet size changed, may indicate binary incompatibility. Expected 144, got 128 return f(*args, **kwds) /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: greenlet.greenlet size changed, may indicate binary incompatibility. Expected 144, got 128 return f(*args, **kwds) /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: greenlet.greenlet size changed, may indicate binary incompatibility. Expected 144, got 128 return f(*args, **kwds) /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap.py:219: Run…
has answer: http://stackoverflow.com/a/64038112
upvote count: 10
type: Question
answer count: 2
has title: Runtime Warning - Greenlet.greenlet size changed??
score: 10
downvote count: 0
has answer: http://stackoverflow.com/a/67632276
favorite count: 0

http://stackoverflow.com/comment/90237982
comment on: http://stackoverflow.com/a/51636791
score: 0
type: AnswerComment
type: Comment
has text: I totally agree, pass means this is not important and I don't do anything in that case so I don't see any advantage in using it in conditional statements as I have to stop and read the condition and then mover over to do.... nothing

http://stackoverflow.com/comment/90047272
type: QuestionComment
comment on: http://stackoverflow.com/q/51539434
type: Comment
has text: `"1":(1,2,3,4),"2":(4,5,6,7)` should be `"1":(1,2,3,4),"2":(5,6,7,8)` and so on
score: 0

http://stackoverflow.com/q/51499605
type: Question
has title: How to remove points from a plot?
has body: I am using matplotlib.pyplot. I would like to do the following: I want to plot a series of background dots (single blue dot in example). I add an additional series of dots (3 black dots in example) I save the figure I remove the additional series of dots (black) and keep the background one (blue). How can I perform step 4? I would like to avoid having to replot the background dots. Hereunder is an example of code with step 4 missing. import matplotlib.pyplot as plt fig = plt.figure() plt.xlim(-10,10) plt.ylim(-10,10) #step 1: background blue dot plt.plot(0,0,marker='o',color='b') #step 2: additional black dots points_list = [(1,2),(3,4),(5,6)] for point in points_list: plt.plot(point[0],point[1],marker='o',color='k') #step 3: save plt.savefig('test.eps') #step 4: remove additional black dots
possible better answer: http://stackoverflow.com/a/51499824
has answer: http://stackoverflow.com/a/51499824
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51499890
favorite count: 0
has answer: http://stackoverflow.com/a/51499693
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51499890

http://stackoverflow.com/comment/90038677
has text: I'm not sure, why you want to do it manually. You can simply run `pip install --no-cache-dir fix_yahoo_finance` when your conda environment is activated.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51535431

http://stackoverflow.com/q/51622278
has answer: http://stackoverflow.com/a/51625232
tagged with: python
has comment: http://stackoverflow.com/comment/90214714
score: 0
has comment: http://stackoverflow.com/comment/90210423
answer count: 1
has comment: http://stackoverflow.com/comment/90210591
has comment: http://stackoverflow.com/comment/90210762
has body: I'm trying to create a deployment package for AWS Lambda but no matter what I do I can't get it to run. Here's my process: 1) Launch AWS EC2 instance from the AMI linked here 2) Use Pip3 to install all my dependencies to a local folder with Python 3.6 installed via Yum. 3) FTP the dependencies to my local computer and zip it with my python file. My folder structure normally: My folder structure INSIDE zip: The exact code I'm trying to call is the "handler" method inside of login.py. This is how my Lambda function is set-up: Lastly, here is the actual error message I receive, I've done everything I think of can't seem to figure this out: Any help greatly appreciated!! EDIT: Here's the python code: import sys import logging import rds_config import bcrypt import pymysql #rds settings rds_host = "xxx" name = rds_config.db_username password = rds_config.db_password db_name = rds_config.db_name logger = logging.getLogger() logger.setLevel(logging.INFO) try: conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5) except: logger.error("ERROR: Unexpected error: Could not connect to MySql instance.") sys.exit() logger.info("SUCCESS: Connection to RDS mysql instance succeeded") def handler(event, context): accountData = None accountEmail = event['userEmail'] accountPassword = event['userPassword'] with conn.cursor() as cur: sql = "SELECT `id`, `email`, `password` FROM `accounts` WHERE `email`=%s" cur.execute(sql, ('myEmail@testEmail.comn')) accountData = cur.fetchone() if accountData['email'] == accountEmail: if bcrypt.hashpw(password, accountData['password']) == accountData['password']: print('Returning Account Id: ' + str(accountData['id'])) return accountData['id'] else: print("Invalid Credentials") return "Invalid Credentials"
type: UnansweredQuestion
has title: AWS Lambda Function cannot find my python code
has comment: http://stackoverflow.com/comment/90210848
has comment: http://stackoverflow.com/comment/90210718
has comment: http://stackoverflow.com/comment/90211734
tagged with: amazon-web-services
tagged with: aws-lambda
type: Question
has comment: http://stackoverflow.com/comment/90211327
has comment: http://stackoverflow.com/comment/90211121

http://stackoverflow.com/comment/90185179
has text: You can use [jsonlint](https://jsonlint.com/) and actually, the snippet isn't valid JSON as you've posted, but it looks like you put your own newline in before `"Dr Paniccia"`. Once that string is all on one line it's valid. But I don't see how you'd get invalid JSON back from bigquery.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51609426

http://stackoverflow.com/comment/90176535
type: QuestionComment
has text: I thought of using pivot, but I am kind of stuck with the solution.
comment on: http://stackoverflow.com/q/51605561
score: 0
type: Comment

http://stackoverflow.com/comment/90050735
has text: just did please help thanks
comment on: http://stackoverflow.com/q/51541042
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51614021
has title: How do open a PDF in the background in Python?
upvote count: 2
has comment: http://stackoverflow.com/comment/90194110
type: Question
has comment: http://stackoverflow.com/comment/90193688
has body: I have made a very simple script that is used to rename PDF files. The procedure is quite simple; I have to open the PDF to see what I should name that particular file. Sometimes I have up towards 100 PDFs to rename. The script looks like this: import os path = os.getcwd() filenames = os.listdir(path) prefix = input("Vad ska stå innan? ") for filename in filenames: if filename.endswith(".pdf"): filepath = path + "\\" + filename print(filename) os.startfile(filepath) nyttNamn = input("Nytt namn: ") nyttNamn = prefix + " " + nyttNamn + ".pdf" os.rename(filename, nyttNamn) else: continue My only problem is that when I open the PDF (which opens in chrome, in a new tab), I have to alt+tab back to the shell to let the loop continue to the next PDF file. Is there someway I can either open the PDF in the background, so that I am still in the shell and can write, or somehow automatically open it and go back to the shell window?
has comment: http://stackoverflow.com/comment/90195367
score: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51614308
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90193819
has comment: http://stackoverflow.com/comment/90193499
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90193628

http://stackoverflow.com/q/51627209
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
score: 1
has title: Django class based view related fields map url
has comment: http://stackoverflow.com/comment/90219195
type: Question
downvote count: 0
tagged with: foreign-keys
tagged with: django-class-based-views
has body: I'm having trouble getting a Novel webpage to return a view with the appropriate chapters for a specific book. My index page lists all the objects of the Book model class and hyperlinks them to the detail page with the slug field. {{ book.name }} This should call my detail.html page with the slug parameter (right???). The detail view works with the Chapter model class, which is linked to the Book model class with foreign key (id number). I realize the Chapter model class doesn't have a slug field of its own, but I think it should be able to map urls through the relationship to the book model. Is the a wrong assumption? I know I can add the slug field to the chapter model but it seems redundant since the application is a translator I will eventually make a model class for sentences in each chapter. How do I get this to work? I don't know if my approach is even correct but this is the error I get: TypeError at /novel/1984/ get_queryset() missing 2 required positional arguments: 'request' and 'slug' The model consists of 2 classes (Book and Chapter) that are linked by foreign key (in Book). The book index page lists each of the books in library and hyperlink to their chapter index page. The book index page works fine however I am can't seem to properly pass parameters to chapter view and display the chapter index page (simply list the chapter number, which I would also hyperlink later). The code is a bit frankensteinish, if anything is unnecessary or if there is an easier way to do it please tell. Any help is greatly appreciated models.py from django.db import models from django.template.defaultfilters import slugify class Book(models.Model): number = models.PositiveIntegerField(primary_key=True, unique=True, db_index=True) name = models.CharField(max_length=33, db_index=True) short = models.CharField(max_length=7) search = models.CharField(max_length=7) chaptercount = models.IntegerField() title = models.CharField(max_length=33) slug = models.SlugField(max_length=33, …
favorite count: 0
has comment: http://stackoverflow.com/comment/90252220
answer count: 0

http://stackoverflow.com/comment/90061437
comment on: http://stackoverflow.com/q/51546593
type: Comment
type: QuestionComment
has text: It’s worth pasting your code into PythonTutor.com or another interactive visualizer—or just using the debugger, if you know how—and stepping through step by step. Everything should become a lot clearer from that, than from anything anyone can explain abstractly.
score: 0

imaplib
tags question: http://stackoverflow.com/q/51543067
type: Tag
tag name: imaplib

http://stackoverflow.com/comment/90158588
comment on: http://stackoverflow.com/q/51596270
has text: @GreenCloakGuy Meaning that the 656 first executions are executed in the same us, then the CPU scheduling switch to Chrome, Outlook, or whatever else was running the background, and then reswitch to the python interpreter 4021 us later to end the while loop? Well maybe, anyway, how can I overcome this? ^^
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51579371
has comment: http://stackoverflow.com/comment/90124040
has comment: http://stackoverflow.com/comment/90124253
tagged with: python-itertools
has title: I want to get all combination of a list in form of a list of list using combinations method of itertools
score: -1
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/90124052
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: I tried this import itertools a=[10, 1 ,2, 7, 6, 1, 5] b=[] for i in range(len(a)): for s in itertools.combinations(a,i): if s not in b: b.append(s) print(b) I am getting desired output in form of tuple. I want output as below: [[10],[1],...[10,1],...[10,1,2]....]
has comment: http://stackoverflow.com/comment/90124529
has comment: http://stackoverflow.com/comment/90124270
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1482308
has answer: http://stackoverflow.com/a/51579516
accepted answer: http://stackoverflow.com/a/51579516
has comment: http://stackoverflow.com/comment/90124238
linked to: http://stackoverflow.com/q/16296643
has comment: http://stackoverflow.com/comment/90124538
type: Question
tagged with: combinations

http://stackoverflow.com/comment/90121297
type: AnswerComment
has text: Thank you for helping me. The problem has been solved
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51574528

http://stackoverflow.com/comment/89956460
has text: Ah, yeah, sorry, I should have understood that :P But yeah, this is a very common pattern, where you put "guards" on the top of the function, then proceed with the real stuff if all the guards are satisfied.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51493231
type: Comment

http://stackoverflow.com/comment/89997920
has text: Thanks, but still recursive.
comment on: http://stackoverflow.com/a/51500728
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51509141
has title: Django ORM: Filter results by values from list, limit answers per value?
accepted answer: http://stackoverflow.com/a/51527976
downvote count: 0
favorite count: 0
tagged with: django
tagged with: python
score: 2
type: AnsweredQuestion
has body: I'm using Django 2.0 and have a Content model with a ForeignKey(User, ...). I also have a list of user IDs for which I'd like to fetch that Content, ordered by "newest first", but only up to 25 elements per user. I know I can do this: Content.objects.filter(user_id__in=[1, 2, 3, ...]).order_by('-id') ...to fetch all the Content objects created by each of these users, plus I'll get it all sorted with newest elements first. But I'd like to fetch up to 25 elements for each of these users (some users might create hundreds of these objects, some might create zero). There's of course the dumb way: for user in [1, 2, 3, ...]: Content.objects.filter(user_id=user).order_by('-id')[:25] This however hits the database as many times as there's objects in the user ID list, and that goes quite high (around 100 or so per page view). Is there any way to optimize this case? (I've tried looking around select_related, but that seems to fetch as many related models as possible.)
possible better answer: http://stackoverflow.com/a/51530109
upvote count: 2
tagged with: django-orm
has answer: http://stackoverflow.com/a/51530109
has answer: http://stackoverflow.com/a/51527976
type: Question
tagged with: django-models
tagged with: greatest-n-per-group
answer count: 2

http://stackoverflow.com/a/51614380
has comment: http://stackoverflow.com/comment/90236178
has comment: http://stackoverflow.com/comment/90217684
type: AcceptedAnswer
score: 4
has comment: http://stackoverflow.com/comment/90194542
has comment: http://stackoverflow.com/comment/90200465
downvote count: 0
has comment: http://stackoverflow.com/comment/90194690
has body: For this dataframe: d={'SK_ID_CURR':[215354, 215354, 215354, 215354, 215354, 215354, 215354, 162297, 162297, 162297, 162297, 162297, 162297,402440 ,238881], 'CREDIT_ACTIVE':['Closed', 'Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Closed', 'Closed', 'Active', 'Active', 'Closed', 'Active', 'Active', 'Closed' ], 'CREDIT_TYPE':['Consumer credit', 'Credit card', 'Consumer credit', 'Credit card', 'Consumer credit', 'Credit card', 'Consumer credit', 'Consumer credit', 'Consumer credit', 'Credit card', 'Credit card', 'Consumer credit', 'Mortgage', 'Consumer credit', 'Credit card', ]} df=pd.DataFrame(d) print(df) Output: SK_ID_CURR CREDIT_ACTIVE CREDIT_TYPE 0 215354 Closed Consumer credit 1 215354 Active Credit card 2 215354 Active Consumer credit 3 215354 Active Credit card 4 215354 Active Consumer credit 5 215354 Active Credit card 6 215354 Active Consumer credit 7 162297 Closed Consumer credit 8 162297 Closed Consumer credit 9 162297 Active Credit card 10 162297 Active Credit card 11 162297 Closed Consumer credit 12 162297 Active Mortgage 13 402440 Active Consumer credit 14 238881 Closed Credit card You can try something like this: aggregations = { 'CREDIT_ACTIVE': { # work on this column, 'CREDIT_ACTIVE': lambda x: list(x).count('Active'), 'CREDIT_CLOSED': lambda x: list(x).count('Closed') }, 'CREDIT_TYPE': { # work on this column, 'CONSUMER_CREDIT ': lambda x: list(x).count('Consumer credit'), 'CREDIT_CARD': lambda x: list(x).count('Credit card') }} temp=df.groupby('SK_ID_CURR').agg(aggregations).reset_index() temp.columns = [e[1] for e in temp.columns.tolist()] print(temp) Output: CREDIT_ACTIVE CREDIT_CLOSED CONSUMER_CREDIT CREDIT_CARD 0 162297 3 3 3 2 1 215354 6 1 4 3 2 238881 0 1 0 1 3 402440 1 0 1 0
type: Answer
answers question: http://stackoverflow.com/q/51613764
upvote count: 4
accepted answer of: http://stackoverflow.com/q/51613764

http://stackoverflow.com/q/51563202
accepted answer: http://stackoverflow.com/a/73830792
answer count: 1
has comment: http://stackoverflow.com/comment/90094111
has comment: http://stackoverflow.com/comment/90094363
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90094262
tagged with: python
has answer: http://stackoverflow.com/a/73830792
tagged with: aggregate
upvote count: 3
tagged with: pivot-table
has comment: http://stackoverflow.com/comment/90094454
has title: Pandas pivot_table drops values for aggregate functions that return all None, even if dropna argument is False
has comment: http://stackoverflow.com/comment/90094356
downvote count: 1
has comment: http://stackoverflow.com/comment/90093953
type: Question
score: 2
type: AnsweredQuestion
has body: The dropna=False argument of pandas pivot_table is not doing what I expect it to do. I'm starting with the following DataFrame: import pandas as pd # pd.__version__ = '0.23.3' df = pd.DataFrame({'fruit':['apple','orange','peach','apple','peach'], 'size': [1,1.5,1,2,1], 'taste': [7,8,6,6,10]}) ...and the following aggregate functions: def return_one(x): return 1 def return_sum(x): return sum(x) def return_none(x): return None I would like to reshape df so that the: index is made up of the original column names ('size','taste'). values are the result of the aggregate functions applied to values within a group. columns are the fruit types ('apple', 'orange', 'peach') The following pivot_table is almost there: pd.pivot_table(df, columns='fruit', aggfunc=[return_sum,return_none,return_one], dropna=False) Except that the output of return_none has been dropped. I would expect the pivoted table to include a set of empty cells for the return_none function because dropna=False, but it does not. Can anyone suggest how to include the output of return_none?
has comment: http://stackoverflow.com/comment/90470973
tagged with: dataframe

http://stackoverflow.com/q/51579470
has comment: http://stackoverflow.com/comment/90125454
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90124432
tagged with: python
has comment: http://stackoverflow.com/comment/90124514
has comment: http://stackoverflow.com/comment/90124347
has title: Numpy has no attribute loadtxt?
has comment: http://stackoverflow.com/comment/90124399
upvote count: 1
downvote count: 1
type: Question
has body: For the code below: import numpy as np f = np.loadtxt('ex21_votes.csv', delimiter=",") I get an error: module 'numpy' has no attribute 'loadtxt'. Installed numpy today, here is the output: git clone https://github.com/numpy/numpy.git numpy Cloning into 'numpy'... remote: Counting objects: 137888, done. remote: Compressing objects: 100% (24/24), done. remote: Total 137888 (delta 13), reused 19 (delta 10), pack-reused 137854 Receiving objects: 100% (137888/137888), 57.00 MiB | 1.18 MiB/s, done. Resolving deltas: 100% (109223/109223), done. Checking connectivity... done.
has answer: http://stackoverflow.com/a/51579514
tagged with: numpy
score: 0
tagged with: python-import
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/14985233
has comment: http://stackoverflow.com/comment/90124484

http://stackoverflow.com/comment/90199310
comment on: http://stackoverflow.com/a/51616500
has text: FYI I did not output the full JSON string, it does open and close with }]
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/q/51591939
tagged with: str-replace
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51592306
has answer: http://stackoverflow.com/a/51591991
accepted answer: http://stackoverflow.com/a/51591991
type: Question
has comment: http://stackoverflow.com/comment/90149128
has body: I have an expression as string like "(addtwo*decimal*p_cost)/(cost+density)". I want to replace cost only but but its replacing p_cost as well like - p_"replaced value". I have tried word boundaries but no luck please help. expr = '(addtwo*decimal*p_cost)/(cost+density)' expr = string.replace(expr, r"\b%s\b" % str(' cost '), str(3)) not doing anything.
score: -1
downvote count: 2
answer count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/51592306
has title: replace whole word from expression in python ignore arithmetic operator

http://stackoverflow.com/q/51560030
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/51560148
has answer: http://stackoverflow.com/a/51560148
has comment: http://stackoverflow.com/comment/90087188
has answer: http://stackoverflow.com/a/51561049
tagged with: selenium
has comment: http://stackoverflow.com/comment/90087377
downvote count: 1
has comment: http://stackoverflow.com/comment/90087635
type: Question
has title: Button is not get clicked
has body: The script needs to click button "Ok" which is located on the pop-up. The button is not surrounded by any IFrame, only Textarea is inside IFrame. I used CSS Selector and XPath to click a button and it's not get clicked and no error is reproduced. driver.find_element_by_xpath("//*[@id='mceu_7']").click() driver.switch_to.frame(driver.find_element_by_xpath("//iframe[@src='https://qsm.qoo10.sg/gmkt.inc.gsm.web/common/scripts/module/tiny_mce_4.5.7/source/plugins/codemirror/source.html']")) driver.find_element_by_xpath("/html/body/div/div[1]/textarea").send_keys("Some text") driver.switch_to.default_content() # Click on the "Ok" button. time.sleep(10) driver.find_elements_by_css_selector("#mceu_108 > button:nth-child(1)").click() As well button was clicked before using switch_to.default_content(). This is how Pop-up looks: Can you please help me what might be the issue? HTML code: Ok Cancel
has comment: http://stackoverflow.com/comment/90087224
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/90087276
accepted answer: http://stackoverflow.com/a/51561049
favorite count: 0
has comment: http://stackoverflow.com/comment/90087137
has comment: http://stackoverflow.com/comment/90087381
tagged with: python

http://stackoverflow.com/comment/90200366
score: 1
has text: What do you want to happen if `text` is not exactly 32 characters long?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51617221

http://stackoverflow.com/q/51505655
type: Question
tagged with: java-10
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/89981141
has title: JPype with Java 10
has body: Does anybody know, if JPype works with a Java 10 JRE? I have tested JPype with Java 8 without any problems but I am not able to use it in combination with Java 10. My test setup: Windows 10 64-bit Python 3.5.2 (Anaconda 4.2.0) 64-bit Spyder 3.3.0 JPype 0.6.3 (via pip install) I execute my Python test script in Spyder (included in Anaconda package). Test using Java 8 (jre1.8.0_181) succeeded. JPype JVM starts without any problems. Test using Java 10 (jre-10.0.2) fails with this error: RuntimeError: Unable to load DLL [C:\Program Files\Java\jre-10.0.2\bin\server\jvm.dll], error = Das angegebene Modul wurde nicht gefunden. at native\common\include\jp_platform_win32.h:58 I do have a german Windows version, so the part "Das angegebene Modul wurde nicht gefunden" may be translated as something like "The specified module cannot be found". I used this Python code, to start the JVM in JPype: import jpype java_path = "C:\\Program Files\\Java\\jre-10.0.2\\bin\\server\\jvm.dll" jpype.startJVM(java_path, '-ea') Edit: Adding the whole test script import jpype import os java_path = "C:\\Program Files\\Java\\jre-10.0.2\\bin\\server\\jvm.dll" # java_path = "C:\\Program Files\\Java\\jre1.8.0_181\\bin\\server\\jvm.dll" # print exists result to be sure the file exists print(os.path.exists(java_path)) jpype.startJVM(java_path, '-ea') print("it works") If I use the Java 10 part, it does not work but if I use the Java 8 part (currently commented), it does work. The first print command prints True in both cases. Thank you in advance, Markus
upvote count: 2
has comment: http://stackoverflow.com/comment/89981763
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54434446
has comment: http://stackoverflow.com/comment/90001242
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/89998139
tagged with: java
tagged with: jpype

http://stackoverflow.com/comment/90228342
type: QuestionComment
has text: @syntonym Messages are made of 16 bits. The MCU does not comprise a floating point unit. The elements are the electrical component, i.e. the DACs, Electrodes, ... that I defined as class. The time is discrete, with a clock ticking at 8 Mhz. I do not need to reproduce the timing aspect, I can for instance make the following: `ticks = range(8000000)` which corresponds to 1 second. Hope it helps :)
comment on: http://stackoverflow.com/q/51631942
score: 0
type: Comment

http://stackoverflow.com/a/51570329
type: Answer
has comment: http://stackoverflow.com/comment/90106806
has body: The idea is to create key for each row in form of (x, idx) where x is the index of the name in the column name_unique which keeps the order of the original name column and contains distinct values only, and idx is the index in the original dataframe In [26]: df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'name': ['a', 'b', 'c', 'b', 'a']}) In [27]: name_ord = {} In [28]: ordering_list = [] In [29]: for idx, value in enumerate(df['name']): ...: if value not in name_ord: ...: name_ord[value] = len(name_ord) ...: ordering_list.append((name_ord[value], idx)) ...: In [30]: df['ord'] = ordering_list In [31]: df.sort_values(by='ord') Out[31]: id name ord 0 1 a (0, 0) 4 5 a (0, 4) 1 2 b (1, 1) 3 4 b (1, 3) 2 3 c (2, 2) Also keeps b on the top in the resulting dataframe if b was in the first row in the original dataframe: In [32]: df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'name': ['b', 'b', 'c', 'a', 'a']}) In [33]: name_ord = {} In [34]: ordering_list = [] In [35]: for idx, value in enumerate(df['name']): ...: if value not in name_ord: ...: name_ord[value] = len(name_ord) ...: ordering_list.append((name_ord[value], idx)) ...: In [36]: df['ord'] = ordering_list In [37]: df.sort_values(by='ord') Out[37]: id name ord 0 1 b (0, 0) 1 2 b (0, 1) 2 3 c (1, 2) 3 4 a (2, 3) 4 5 a (2, 4)
accepted answer of: http://stackoverflow.com/q/51570181
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51570181

http://stackoverflow.com/comment/90074595
has text: The canonical answer discusses extensively the performance differences. If an aspect is not covered by it (memory or CPU use), please specify exactly what you want to know in addition.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51553625
type: Comment

http://stackoverflow.com/q/51553348
upvote count: 1
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/42468715
score: 1
tagged with: selenium
accepted answer: http://stackoverflow.com/a/51553460
has body: from selenium import webdriver driver = webdriver.Chrome() driver.get("chrome://settings") advanced = driver.find_element_by_css_selector("#advancedToggle &gt; span") advanced.click() The above code doesn't work. To see where the advanced variable was referring to, you can go to paste "chrome://settings" in your browser (only works if you're using chrome) and scroll down to the bottom where you see the "Advanced" toggle. That toggle even has an id "advancedToggle" but I can't seem to find anything on this page by any method (id, class, css, xpath). Is it possible that some pages are just automation-resistant (if that's a proper term)? If so, is there any way to tell which pages can't be automated on? I've placed this last question in a block quote because this question was marked as a duplicate, but while the example has appeared somewhere else, I don't think there has been an answer for the question in the block...
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51553460
has title: Are there pages that cannot be automated through Selenium?
duplicate of: http://stackoverflow.com/q/42468715
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/90185791
comment on: http://stackoverflow.com/q/51608964
has text: Yes conda install pandas, and then i did conda update pandas and then i tried pip install pandas==0.22 too
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89973484
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51501708
has text: You need to see this differently. The legend is simply outside of the figure all the time. To expand the figure when saving, you may add `plt.savefig(protein_name + "_violin_plots.jpg", bbox_inches="tight")`
type: Comment

http://stackoverflow.com/a/51622231
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51622185
score: 1
has body: use parser.parse method from dateutil module. You can install it by doing pip install python-dateutil &gt;&gt;&gt; from dateutil import parser &gt;&gt;&gt; parser.parse('Sun 10 May 2015 13:54:36 -0700') datetime.datetime(2015, 5, 10, 13, 54, 36, tzinfo=tzoffset(None, -25200))

http://stackoverflow.com/a/51596840
has comment: http://stackoverflow.com/comment/90164377
has comment: http://stackoverflow.com/comment/90164399
has comment: http://stackoverflow.com/comment/90160824
type: Answer
has comment: http://stackoverflow.com/comment/90163055
has comment: http://stackoverflow.com/comment/90159736
has comment: http://stackoverflow.com/comment/90161057
has comment: http://stackoverflow.com/comment/90159656
score: 0
accepted answer of: http://stackoverflow.com/q/51595563
has body: You can use this xpath : //a[text()='Luke Wilson']/parent::td/preceding-sibling::td[@class='vt']/a Note that based on name Luke Wilson , it will give you requested hyperlink which you can use to right click. In case you want that name to be picked by script dynamically : name = Luke Wilson //a[text()='"+name+"']/parent::td/preceding-sibling::td[@class='vt']/a Hope that helps.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51595563

http://stackoverflow.com/comment/90228761
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51632323
score: 2
has text: You could also comment why the OP is seeing the current behavior, namely because those `x123` column names are sorting as text, and not numbers.

http://stackoverflow.com/a/51489189
answers question: http://stackoverflow.com/q/51489128
has body: You might just match 3 characters surrounded by word boundaries: csvText = ' sdh , ash, vbn' matches = re.findall(r'\b\w{3}\b', csvText)
score: 0
type: Answer

http://stackoverflow.com/q/51620072
tagged with: python
has comment: http://stackoverflow.com/comment/90207086
has comment: http://stackoverflow.com/comment/90211164
tagged with: qt
score: 0
has body: I was looking to implement QRunnable and QThreadPool into my Qt application, where I want to have the GUI continuously listen in the background for microphone input. I have the thread working and it does run, however whenever I try to interact with the GUI the program crashes. import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * class Worker(qt.QRunnable): def widget(self, m, r): self.m = m self.r = r def run(self): with self.m as source: while True: print("listening") self.r.adjust_for_ambient_noise(source) audio = self.r.listen(source) try: print(self.r.recognize_google(audio)) # handles any api/voice errors errors except sr.RequestError: print("There was an issue in handling the request, please try again") except sr.UnknownValueError: print("Unable to Recognize speech") class VoiceRecognitionWidget(ScriptedLoadableModuleWidget): def setup(self): ScriptedLoadableModuleWidget.setup(self) #Initializes recognizer and microphone self.recognizer = sr.Recognizer() try: self.microphone = sr.Microphone() except(IOError): print("ERROR: No default microphone. Check if microphone is plugged in or if you have a default microphone set in your sound settings.") self.errors.setText("ERROR: No default microphone. Check if your microphone is plugged in or if you have a default microphone set in your sound settings.") parametersCollapsibleButton = ctk.ctkCollapsibleButton() parametersCollapsibleButton.text = "Parameters" self.layout.addWidget(parametersCollapsibleButton) # Layout within the dummy collapsible button parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton) self.listenButton = qt.QPushButton("Begin Listneing") self.listenButton.toolTip = "Listens for voice." self.listenButton.enabled = True parametersFormLayout.addRow(self.listenButton) self.stopButton = qt.QPushButton("Stop Listensing") self.stopButton.toolTip = "Stops listening." self.stopButton.enabled = True parametersFormLayout.addRow(self.stopButton) self.repeatButton = qt.QPushButto…
has title: PythonQt QRunnable GUI crashes whenever thread is running
has comment: http://stackoverflow.com/comment/90206051
answer count: 0
has comment: http://stackoverflow.com/comment/90234023
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90231498
tagged with: pythonqt
type: Question
tagged with: multithreading

http://stackoverflow.com/q/51485490
type: Question
linked to: http://stackoverflow.com/q/42380494
score: 0
has comment: http://stackoverflow.com/comment/89940264
has title: Timer to run every 5 minutes (0,5,10,15,etc) 24/7 non stop
has comment: http://stackoverflow.com/comment/89940050
answer count: 0
type: UnansweredQuestion
tagged with: multithreading
tagged with: ifttt
tagged with: python
has body: We're trying to get notifications on the cellphone (using IFTTT) when there are problems with an API service. This is the system status request: status = client.get_system_status() print(status) And this is the json response: {'msg': 'normal', 'status': 0} When the system status enters Maintenance mode, the response change to 'status' : 1. We want to check the system status every round 5 minutes (0,5,10,15,etc) 24/7 non stop, and if a system maintenance is found ('status': 1), send the notification using the code below: import requests data = {"value1":"Attention: System Maintenance"} response = requests.post('https://maker.ifttt.com/trigger/23423/with/key/dLL84tqq34tQlpcwsNPR_mDzoD_2D5yRLv8LNG8NVDElxbsfMi', json=data) print (response.status_code) Which would be the best way to do it?
has comment: http://stackoverflow.com/comment/89942075
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/90113921
type: Comment
comment on: http://stackoverflow.com/q/51573969
has text: Looks like https://stackoverflow.com/questions/28669482/appending-pandas-dataframes-generated-in-a-for-loop works quite well.
score: 0
type: QuestionComment

http://stackoverflow.com/q/51612114
favorite count: 0
accepted answer: http://stackoverflow.com/a/51612282
has body: I have two files a.txt and b.txt, So i am trying to compare using hash like below. #getting hash of files and comparing file1 = hashlib.md5(open('a.txt', 'rb').read()).hexdigest() file2 = hashlib.md5(open('b.txt', 'rb').read()).hexdigest() file1==file2--&gt; returns True or False this is one way and also we can do using filecmp as below filecmp.cmp('a.txt','b.txt')--&gt; returns True or False In both of these ways which is better and why?
tagged with: python
has comment: http://stackoverflow.com/comment/90189124
has comment: http://stackoverflow.com/comment/90189080
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51612282
upvote count: 0
has comment: http://stackoverflow.com/comment/90221656
linked to: http://stackoverflow.com/q/4032209
has comment: http://stackoverflow.com/comment/90221703
type: Question
score: -2
has comment: http://stackoverflow.com/comment/90189091
tagged with: hashlib
downvote count: 2
has comment: http://stackoverflow.com/comment/90189115
answer count: 1
has title: Best way of comparing two files in python and why?

http://stackoverflow.com/q/51494185
type: Question
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51503238
has body: Scipy(Python): from scipy import stats a=[3,4,5,8,9,1,2,4,5,3,8] b=[6,19,3,2,14,4,5,17,1,2,4] stats.ttest_ind(a,b, equal_var=True) Ttest_indResult(statistic=-1.0810463365416798, pvalue=0.29254014390233507) Excel: The result of Scipy is 0.292540, Excel is 0.293487. What the correct grammar to make the result of Scipy like the TTEST(a, b, 2, 1)?
favorite count: 0
tagged with: python
has title: Why ttest_ind in Scipy a little different from Excel TTest?
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: scipy
has answer: http://stackoverflow.com/a/51503238
tagged with: excel

http://stackoverflow.com/comment/89974906
type: Comment
has text: What does xxx stand for? If you manually ssh to the host and execute xxx, does it hang, or wait for input? My guess is that xxx waits for input, but your script does not feed xxx with the requested input.
comment on: http://stackoverflow.com/q/51500947
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90025667
comment on: http://stackoverflow.com/q/51528341
has text: What do you mean nothing happens? It doesn't apply the change in place so your command basically creates a new variable.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90074293
comment on: http://stackoverflow.com/a/51553536
score: 0
type: AnswerComment
has text: thanks! is this because i can't change the string at the original place? So i have to assign it to a new name? It is not like list.append(), right?
type: Comment

http://stackoverflow.com/comment/90100427
score: 0
type: AnswerComment
type: Comment
has text: @Rob, edited. When I ran your loop, I thought it got rid of the blank string, but I must have misread.
comment on: http://stackoverflow.com/a/51566820

http://stackoverflow.com/a/56082182
has body: You can use eval or ast.literal_eval as below. data = "b'gAAAAABc1arg48DmsOwQEbeiuh-FQoNSRnCOk9OvXXOE2cbBe2A46gmP6SPyymDft1yp5HsoHEzXe0KljbsdwTgPG5jCyhMmaA=='" eval(data) b'gAAAAABc1arg48DmsOwQEbeiuh-FQoNSRnCOk9OvXXOE2cbBe2A46gmP6SPyymDft1yp5HsoHEzXe0KljbsdwTgPG5jCyhMmaA==' Using ast.literal_eval import ast ast.literal_eval(data) thanks to @juanpa.arrivillaga. I just added to answer.
type: Answer
answers question: http://stackoverflow.com/q/51489961
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/comment/90205378
comment on: http://stackoverflow.com/a/51619701
has text: Good suggestion, however, at some point I need to use the information regarding the depth of each element in my parse tree. So I am not quite sure if by turning the tree into a list as you mentioned I can keep the structural information of the tree.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51576690
upvote count: 3
has comment: http://stackoverflow.com/comment/90131252
answers question: http://stackoverflow.com/q/51576635
type: Answer
has comment: http://stackoverflow.com/comment/90128389
score: 3
downvote count: 0
has body: One can invert all y values by subtracting them from its maximum so that one can then plot it without inverting y axis in matplotlib. y = max(y) - y The plot result will remain the same.

http://stackoverflow.com/a/51537018
type: Answer
accepted answer of: http://stackoverflow.com/q/51536771
has body: You should convert your Ouput[2] to a map (a pandas series), e.g.: df2.ID = df2.ID.apply(lambda x: x[0]) s2 = df2.set_index('ID')['ALT_NAME'] # let us rename it s2 as it is a series now! When that is done you can simply use apply and fetch the values with a list comprehension: df1['ALT NAME'] = df1.ID.apply(lambda x: [s2.get(i,None) for i in x]) print(df1) Returns: ID NAME ALT NAME 0 [1111] foo [foo_alt] 1 [2222, 3333] bar [bar_alt, zoo_alt] 2 [4444, 5555] zoo [baoo, razz] 3 [6666] bahh [None] Small comment: This does not give you the nan in last row. But what if you have 1 match and 1 none match, is that not [match1, None]?. Df2 after conversion to s2: ID 1111 foo_alt 2222 bar_alt 3333 zoo_alt 4444 baoo 5555 razz 7777 foo fi one-row version: s2 = df2.assign(ID=df2.ID.apply(lambda x: x[0])).set_index('ID')['ALT_NAME']
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/90041734
has comment: http://stackoverflow.com/comment/90056349
has comment: http://stackoverflow.com/comment/90042971
type: AcceptedAnswer
upvote count: 3
answers question: http://stackoverflow.com/q/51536771

http://stackoverflow.com/q/51623428
answer count: 0
has comment: http://stackoverflow.com/comment/90213788
tagged with: tensorflow
type: Question
has title: How do I prevent failed to create session error in keras?
tagged with: anaconda
has comment: http://stackoverflow.com/comment/90245927
score: 0
has body: I am new to tensorflow and Keras, below is my code import numpy as np np.random.seed(123) # for reproducibility from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from keras.datasets import mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() # 5. Preprocess input data X_train = X_train.reshape(X_train.shape[0], 28, 28, 1) X_test = X_test.reshape(X_test.shape[0], 28, 28, 1) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 # 6. Preprocess class labels Y_train = np_utils.to_categorical(y_train, 10) Y_test = np_utils.to_categorical(y_test, 10) # 7. Define model architecture model = Sequential() model.add(Convolution2D(32, 3, 3, activation='relu', input_shape= (28,28,1))) model.add(Convolution2D(32, 3, 3, activation='relu')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) # 8. Compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # 9. Fit model on training data model.fit(X_train, Y_train, batch_size=32, nb_epoch=10, verbose=1) # 10. Evaluate model on test data score = model.evaluate(X_test, Y_test, verbose=0) I keep getting the following error after running this code 2018-07-31 19:25:45.099850: I C:\users\nwani_bazel_nwani\mmtm6wb6\execroot\org_tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2 2018-07-31 19:25:45.711357: I C:\users\nwani_bazel_nwani\mmtm6wb6\execroot\org_tensorflow\tensorflow\core\common_runtime\gpu\gpu_device.cc:1356] Found device 0 with properties: name: GeForce 840M major: 5 minor: 0 memoryClockRate(GHz): 1.124 pciBusID: 0000:04:00.0 totalMemory: 2.00GiB freeMemory: 1.…
tagged with: keras
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/89981587
has text: if we split only displays 1 word but i want two words three words etc...
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51506227

http://stackoverflow.com/comment/90078129
has text: I was just putting pieces together based on the limited exposure I had to pyparsing so far, and `infixNotation` was the only hammer I really knew. ;) Thank you!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51555489
type: Comment

http://stackoverflow.com/comment/90325490
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51661344
has text: Not a problem at all. Please just create separate questions and I will be happy to answer them all to the best of my ability!

http://stackoverflow.com/comment/90856881
comment on: http://stackoverflow.com/a/51832037
has text: It should be `return Markup(' ' % form.thumbgen_filename(model.MediaPath))` and again this is assuming that `thumbgen_filename()` will take the path from that column an generate a path for the thumbnail. the `model` argument that is passed to the `_list_thumbnail` formatter gives you access to all the columns. Just use `model.columnName` when you want to access a certain column. In your case, `model.MediaPath`
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90265300
type: AnswerComment
has text: it still says 'play game at none' rather than 'play game at a level'
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51615979

http://stackoverflow.com/q/51622109
has comment: http://stackoverflow.com/comment/90235113
answer count: 0
type: UnansweredQuestion
tagged with: django
has body: I have copied my Django 1.4.3 app from one server to another. It is running using mod_wsgi daemon on the other server. mod_python is installed, as verified by looking at php.info(). Python version is 2.7, and Apache version is 2.4. I get the following error whenever I run manage.py runserver 0.0.0.0:8000: Traceback (most recent call last): File "./manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 252, in fetch_command app_name = get_commands()[subcommand] File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 101, in get_commands apps = settings.INSTALLED_APPS File "/usr/lib/python2.7/site-packages/django/utils/functional.py", line 184, in inner self._setup() File "/usr/lib/python2.7/site-packages/django/conf/__init__.py", line 42, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python2.7/site-packages/django/conf/__init__.py", line 128, in __init__ logging_config_module = importlib.import_module(logging_config_path) File "/usr/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/lib/python2.7/site-packages/django/utils/log.py", line 6, in &lt;module&gt; from django.views.debug import ExceptionReporter, get_exception_reporter_filter File "/usr/lib/python2.7/site-packages/django/views/debug.py", line 9, in &lt;module&gt; from django.http import (HttpResponse, HttpResponseServerError, File "/usr/lib/python2.7/site-packages/django/http/__init__.py", line 19, in &lt;module&gt; from mod_python.util import parse_qsl File "/usr/lib64/python2.7/site-packages/mod_python/__init__.py", line 2…
has comment: http://stackoverflow.com/comment/90210555
has title: Django - running manage.py produces fatal error for version.py: Not a git repository
tagged with: mod-wsgi
type: Question
score: 0
tagged with: apache
tagged with: python-2.7
tagged with: python

http://stackoverflow.com/a/51495316
has comment: http://stackoverflow.com/comment/89960204
has body: One option is to use MySQLdb. Then you can change: cursor = connection.cursor() To: cursor = connection.cursor(MySQLdb.cursors.DictCursor) and access the values by field names instead indexes.
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89961867
upvote count: 5
accepted answer of: http://stackoverflow.com/q/51493860
type: Answer
answers question: http://stackoverflow.com/q/51493860
downvote count: 0

http://stackoverflow.com/comment/90074082
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51553492
has text: Pass important_arg as an arg into `worker.run()` and hence to `helper.dosth()`

http://stackoverflow.com/comment/89976554
comment on: http://stackoverflow.com/q/51503591
score: 0
type: Comment
type: QuestionComment
has text: @abarnert I'm not. I just needed a few minutes to read through the comments and update my answer. Regardless, I don't think simple yes or no questions should be downvoted unless they are off-topic.

http://stackoverflow.com/q/51567301
answer count: 0
has body: This is my Program, Text Extraction from Image program: import pytesseract from PIL import Image import os from os.path import join import sys con_1 = True store_1 = [] store_2 = [] store_3 = [] con_1 = True print("Welcome to my Text Extraction from Image Program. Here you can extract text from any image.") while con_1: image_name = input("Enter your image's name:") for root, dirs, files in os.walk("/home/"): if image_name in files: found = join(root, image_name) store_1.append(found) if len(store_1) == 0: ask_1 = str(input("Your image was not found. Do you want to try again(Y/n)?:")) if ask_1 == "Y" or ask_1 == "y": con_1 = True elif ask_1 == "N" or ask_1 == "n": con_1 = False else: print("Your input is out of bounds. Please try again.") else: print("Your image was successfully found.") image_open = Image.open(found) image_text = pytesseract.image_to_string(image_open) print(image_text) break This is the image I am testing it on: And this is the most weirdest output I have ever seen: ‘Understanding how computer memory ia tire terrae tec programming lan This is another image I am testing it on: And another really weird output: Sesh chee nia ec Hiok pc RU hun oe mete een machines work while still being easy to learn. I have never seen my program giving me such off-target and weird outputs. I have absolutely no idea how this is happening. I would very much like to know how to fix it as well as why my program is malfunctioning.
type: UnansweredQuestion
upvote count: 1
has title: Very Wierd Output, for my text extraction program
tagged with: python-imaging-library
score: 1
tagged with: image
type: Question
downvote count: 0
tagged with: python
favorite count: 0
tagged with: python-3.x
tagged with: python-tesseract

http://stackoverflow.com/comment/89977273
has text: It still 2% faster though ;)
type: AnswerComment
comment on: http://stackoverflow.com/a/51504245
type: Comment
score: 1

http://stackoverflow.com/comment/89986036
type: QuestionComment
comment on: http://stackoverflow.com/q/51508514
score: 1
has text: `a.index(max(a))` [works for me](https://ideone.com/d6quNx). Can you show an entire program that demonstrates your issue?
type: Comment

http://stackoverflow.com/q/51487339
has comment: http://stackoverflow.com/comment/90052184
downvote count: 0
tagged with: keras
favorite count: 0
has body: I'm trying to convert my Deep learning network written in Matlab to Python via Keras libraries. Network's task is to recognize specific note in given image, and return single character corresponding to specific sound name ('from 'a' to 'h') Code in Matlab: digitDatasetPath = fullfile('zbior_uczacy'); imds = imageDatastore(digitDatasetPath, ... 'IncludeSubfolders',true,'LabelSource','foldernames'); labelCount = countEachLabel(imds) img = readimage(imds,1); size(img) numTrainFiles = 1200; [imdsTrain,imdsValidation] = splitEachLabel(imds,numTrainFiles,'randomize'); layers = [ imageInputLayer([50 30 1]) convolution2dLayer(6,12,'Padding',1) reluLayer maxPooling2dLayer(2,'Stride',2) convolution2dLayer(6,24,'Padding',1) reluLayer maxPooling2dLayer(2,'Stride',2) convolution2dLayer(6,48,'Padding',1) reluLayer fullyConnectedLayer(7) softmaxLayer classificationLayer]; options = trainingOptions('sgdm', ... 'LearnRateSchedule', 'piecewise', ... 'LearnRateDropFactor', 0.3, ... 'LearnRateDropPeriod', 5, ... 'MaxEpochs', 50, ... 'MiniBatchSize', 300); net = trainNetwork(imdsTrain,layers,options); YPred = classify(net,imdsValidation); YValidation = imdsValidation.Labels; accuracy = sum(YPred == YValidation)/numel(YValidation) Code has been already tested, working fine. Now I'm trying to convert this code into Keras code. Full code here: import numpy as np import cv2 from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten, Input from keras.layers import Convolution2D, MaxPooling2D from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img from keras import backend as K from keras.preprocessing import image print("\n") print("\n") trained_weights = [] trained_bias = [] trained_weights = np.loadtxt('Weights.csv', delimiter=';') trained_bias = np.loadtxt('Bias.csv', delimiter=';') network_weights = np.array(trained_weights) network_outputs = np.array('a','c','d','e','f','g','h') # Load test image img = …
type: UnansweredQuestion
tagged with: python
tagged with: matlab
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/90054567
upvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/89943814
has title: ValueError: Error when checking input: expected conv2d_1_input to have shape (None, 50, 30, 3) but got array with shape (1, 3, 50, 30)
has comment: http://stackoverflow.com/comment/89965868
has comment: http://stackoverflow.com/comment/89949423
tagged with: deep-learning

http://stackoverflow.com/q/51521364
has body: i have an aplication homestay reservation built with flask.. every homestay have an user login, this login built with flask-security and every owner of the homestay have role User. and every user can input their homestay data with flask-admin. but unfortunately if a user input their data, the others user which have role User can seing the data have input too.. so.. my question how to separate the data if a user have the same role..? user A can just see his data, and user B so too.. this is my models.py code: roles_users = database.Table( 'roles_users', database.Column('user_id', database.Integer(), database.ForeignKey('user.id')), database.Column('role_id', database.Integer(), database.ForeignKey('role.id')) ) class Role(database.Model, RoleMixin): id = database.Column(database.Integer(), primary_key=True) name = database.Column(database.String(80), unique=True) description = database.Column(database.String(255)) def __str__(self): return self.name class User(database.Model, UserMixin): id = database.Column(database.Integer, primary_key=True) first_name = database.Column(database.String(255)) last_name = database.Column(database.String(255)) email = database.Column(database.String(255), unique=True) password = database.Column(database.String(255)) active = database.Column(database.Boolean()) confirmed_at = database.Column(database.DateTime()) roles = database.relationship('Role', secondary=roles_users, backref=database.backref('users', lazy='dynamic')) def __str__(self): return self.email class Room(database.Model): __tablename__ = 'room' room_id = Column(Integer, primary_key=True) room_name = Column(String) room_description = Column(String) room_images = Column(database.Unicode(128)) room_price = Column(Integer) user_id = Column(Integer, ForeignKey(User.id)) and this is my views.py : class UserAccess(ModelView): def is_accessible(self): if not current_user.is_active or not current_user.is_authenticated: return False if current_user.has_role('user'): return True ret…
has answer: http://stackoverflow.com/a/51570014
answer count: 1
tagged with: flask-security
has title: flask security separating access data on flask admin
tagged with: flask-sqlalchemy
tagged with: flask-admin
tagged with: python
accepted answer: http://stackoverflow.com/a/51570014
type: AnsweredQuestion
score: 0
type: Question
tagged with: flask

http://stackoverflow.com/a/51586698
has comment: http://stackoverflow.com/comment/90138883
score: 2
has body: Unfortunately, Python doesn't allow you to do that in a comprehension. However, you can do this: values = [1 if char.isalpha() else 2 for char in string if char.isalnum()] (where char.isalnum() if and only if char.isalpha() or char.isdigit().) You can also do values = [value for value in (1 if char.isalpha() else 2 if char.isalnum() else None for char in string) if value] or its equivalent (thanks for the reminder, AChampion) values = list(filter(None, (1 if char.isalpha() else 2 if char.isalnum() else None for char in string))) to get rid of the None, though I am not sure how fast/not fast it is (it is not building a new list, just using a generator, so the slowdown might be quite imperceptible).
answers question: http://stackoverflow.com/q/51586643
downvote count: 0
has comment: http://stackoverflow.com/comment/90138796
has comment: http://stackoverflow.com/comment/90138766
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/90138821

http://stackoverflow.com/comment/133892318
comment on: http://stackoverflow.com/q/51567750
type: Comment
type: QuestionComment
has text: PyPDF2 is deprecated since 2022. Use pypdf.
score: 1

http://stackoverflow.com/comment/109212098
type: Comment
score: 1
type: AnswerComment
has text: @Lucho you can set a global environment variable by something like this: https://stackoverflow.com/questions/1641477/how-to-set-environment-variable-for-everyone-under-my-linux-system
comment on: http://stackoverflow.com/a/53375405

http://stackoverflow.com/comment/90167935
type: Comment
has text: @ZeddCodes_ no. For the same reason. Also, since your `if` condition can only be true or false, you don't need to use `elif` (when there are multiple "else" possibilities), or even `else` (which would be OK to use, but unnecessary since this assignment can be done just by evaluating the boolean expression and assigning that value to the `VowelsInString`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51600703

http://stackoverflow.com/comment/89974731
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51502359
has text: Makes sense that this is the fastest because `searchshorted` can short circuit. My solution computes the intervals in a different way, but it requires comparing each value in `sample` to each interval. Would you mind benchmarking `[next(i for i in intervals if i>s) for s in sample]` - it obviously has the for loop, but I am wondering how much the `next()` saves in time. @ascripter
type: AnswerComment

http://stackoverflow.com/comment/90168281
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51600986
has text: Try running `conda install pandas` from the command line, and if that doesn't work, try `pip install pandas`. You should also check to make sure pandas was installed by running `pip show pandas` from the command line. pandas isn't automatically downloaded with conda
type: Comment

http://stackoverflow.com/a/51601851
answers question: http://stackoverflow.com/q/51601761
has body: You're invoking a shell to run start that will run a CMD to run your BAT file! That means you want to run a subprocess, but end up starting FOUR instead! Don't use shell=True Don't use start unless you really need it Don't execute CMD By doing this you can just pass your parameters as a list and it will work: dir = r"f:\_Python" cmdline = ["setENVvariables.bat", UID, PSWD] rc = call(cmdline, cwd=dir)
score: 0
has comment: http://stackoverflow.com/comment/90169922
has comment: http://stackoverflow.com/comment/90169902
type: Answer

http://stackoverflow.com/comment/89973959
has text: @whitek1ght, you can use different [virtual environment](https://docs.python.org/3/tutorial/venv.html)s to run a specific version of Python.
comment on: http://stackoverflow.com/q/51502708
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51488130
has comment: http://stackoverflow.com/comment/89952592
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89952669
type: Answer
has comment: http://stackoverflow.com/comment/89991313
has comment: http://stackoverflow.com/comment/89967225
accepted answer of: http://stackoverflow.com/q/51487549
answers question: http://stackoverflow.com/q/51487549
upvote count: 10
downvote count: 1
has body: Try MeanShift. From the sklean user guide of MeanShift: The algorithm automatically sets the number of clusters, ... Modified demo code: import numpy as np from sklearn.cluster import MeanShift, estimate_bandwidth # ############################################################################# # Generate sample data X = [1,2,4,7,9,5,4,7,9,56,57,54,60,200,297,275,243] X = np.reshape(X, (-1, 1)) # ############################################################################# # Compute clustering with MeanShift # The following bandwidth can be automatically detected using # bandwidth = estimate_bandwidth(X, quantile=0.2, n_samples=100) ms = MeanShift(bandwidth=None, bin_seeding=True) ms.fit(X) labels = ms.labels_ cluster_centers = ms.cluster_centers_ labels_unique = np.unique(labels) n_clusters_ = len(labels_unique) print("number of estimated clusters : %d" % n_clusters_) print(labels) Output: number of estimated clusters : 2 [0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1] Note that MeanShift is not scalable with the number of samples. The recommended upper limit is 10,000. BTW, as rahlf23 already mentioned, K-mean is an unsupervised learning algorithm. The fact that you have to specify the number of clusters does not mean it is supervised. See also: Overview of clustering methods Choosing the right estimator
score: 9
has comment: http://stackoverflow.com/comment/111095091
has comment: http://stackoverflow.com/comment/89990557

http://stackoverflow.com/q/51629294
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51630076
type: Question
tagged with: python
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51630076
has comment: http://stackoverflow.com/comment/90222837
has body: In below programming, first we redirect all print to log files, then we close the file object and then again restort print command to interactive prompt. import sys temp = sys.stdout # store original stdout object for later sys.stdout = open('log.txt', 'w') # redirect all prints to this log file print("testing123") # nothing appears at interactive prompt print("another line") # again nothing appears. it's written to log file instead sys.stdout.close() # ordinary file object sys.stdout = temp # restore print commands to interactive prompt print("back to normal") # this shows up in the interactive prompt Why python doesn't support a method something like this, to restore the command to interactive mode sys.stdout.default()
has comment: http://stackoverflow.com/comment/90222930
type: AnsweredQuestion
has title: Why sys.stdout (in python) doesn't have default method to restore to default value
has comment: http://stackoverflow.com/comment/90223055

http://stackoverflow.com/comment/90043702
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51537967
has text: Oh, good. You get an up vote then. Any particular reason you've picked Python 2 for your hack?

http://stackoverflow.com/a/51524178
accepted answer of: http://stackoverflow.com/q/51505142
answers question: http://stackoverflow.com/q/51505142
has body: I found the problem. It is because the interpreter I specified cannot be found by the server. system(...) line actually doesn't run at all. The reason that I didn' t see any error is because system() hides the error for me. Actually the return value of system() is -1, which means something wrong. I should have checked the return value
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/q/51540659
tagged with: pandas
upvote count: 1
answer count: 1
tagged with: jupyter
favorite count: 0
has answer: http://stackoverflow.com/a/51540691
accepted answer: http://stackoverflow.com/a/51540691
has title: How can I extract unique strings from a Dataframe column?
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: numpy
has body: I have a dataframe 'df_copy' which has a column 'genres'. In the column, each entry has single or multiple genres. Something like this I wish to extract all the unique genres that are present in the column. How can I do this?
score: -1
downvote count: 2

http://stackoverflow.com/comment/90203388
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51618435
has text: Thx 4 all of your answer! I guess my next question would now be how to properly read from the event queue?

http://stackoverflow.com/comment/90135354
score: 0
comment on: http://stackoverflow.com/q/51584734
type: Comment
has text: See [@DYZ's answer](https://stackoverflow.com/a/51584791/9209546).
type: QuestionComment

reset
tags question: http://stackoverflow.com/q/51598745
type: Tag
tag name: reset

http://stackoverflow.com/a/51608403
answers question: http://stackoverflow.com/q/51605036
has body: I would recommend to familiarize yourself with CoNNL-U Format. http://universaldependencies.org/format.html And possibly also UDPipe https://lindat.mff.cuni.cz/services/udpipe/
type: Answer
score: 0

http://stackoverflow.com/comment/90119186
comment on: http://stackoverflow.com/a/51576883
score: 0
type: AnswerComment
type: Comment
has text: I copied your code and it's still not working on `Python 2.7.15 |Anaconda, Inc.| (default, May 1 2018, 18:37:09) [MSC v.1500 64 bit (AMD64)] on win32`. It prints `u'a?b?c'`

http://stackoverflow.com/comment/89950112
type: Comment
has text: use ** operator maybe
comment on: http://stackoverflow.com/q/51490738
score: 0
type: QuestionComment

http://stackoverflow.com/a/51523153
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51522976
has body: There are most likely better ways, but this one should work too: df['previous'] = df.signal.shift() def get_signal_value(row): if row.signal == 0: compare = row.previous - 0.02 if compare &lt; -1: return -1 else: return compare elif row.signal == 1: compare = row.previous + 0.01 if compare &gt; 1: return 1 else: return compare df['new_signal'] = df.apply(lambda row: get_signal_value(row), axis=1)

http://stackoverflow.com/a/51635395
score: 3
has body: Notice your column type right now is string not numeric anymore df = df.apply(lambda x : pd.to_numeric(x, errors='coerce')) df['xy'] = df.sum(1) More df['xy'] =df'x','y'.astype(str).apply(''.join,1) #df'x','y'.astype(str).apply(''.join,1) Out[655]: 0 1.0 1 2.0 2 3 4.0 4 8.0 dtype: object
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90235413
answers question: http://stackoverflow.com/q/51635290
upvote count: 3

http://stackoverflow.com/comment/89969924
has text: Hello! Thank you so much. I am getting "yield f'{line1}\n<{total_time} {singular_or_plural}>' ^ SyntaxError: invalid syntax" and when I remove the "f" I get this as output: {line1} <{total_time} {singular_or_plural}> {line1} <{total_time} {singular_or_plural}> {line1} <{total_time} {singular_or_plural}> {line1} <{total_time} {singular_or_plural}> {line1} <{total_time} {singular_or_plural}> {line1} <{total_time} {singular_or_plural}> {line2}
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51491949

http://stackoverflow.com/a/51490129
answers question: http://stackoverflow.com/q/51489871
type: Answer
has comment: http://stackoverflow.com/comment/89985625
has comment: http://stackoverflow.com/comment/89962899
score: 1
has comment: http://stackoverflow.com/comment/90068146
upvote count: 1
downvote count: 0
has body: In your last line, you are joining daemon processes. Per Python documentation: Note that a daemonic process is not allowed to create child processes. Otherwise a daemonic process would leave its children orphaned if it gets terminated when its parent process exits. Additionally, these are not Unix daemons or services, they are normal processes that will be terminated (and not joined) if non-daemonic processes have exited.
has comment: http://stackoverflow.com/comment/90007126

http://stackoverflow.com/comment/89966800
score: 0
comment on: http://stackoverflow.com/q/51499045
type: Comment
type: QuestionComment
has text: This is a horrible idea; `locals()` is not guaranteed to be writable. The proper way to handle an import of an optionally-installed module is to do it in a `try`...`except ImportError:` block.

http://stackoverflow.com/a/51547059
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51546913
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51546913
has body: You have two instances of pip installed. When you called pip --version, the package it looks at is within C:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages When you called python -m pip install --upgrade pip, the package that was "already up-to-date" is located in C:\users\rule\appdata\local\programs\python\python37-32\lib\site-packages To use the pip package that is already up-to-date, you can either CD into this directory and call pip, or (better yet), change your PATH variable from the prior path to the latter. To edit PATH environmental variables, you can reference this page. Look for the path that I listed first, and replace it with the path I listed second.
type: Answer

http://stackoverflow.com/comment/90230308
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51628451
has text: @Programmer120 , it means your API is not returning you a json string. Print it out and also print the `type(responsedata)`. Take a look, a json string means it should be a string, but with structure, for example `"{response:[{field:'sample'}]}"`
score: 0

http://stackoverflow.com/q/51594411
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: opencv
answer count: 0
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90155118
downvote count: 0
has title: Interpretation of projectPoints() function
has body: I am working on converting 3D real-world points (X,Y,Z) meters to image coordinates (u, v) pixels. I have access to the Camera matrix K, camera orientation (in degrees) and translation vector. I use the code below to calculate the pixel coordinates. For (X,Y,Z) = (0.04379281, 0.15902013, 0.73328906), I obtain (u, v) = (-184.52735432, -249.19158505) on an image of size 352x287 px. Is the origin of pixel coordinates in the image still top left corner? If yes, the obtained pixel location is outside the image. Is this right? # Calculates Rotation Matrix given euler angles. def eulerAnglesToRotationMatrix(theta): R_x = np.array([[1, 0, 0], [0, math.cos(theta[0]), -math.sin(theta[0])], [0, math.sin(theta[0]), math.cos(theta[0])] ]) R_y = np.array([[math.cos(theta[1]), 0, math.sin(theta[1])], [0, 1, 0], [-math.sin(theta[1]), 0, math.cos(theta[1])] ]) R_z = np.array([[math.cos(theta[2]), -math.sin(theta[2]), 0], [math.sin(theta[2]), math.cos(theta[2]), 0], [0, 0, 1] ]) R = np.dot(R_z, np.dot(R_y, R_x)) return R # x-roll, y-pitch, z-yaw (in degrees) theta = [-128.41639709472657, -11.528900146484375, 53.37379837036133] # rotation vector rvec = eulerAnglesToRotationMatrix(theta) # translation vector tvec = np.array([[0.26409998536109927], [1.294700026512146], [0.017799999564886094]], np.float) # camera matrix cameraMatrix = np.array([[148.130859375, 0, 142.5562286376953], [0, 148.130859375, 179.04293823242188], [0, 0, 1]], np.float) # Point in (X,Y,Z) meters objPts = np.array([[0.04379281, 0.15902013, 0.73328906]], np.float) distCoeffs = np.array([0, 0, 0, 0, 0], np.float) imgPts, _ = cv2.projectPoints(objPts, rvec, tvec, cameraMatrix, distCoeffs)

http://stackoverflow.com/comment/90093167
type: QuestionComment
has text: @WarrenWeckesser Thanks for the suggestion. I have done it and posted the matrix again.
comment on: http://stackoverflow.com/q/51562302
score: 0
type: Comment

http://stackoverflow.com/q/51633605
tagged with: mobaxterm
tagged with: matplotlib
answer count: 0
downvote count: 0
type: UnansweredQuestion
has title: Why can't display or plot graphs/charts in Mobaxterm terminal using python libraries
score: 1
favorite count: 0
type: Question
has body: I'm trying to plot a graph having from a DataFrame, having two columns (date and values), I used "matplotlib", "gnuplot" and many other libraries but without getting any wanted result. For example I'm using this simple code : import matplotlib.pyplot as plt X = [590,540,740,130,810,300,320,230,470,620,770,250] Y = [32,36,39,52,61,72,77,75,68,57,48,48] plt.scatter(X,Y) plt.show() But I keep getting this error message when using matplotlib and it's a authorisation problem : QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root' MobaXterm X11 proxy: Unsupported authorisation protocol qt.qpa.screen: QXcbConnection: Could not connect to display localhost:10.0 Any help would be appreciated and I'm open to alternative propositions.
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/90210345
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51622452
score: 0
has text: https://drive.google.com/file/d/1QbadA-CHSjNrPvDN0UuIx1NQwyTWnJyU/view?usp=sharing this is a little sample

http://stackoverflow.com/comment/89985458
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51507607
type: Comment
has text: is it possible to hide the index header (Col1)? Also, in some pivot_table appear two index headers, is it possible to hide them?Thanks a lot.

http://stackoverflow.com/q/51553046
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90073968
score: 0
has comment: http://stackoverflow.com/comment/103303735
favorite count: 0
has body: I have encountered an error when I run the following code. I want to remove stopwords, however it doesn't work! def cut_txt(old_file): from string import punctuation import jieba jieba.load_userdict("user_dictionary.csv") stopwords = [line.strip().decode('utf-8') for line in open('stop_words.txt').readlines() ] global cut_file # 分词之后保存的文件名 cut_file = old_file + '_cut.txt' try: fi = open(old_file, 'r', encoding='utf-8') except BaseException as e: # 因BaseException是所有错误的基类，用它可以获得所有错误类型 print(Exception, ":", e) # 追踪错误详细信息 text = fi.read() # 获取文本内容 new_text = jieba.cut(text, cut_all=False) # 精确模式 str_out = ' '.join(new_text).replace('，', '').replace('。', '').replace('？', '').replace('！', '') \ .replace('“', '').replace('”', '').replace('：', '').replace('…', '').replace('（', '').replace('）', '') \ .replace('—', '').replace('《', '').replace('》', '').replace('、', '').replace('‘', '') \ .replace('’', '').replace(',', '').replace('【', '').replace('】', '').replace('"', '')\ .replace('#','').replace('...','').replace('?','').replace('『','') # 去掉标点符号 #去除停用词 final = '' for seg in str_out: seg = seg.encode('gbk') if seg not in stopwords: final += seg fo = open(cut_file, 'w', encoding='utf-8') fo.write(final) cut_txt('你的天空')
type: UnansweredQuestion
has title: remove stopwords using jieba in Python
tagged with: python
tagged with: nlp
tagged with: stop-words
answer count: 0
upvote count: 1

http://stackoverflow.com/comment/90043190
comment on: http://stackoverflow.com/a/51537047
type: AnswerComment
type: Comment
has text: @askd https://wiki.videolan.org/Python_bindings will be better for you.
score: 1

http://stackoverflow.com/q/51625336
has comment: http://stackoverflow.com/comment/90215524
has answer: http://stackoverflow.com/a/51625515
tagged with: operating-system
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90215434
possible better answer: http://stackoverflow.com/a/76419489
score: 10
has answer: http://stackoverflow.com/a/76419489
upvote count: 11
favorite count: 0
has comment: http://stackoverflow.com/comment/90215669
answer count: 2
tagged with: python
downvote count: 1
accepted answer: http://stackoverflow.com/a/51625515
tagged with: file
has comment: http://stackoverflow.com/comment/90215458
has body: I have written code to find out common files between two given folders (paths) accounting for all levels of sub folders if present. Please suggest if there is a more efficient method. It's taking too long if folders with many levels of subfolders are given. def findCommonDeep(self,path1,path2): commonfiles = [] for (dirpath1, dirname1, filenames1) in os.walk(path1): for file in filenames1: for (dirpath2, dirname2, filenames2) in os.walk(path2): if (file in filenames2 and isfile(join(dirpath2, file))): commonfiles.append(file) print(commonfiles) and calling this function with paths, like shown below: findCommonDeep("/home/naseer/Python", "/home/naseer/C") I understand that if I store a list of all files for any given path the speed of execution can be reduced. but I guess that will run out of memory. Please guide me in approaching to this more efficiently.
has title: Efficient Method of finding common files between two given paths in Python
type: Question

http://stackoverflow.com/a/52409881
type: Answer
upvote count: 1
has body: What version of rasa-core are you using? For e.g. on my mac Below are versions. pip freeze |grep -i rasa rasa-core==0.8.2 rasa-core-sdk==0.11.4 rasa-nlu==0.11.4 for rasa-core==0.8.2 class KerasPolicy is in python3.6/site-packages/rasa_core/policies/keras_policy.py. Hence you would import it using, from rasa_core.policies.keras_policy import KerasPolicy However, if you are using latest version rasa-core. for e.g. pip freeze |grep -i rasa rasa-core==0.12.0a3 rasa-core-sdk==0.11.4 rasa-nlu==0.13.3 Then class KerasPolicy is in /python3.6/site-packages/rasa_core/policies/keras_policy.py . Hence you would import it using from rasa_core.policies.keras_policy import KerasPolicy It appears that you are using an older version of rasa-core and trying newer versions based example. You need to upgrade both rasa-core and rasa-nlu. Here's link to latest requirement.txt that you can download. After that simply run following to get dependencies installed along-with rasa-core and rasa-nlu. pip install -r requirement.txt
answers question: http://stackoverflow.com/q/51588632
has comment: http://stackoverflow.com/comment/99692727
downvote count: 0
score: 1

http://stackoverflow.com/comment/90218576
comment on: http://stackoverflow.com/q/51626953
score: 0
type: Comment
type: QuestionComment
has text: Well `7/31/2018` isn't a double precision number, it´s a date. Edit: Sorry, that wasn't very informative. It looks to me like your `LastTradeDate` column expects a double, is that correct?

http://stackoverflow.com/comment/90243377
comment on: http://stackoverflow.com/q/51639462
has text: And if that's not a string then you don't have all those digits.
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51641236
downvote count: 0
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/93293153
has comment: http://stackoverflow.com/comment/90274563
answers question: http://stackoverflow.com/q/51638347
type: Answer
has body: That is essentially what I am doing. I created a module (interactions.py) that has, for example a function like this: async def get(url, headers=None, **kwargs): async with aiohttp.ClientSession() as session: log.debug(f'Fetching {url}') async with session.get(url, headers=headers, ssl=ssl) as response: try: return await response.json() except Exception as e: log.error(f'Unable to complete interaction: {e}') return await response.text() Then I just await on that: results = await interactions.get(url) I am not sure why that is not the "right way". The session (at least for my needs) can be closed as soon as my request is done.

http://stackoverflow.com/a/51538001
downvote count: 0
has comment: http://stackoverflow.com/comment/90043649
accepted answer of: http://stackoverflow.com/q/51537874
type: Answer
answers question: http://stackoverflow.com/q/51537874
score: 3
upvote count: 3
has body: Use ListCreateAPIView. It provides get and post method handlers for a view. Refer: Django Rest Framework class QuestionView(generics.ListCreateAPIView) queryset = Question.objects.all() serializer_class = QuestionSerializer
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90043590
has comment: http://stackoverflow.com/comment/90043793

http://stackoverflow.com/a/51550031
downvote count: 0
score: 1
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51549949
answers question: http://stackoverflow.com/q/51549949
has body: l = [[1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1]] s = [[1,2,3,4], [5,6,7,8]] def insert(large, small, row, col): for i, r in enumerate(small): large[row + i][col:col + len(r)] = r insert(l, s, 1, 6) print(l) This outputs: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 2, 3, 4], [1, 1, 1, 1, 1, 1, 5, 6, 7, 8]]
type: AcceptedAnswer

http://stackoverflow.com/q/51592584
favorite count: 0
tagged with: asyncpg
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90153997
upvote count: 3
type: UnansweredQuestion
has body: I use an asyncpg Pool for my discord.py bot but as I said in the title, it randomly stops responding. Commands that use the pool don't work, but others do, and I'm sure I close all the connections after I use them. I tried searching on google but haven't found anything Here's how I create the pool: self.pg_pool:asyncpg.pool.Pool = await asyncpg.create_pool(DSN, max_inactive_connection_lifetime=3600.0) EDIT: I thought this information isn't enough and I decided to add something. I get no exceptions or errors. I thought maybe it's because of the pool's lifetime and changed it to 0(disables the mechanism) and that doesn't work
has title: Asyncpg pool randomly stops responding
has answer: http://stackoverflow.com/a/58584288
has answer: http://stackoverflow.com/a/52069650
type: Question
answer count: 2
tagged with: discord.py
downvote count: 0
has comment: http://stackoverflow.com/comment/90173452
score: 3
tagged with: python

http://stackoverflow.com/q/51611455
tagged with: python
has comment: http://stackoverflow.com/comment/90202086
linked to: http://stackoverflow.com/q/48884214
upvote count: 3
answer count: 1
has body: I have the following demonstration code where I create a simple scatter plot and save it as png, fully vectorized eps and partly rasterized eps. For a large number of points I expect the filesize of the vectorized eps to be much bigger than the png (at least at reasonable dpi), and this is indeed what I observe. When I rasterize the scatter plot, I would expect the filesize to get back down towards the size of the png, since I'm practically just "embedding" the png in an eps, right? However, the rasterized version completely bloats up by a factor of ~20: png: 48K, fully vectorized eps: 184K, rasterized eps: 3.8M (on Linux openSUSE, python 3.4.6, matplotlib 2.2.2) What's the reason for this? Is my understanding of what happens when one rasterizes the plot completely wrong? When I put the png into inkscape and export as eps I get a file (which is obviously rasterized) of only minutely larger size than the original png. Demonstration code: import matplotlib.pyplot as plt import numpy as np # Prepare some random data N = 10000 x = np.random.rand(N) y = np.random.rand(N) dpi = 150 # Create a figure and plot some points fig = plt.figure() ax = fig_mesh.add_subplot(111) scatter = ax.scatter(x, y, zorder=0.5) # Save it as png or unrasterized eps fig_mesh.savefig('mesh.png', dpi=dpi) # 184K fig_mesh.savefig('mesh.eps') # 48 K # Save it with rasterized points ax_mesh.set_rasterization_zorder(1) fig_mesh.savefig('mesh_rasterized.eps', dpi=dpi, rasterized=True) # 3.8M! Thanks in advance!
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90202683
has answer: http://stackoverflow.com/a/51619122
tagged with: eps
has comment: http://stackoverflow.com/comment/90193786
type: AnsweredQuestion
score: 3
downvote count: 0
linked to: http://stackoverflow.com/q/19638773
has title: Why does the filesize of a matplotlib plot saved as .eps with rasterization explode?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51619122
has comment: http://stackoverflow.com/comment/90202304

http://stackoverflow.com/comment/90004457
comment on: http://stackoverflow.com/q/51517685
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/30227466/combine-several-images-horizontally-with-python
score: 0

http://stackoverflow.com/q/51620956
tagged with: python
tagged with: pygame
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/51625757
accepted answer: http://stackoverflow.com/a/51625757
has title: Moving objects in a loop in pygame
upvote count: 1
answer count: 1
has body: As you can see on this Picture, there is my rectangle (red) that I am controlling and green ones that I am not controlling. I want those green rectangles to constantly move from left to right (Every second one is moving in the opposite direction). I tried to do it, but I only managed them to go to one side and then they stop. I don't know how to make them go back to the other side and then do that constantly. Here is the picture how it looks after my if statement ends. import pygame pygame.init() win = pygame.display.set_mode((1200, 600)) clock = pygame.time.Clock() BLACK = (0, 0, 0) WHITE = (255,255,255) RED = (255, 0, 0) GREEN = (13, 255, 0) player = pygame.Rect(40, 45, 30, 30) vel = 4 walls = [ pygame.Rect(0, 0, 1200, 20), pygame.Rect(0, 0, 20, 600), pygame.Rect(0, 580, 1200, 20), pygame.Rect(1180, 0, 20, 600), pygame.Rect(300, 0, 20, 530), pygame.Rect(20, 100, 230, 20), pygame.Rect(70, 200, 230, 20), pygame.Rect(20, 300, 230, 20), pygame.Rect(70, 400, 230, 20), pygame.Rect(600, 100, 20, 500), ] movingobjectsleft = [ pygame.Rect(320, 120, 30, 30), pygame.Rect(320, 240, 30, 30), pygame.Rect(320, 360, 30, 30), ] movingobjectsright = [ pygame.Rect(570, 180, 30, 30), pygame.Rect(570, 300, 30, 30), pygame.Rect(570, 420, 30, 30) ] run = True while run: # Handle the events. for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() # Update the player coordinates. if keys[pygame.K_LEFT] and player.x &gt; 0: player.x -= vel if keys[pygame.K_RIGHT] and player.x &lt; 1200 - player.width: player.x += vel if keys[pygame.K_UP] and player.y &gt; 0: player.y -= vel if keys[pygame.K_DOWN] and player.y &lt; 600 - player.height: player.y += vel # Game logic for walls and moving objects for wall in walls: # Check if the player rect collides with a wall rect. if player.colliderect(wall): print("Game over") for object in movingobjectsleft: if player.colliderect(object): print("Game over") if object.x &lt; 570: object.x += vel for object…
favorite count: 0
linked to: http://stackoverflow.com/q/30720665

http://stackoverflow.com/q/51584559
has body: When I create a random image in .pbm-format (code below) and output the result in a .pbm-file, the file appears to be corrupt (cannot be opened e.g. with GIMP). However, if I open the file with a text editor (e.g. Notepad) and copy the content over to a new text file, that was manually created, it works fine. I also tried outputting the image as .txt and manually changing it to .pbm, which did not work either without manually creating a new text file and copy&amp;pasting the content. I also noticed that the text file created by Python is bigger in size (about double) compared to the manually created one with the same content. Do you guys have any idea, why and how the .txt-file created in python differs from a manually created one with the same content? Thanks a lot! .pbm-file created with the following command in windows command line: python random_image 20 10 &gt; image.pbm Code used: import random import sys width = int(sys.argv[1]) #in pixel height = int(sys.argv[2]) #in pixel def print_image(width, height): image=[[" " for r in range(height)] for c in range(width)] print("P1 {} {}".format(width, height)) for r in range(height): for c in range(width): image[c][r]=random.getrandbits(1) print (image [c][r], end='') print() print_image(width, height)
has title: pbm-file created with Python only works when copy&pasted in new text-file
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51585245
tagged with: text-files
tagged with: command-line
score: 2
upvote count: 2
type: UnansweredQuestion
type: Question
tagged with: pbm

http://stackoverflow.com/a/76317143
has body: Because you set include_granted_scopes='true' so scopes will be append when you run again. Let's set include_granted_scopes='false'
answers question: http://stackoverflow.com/q/51499034
type: Answer
score: 0

http://stackoverflow.com/comment/90365061
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51627317
has text: @amanrawat Well, it works for me correctly, what version of python and pyqt4?
type: AnswerComment

http://stackoverflow.com/q/51574431
has body: i am trying to split data between two new columns based on string match in csv file. Input file looks like below. ID Service Type 10 Parts warranty 20 Service warranty 30 Parts warranty 10 Service warranty 30 Service warranty 20 Parts warranty If 'Service Type' column data matches Parts Warranty it should move to new columns 'Parts' and if 'Service Type' column data matches Service warranty then it should move to new 'Service' column and delete the original column 'Service Type'. ID Parts Service 10 Parts warranty Service warranty 20 Parts warranty Service warranty 30 Parts warranty Service warranty Any help is appreciated as i am new to Pandas and python and want to figure this out for a new code i am working on.
answer count: 2
has title: Splitting data from original column to two new columns based on string match in Python?
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51574753
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/51574514

http://stackoverflow.com/comment/90014067
comment on: http://stackoverflow.com/a/51522100
type: AnswerComment
score: 0
type: Comment
has text: Hi Thank You for your reply. Have updated the result statement as above. But still the result is same. Request your help to overcome this issue.

http://stackoverflow.com/comment/90082096
comment on: http://stackoverflow.com/a/51552035
type: AnswerComment
has text: Hi thank you so much I have read the pro gan paper already and finally understood what toRGB and fromRGB layers are now. Everything finally makes sense, so that's what they mean by fading in the layers. You have no idea how happy I am right now this was a major confusion and obstacles for me thanks for clearing this up!
score: 0
type: Comment

http://stackoverflow.com/q/51546613
has body: Why is it giving 1th instead of 1st? a=1 i=None for i in "abcdef": print("{}{} character is: {}".format(a,x,i)) if a==1: x="st" elif a==2: x="nd" elif a==3: x="rd" elif a&gt;=4: x="th" a+=1 Result: '1th character is: a' '2st character is: b' '3nd character is: c' '4rd character is: d' '5th character is: e' '6th character is: f'
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90061440
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51546668
has comment: http://stackoverflow.com/comment/90061036
has comment: http://stackoverflow.com/comment/90061100
accepted answer: http://stackoverflow.com/a/51546668
type: Question
has comment: http://stackoverflow.com/comment/90060995
has title: for loop associated query in python 3
score: 0
answer count: 1

http://stackoverflow.com/comment/90030479
has text: Right before you call ``sess.run(your_own_ops)``, you should initialize the variables using ``sess.run(init_op)`` where ``init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())``. This way, TF will actually assign initial values to all variables in the graph. The ``tf.random_normal_initializer`` only tells you're gonnal use normal distribution, it does not assign the values right away.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51530203

http://stackoverflow.com/comment/90428104
comment on: http://stackoverflow.com/a/51602441
type: AnswerComment
score: 0
type: Comment
has text: tbh, I am shocked by the fact that something may work with `s.values` but not with `s` and this is not considered a bug.

http://stackoverflow.com/comment/89955165
type: Comment
score: 0
has text: Yes, thank you. just before seeing your reply I made an edit about how I should really tell which input was invalid instead of sending a general error that is not indicative enough.
comment on: http://stackoverflow.com/a/51493231
type: AnswerComment

google-visualization
tags question: http://stackoverflow.com/q/51531115
type: Tag
tag name: google-visualization

http://stackoverflow.com/comment/90036597
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51533902
has text: The find_executable('mvn') is None even if 'mvn' is available with built-in command line.

http://stackoverflow.com/comment/90055983
comment on: http://stackoverflow.com/a/51544029
has text: Yeah, it's pretty cool. It works for union (`|`) and difference (`^`) too.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52616673
type: Answer
has body: In my project my goal is to establish two-way data exchange between Arduino and Raspberry Pi via serial interface. The Raspberry Pi sends the Arduino command to execute, Arduino sends the Raspberry Pi sensor readings (currently a random number). Currently, the project includes two scripts for Raspberry Pi, written on Python, and a program for Arduino. The first script for Raspberry Pi using the URWID library organizes the graphical interface and command input, the second script is used to communicate with a serial port. The sources are given below. The result of the operation is quite satisfactory, but maybe somewhere I'm doing something wrong? Is this solution of the problem correct? Arduino software: #define SERIAL_SPEED 19200 // the speed of the serial port #define READ_SENSOR_INTERVAL 1000UL // frequency of output to the serial port int IN1 = 7; int IN2 = 6; int IN3 = 5; int IN4 = 4; int ENA = 9; int ENB = 3; char command = 'S'; char prevCommand = 'A'; int velocity = (4 + 1) * 10 + 100; // the fill factor of the PWM unsigned long timer0 = 2000; unsigned long timer1 = 0; long randNumber; long myflag = 0; void setup() { Serial.begin(SERIAL_SPEED); pinMode (ENA, OUTPUT); pinMode (IN1, OUTPUT); pinMode (IN2, OUTPUT); pinMode (ENB, OUTPUT); pinMode (IN4, OUTPUT); pinMode (IN3, OUTPUT); } void loop() { static unsigned long prevSensorTime = 0; if (millis() - prevSensorTime &gt; READ_SENSOR_INTERVAL) { prevSensorTime = millis(); if (myflag == 1) { randNumber = random(300); Serial.print(command); Serial.println(randNumber); } } if (Serial.available() &gt; 0) { timer1 = millis(); prevCommand = command; command = Serial.read(); myflag = 1; if (command != prevCommand) { switch (command) { case 'W': // Вперёд analogWrite(ENA, 0); analogWrite(ENB, 0); delay(20); digitalWrite (IN2, LOW); digitalWrite (IN1, HIGH); digitalWrite (IN4, LOW); digitalWrite (IN3, HIGH); analogWrite(ENA, velocity); analogWrite(ENB, velocity); break; case 'A': analogWrite(ENA, 0); analogWrite(ENB, 0); …
score: 0
answers question: http://stackoverflow.com/q/51616637

text-indent
tag name: text-indent
type: Tag
tags question: http://stackoverflow.com/q/51576404

http://stackoverflow.com/a/51540963
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90075083
has comment: http://stackoverflow.com/comment/90058232
type: AcceptedAnswer
downvote count: 0
has body: You can do this easily using itertools.groupby lst = [ [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')], [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Justice'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')], [('Lord', 'Justice', 'Smith'), ('Lady', 'Smiles'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')], [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')], [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lady', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Another'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')] ] res = [[max(reversed(list(v)), key=len) for k,v in groupby(sl, lambda x: x[0])] for sl in lst] for l in res: print(l) Output [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')] [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')] [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')] [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')] [('Lord', 'Justice', 'Smith'), ('Lady', 'Justice', 'Smiles'), ('Lord', 'Other'), ('Lady', 'Diana', 'Spencer'), ('Lord', 'Dave', 'Castle')]
answers question: http://stackoverflow.com/q/51540399
has comment: http://stackoverflow.com/comment/90063461
type: Answer
accepted answer of: http://stackoverflow.com/q/51540399

http://stackoverflow.com/a/51965055
answers question: http://stackoverflow.com/q/51572796
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91006338
upvote count: 1
has comment: http://stackoverflow.com/comment/91060081
type: Answer
has comment: http://stackoverflow.com/comment/92089807
has body: Hi check if you added the relevant python paths to the PATH.

http://stackoverflow.com/comment/90165894
score: 0
type: AnswerComment
type: Comment
has text: @aL_eX No, you just need to get this implementation right. Debug both versions to see whether they're going wrong. I edited the answer to show the most obvious error and the smallest change to fix it, but I can't promise that's the only error.
comment on: http://stackoverflow.com/a/51599339

http://stackoverflow.com/comment/124085144
score: 0
type: QuestionComment
has text: For anyone trying our the attached python code and getting an error, it should be `lat_1` and `lat_2` instead of `lat1` and `lat2`
type: Comment
comment on: http://stackoverflow.com/q/51554602

http://stackoverflow.com/comment/90114410
comment on: http://stackoverflow.com/a/51574299
type: AnswerComment
score: 0
type: Comment
has text: OP mentions nothing about effectiveness. You can insert elements of type int and dict would be of type object as you describe. I don't see the problem here?

http://stackoverflow.com/q/51542001
tagged with: har
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90052689
tagged with: google-chrome-devtools
tagged with: selenium
has comment: http://stackoverflow.com/comment/90052468
type: Question
has title: Where do I run DevTools code?
tagged with: javascript
has body: I want to get a HAR file using chrome.devtools.network.getHAR(). Specifically, I am using Selenium within a MahiMahi replay shell, and I want to inject JS that will dump the HAR into a file. The standard JS injection (Selenium's executeScript method) does not work, because the page's JS scope does not include DevTools compatibility. With this in mind, I have a series of questions: Where and how can I use methods like chrome.devtools.network.getHAR()? I have yet to find where I can run this, as the console when I F12 doesn't have it in scope. Can I automate this process? Can I get to this using Selenium specifically, or are there any other browser automation techniques that would work better? (Though I would prefer to avoid PhantomJS because it's outdated) Are there any other easier ways to automate getting a HAR file from a site? Note: My code base is in Python Thank you!
has comment: http://stackoverflow.com/comment/90053362
score: 0

http://stackoverflow.com/q/51545345
tagged with: python
has comment: http://stackoverflow.com/comment/90058873
upvote count: 2
has comment: http://stackoverflow.com/comment/90059292
downvote count: 1
has comment: http://stackoverflow.com/comment/90058944
has comment: http://stackoverflow.com/comment/90059219
type: UnansweredQuestion
tagged with: pyautogui
has comment: http://stackoverflow.com/comment/90059086
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/90097127
favorite count: 0
tagged with: python-3.x
type: Question
has title: How to automated curved mouse movements in Python (with pyautogui or any other similarmodule)
has comment: http://stackoverflow.com/comment/90059186
has body: I'm trying to automate mouse movements in a way that would look somewhat human-like. The reason why I need to do this is because I'm currently working on promotional videos for a web-app and I want to show how it's used. I don't want to just record my own movements because what I mean by "somewhat" human-like is that I want it to feel kind of organic, but I still want it to be perfect. I've been using pyautogui and time for now and it works great. I can get the cursor to move at whatever speed I want. I can make it slow down with tweening functions. It looks almost human, but it's all in straight lines. I'd like to have the cursor move in curves. Is that possible? Either that means using pyautogui with another module or simply other modules completely, that'd be fine. Also, I've found only one question here about this subject and I'm not sure the poster had the same objective as I do. They were talking about a bezier curve. I'm not particularly familiar with those so ideally, if it's possible of course, I'd like a simpler solution.

http://stackoverflow.com/a/51500275
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/51500221
has body: numpy.squeeze might be the preferred method to do this. Call np.squeeze(a) for the array that you wish to flatten. np.squeeze should be much faster than a list comprehension such as [e[0] for e in a]
type: Answer
score: 2

http://stackoverflow.com/q/51555900
has comment: http://stackoverflow.com/comment/90081423
type: AnsweredQuestion
has body: Sorry, I know this has been asked before but my score is too low to comment unfortunately. I´m working on Mac &amp; getting this error when trying to install a package in conda: pip install git+https://github.com/protos-research/protos-edge.git Already updated setup.py, but didn't make a difference.. Any ideas how to fix this? Thank you!
tagged with: installation
accepted answer: http://stackoverflow.com/a/51557574
has comment: http://stackoverflow.com/comment/90086242
has title: Getting Command "python setup.py egg_info" failed with error code 1 when installing via pip
type: Question
answer count: 1
tagged with: conda
score: 0
has answer: http://stackoverflow.com/a/51557574
linked to: http://stackoverflow.com/q/44981793
tagged with: pip
tagged with: python
linked to: http://stackoverflow.com/q/38902174

http://stackoverflow.com/comment/90058167
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51545141
type: QuestionComment
has text: Terminology nitpick: there are no arrays in your code. `arr` is a list. So really you're asking "how do I convert a list to a list?"

http://stackoverflow.com/comment/90080518
score: 0
comment on: http://stackoverflow.com/q/51556737
type: QuestionComment
type: Comment
has text: Just to practice OOP concept.

http://stackoverflow.com/comment/90026108
has text: thanks for the feedback. I will be ingesting the data into elasticsearch, though not all at once. for example, I could ingest 3 CSV files today and 3 different files tomorrow and there could be duplicated across both sets, hence the need to desire to generate an _id per row before ingest time to prevent duplicates in the elastic index.
comment on: http://stackoverflow.com/q/51525995
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51563547
answer count: 1
tagged with: python
type: UnansweredQuestion
has title: Python netifaces gives two address
tagged with: network-programming
type: Question
has answer: http://stackoverflow.com/a/51564510
has body: I am trying to get the ip address and broadcast address of my machine and after a lot of research netifaces works fine but the problem is ip address prints properly but when i wanted the broadcast address it gives the docker broadcast address as well as the 'lo' broadcast address but i wanted only 'lo' broadcast address and i am not sure how to get only the broadcast address associated with 'lo'. Please help me with some ideas. Also i am not sure that i have mentioned that wanted only 'lo' broadcast address but it also gives me dockers broadcast address as well. Code: import netifaces interfaces=netifaces.interfaces() for i in interfaces: if i=='lo': continue iface= netifaces.ifaddresses(i).get(netifaces.AF_INET) if iface != None: for j in iface: bd=(j['broadcast']) print(bd) Output: 192.169.x.x('lo'-broadcast) 175.17.x.x ('docker'-broadcast)
score: 0

http://stackoverflow.com/q/51484356
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/89941684
tagged with: tkinter
type: UnansweredQuestion
upvote count: 1
has body: (I apologize for the naive question) I have a window that pops up that allows a user to select two months as a starting point and end point for data collection. The events that occur with the click of the 'OK' button are to return a list and dictionary of the months in between the selected range, and to notify the user of their selected range. However, I would like this window to close after clicking 'OK' as well. The events are under the callback function. I cannot make root.destroy reachable. All the code that is involved is here. My function callback is towards the bottom: from tkinter import * startDate = 'Dec 16' now = datetime.now() endDate = now.strftime('%b %y') start = datetime.strptime(startDate, '%b %y').date() end = datetime.strptime(endDate, '%b %y').date() cur_date = start range_months = [] while cur_date &lt; end: cur_date += relativedelta(months=1) range_months.append(cur_date) range_months = [month.strftime('%b %y') for month in range_months] dict_months = dict((month, pd.to_datetime(month, format='%b %y')) for month in range_months) root = Tk() #root.withdraw() root.title("Select your Month Range") # Setting up Grid mainframe = Frame(root) mainframe.pack(pady=50, padx=50) Label(mainframe, text="Select Start Month").grid(row=1, column=1) Label(mainframe, text="Select End Month").grid(row=1, column=6) # Creating two Tkinter variables to obtain user input from the drop down menus tkvar_start = StringVar(root) tkvar_end = StringVar(root) tkvar_start.set('Jan 17') # Setting a default option tkvar_end.set(endDate) start_popupMenu = OptionMenu(mainframe, tkvar_start, *dict_months) end_popupMenu = OptionMenu(mainframe, tkvar_end, *dict_months) start_popupMenu.grid(row=2, column=1) end_popupMenu.grid(row=2, column=6) def callback_range(): print('The range is from %s to %s' % (tkvar_start.get(), tkvar_end.get())) list_of_month_keys = list(dict_months.keys()) import itertools range_dict_months = dict(itertools.islice(dict_months.items(), list_of_month_keys.in…
score: 1
has comment: http://stackoverflow.com/comment/89937814
has title: Tkinter window will not close upon clicking a button
type: Question
has answer: http://stackoverflow.com/a/51498182
answer count: 2
has answer: http://stackoverflow.com/a/51498442
downvote count: 0
tagged with: button

http://stackoverflow.com/comment/136182198
type: Comment
comment on: http://stackoverflow.com/a/63834834
has text: Because it took me way too long to figure this out: make sure your `as_completed()` call is **inside** the executor context.. *facepalm*
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90212702
score: 0
type: Comment
type: QuestionComment
has text: What makes you think it would not work?
comment on: http://stackoverflow.com/q/51623790

http://stackoverflow.com/q/51535921
downvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51540282
favorite count: 0
has title: Match if a word exists but only if it's not matching other words within a textfile
tagged with: python
tagged with: regex
linked to: http://stackoverflow.com/q/2866637
possible better answer: http://stackoverflow.com/a/51536354
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/11026959
linked to: http://stackoverflow.com/q/2973436
type: Question
has comment: http://stackoverflow.com/comment/90047257
has body: I would like to know how to create a RegEx with Python for the following issue: I got a textfile with data in it, the regex should only match if: it has the right ID and does not include a specific value2 or value3 within the textfile (which can occur anywhere) Textfile: blabla ID blabla ... blabla value1 blabla ... blabla value2 blabla ... This (?&lt;!\n)(\n.*(ID)(?!\n.*(value2|value3).*) works, but only if value2 or value3 is on the line before or right after the line ID. So, how to look up any line before and after the line ID? The solution should fit a single line of code like my try above.
score: -2
has comment: http://stackoverflow.com/comment/90047008
accepted answer: http://stackoverflow.com/a/51540282
linked to: http://stackoverflow.com/q/30410633
has answer: http://stackoverflow.com/a/51536354

http://stackoverflow.com/comment/90235174
has text: I think `lambda` makes my `transform` slower. Already +1 ed to your answer. @jezrael
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51635223

http://stackoverflow.com/a/51562511
answers question: http://stackoverflow.com/q/51537507
has comment: http://stackoverflow.com/comment/90094509
has comment: http://stackoverflow.com/comment/90092618
has comment: http://stackoverflow.com/comment/90094724
type: Answer
has comment: http://stackoverflow.com/comment/90092943
has body: I think you're confusing network character encoding with storage encoding. In MySQL the life of string data is roughly this: disk_storage --decode--&gt; MySQL --encode--&gt; network --decode--&gt; database_driver When string data is read from the disk, MySQL decodes it using the character_set_database value. When a client connects over the network, the client specifies an encoding for the connection. For Python this is typically UTF-8. MySQL then encodes the data to the connection encoding. The Python Mysql driver then decodes the data it receives using the connection encoding it set. If anyone of those decodings or encodings use the wrong value, then bad data will be created. If character_set_database has been set incorrectly, then MySQL will be decoding the data incorrectly before encoding the bad data on the network connection. The solution should be as simple as changing character_set_database to the correct value without changing the actual data. This can be achieved with: ALTER DATABASE dbname CHARACTER SET koi8r COLLATE koi8r_general_ci; (DO NOT RUN ALTER TABLE tbl_name CONVERT.. - this will actually re-encode your data. As the old character_set value was wrong, your data will be decoded incorrectly before encoding to the new encoding) Change all Python settings back to their default (UTF-8 etc). Do not set DEFAULT_CHARSET or any other value. To ensure that MySQL driver connects correctly and uses UTF-8 for the network connection set use_unicode=True and charset="utf8" E.g. &gt;&gt;&gt; db = MySQLdb.connect(host="localhost", user='root', passwd='passwd', db='sandbox', use_unicode=True, charset="utf8")
has comment: http://stackoverflow.com/comment/90096318
upvote count: 1
has comment: http://stackoverflow.com/comment/90096141
has comment: http://stackoverflow.com/comment/90097932
score: 1
has comment: http://stackoverflow.com/comment/90093463
has comment: http://stackoverflow.com/comment/90093606
downvote count: 0

http://stackoverflow.com/comment/90008049
has text: One problem I see right away is my_api returns not a pointer, but a pointer to a list of pointers.
comment on: http://stackoverflow.com/q/51507196
score: 0
type: Comment
type: QuestionComment

win32com
tags question: http://stackoverflow.com/q/51589733
tags question: http://stackoverflow.com/q/51537016
tags question: http://stackoverflow.com/q/51562092
type: Tag
tags question: http://stackoverflow.com/q/51585970
tag name: win32com
tags question: http://stackoverflow.com/q/51544847
tags question: http://stackoverflow.com/q/51530305
tags question: http://stackoverflow.com/q/51634576
tags question: http://stackoverflow.com/q/51491782
tags question: http://stackoverflow.com/q/51502558

http://stackoverflow.com/comment/90215231
has text: I just saw that, thank you! I forgot the print() at the end
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/51625160
type: Comment

http://stackoverflow.com/q/51607038
upvote count: 2
answer count: 2
possible better answer: http://stackoverflow.com/a/51608520
tagged with: pyqt
has title: `QImage` constructor has unknown keyword `data`
tagged with: qimage
favorite count: 0
has answer: http://stackoverflow.com/a/51608230
accepted answer: http://stackoverflow.com/a/51608230
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: pyqt5
type: Question
tagged with: opencv
has body: Suppose I am taking an image from the webcam using opencv. _, img = self.cap.read() # numpy.ndarray (480, 640, 3) Then I create a QImage qimg using img: qimg = QImage( data=img, width=img.shape[1], height=img.shape[0], bytesPerLine=img.strides[0], format=QImage.Format_Indexed8) But it gives an error saying that: TypeError: 'data' is an unknown keyword argument But said in this documentation, the constructor should have an argument named data. I am using anaconda environment to run this project. opencv version = 3.1.4 pyqt version = 5.9.2 numpy version = 1.15.0
has answer: http://stackoverflow.com/a/51608520

http://stackoverflow.com/comment/90213252
type: Comment
comment on: http://stackoverflow.com/a/51623564
has text: yeah, when you open the terminal try `cd ... (path to the python file)` then from there run `python3 roboc.py`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90194188
comment on: http://stackoverflow.com/a/51605215
has text: Right okay so that is really helpful! My codes loss function and validation losses are currently zero:loss:" 0.0000e+00 - val_loss: 0.0000e+00". I assume this is incorrect. Could this be due to the fact that I have written my codes to measure the losses incorrectly? Or could this be another defect within the algorithm? Thank you for breaking this down for me! I didn't realise it was that straight forward.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51522500
tagged with: datetime
tagged with: python
has body: Plotly has the ability to make bar charts with spaces in them, similar to a Gantt chart. I want to use this capability to create a figure that looks like a Gantt chart, but has a "time x-axis" instead of a "day x-axis". For example, import plotly.graph_objs as go from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import datetime trace1 = go.Bar( y = ['Task 1', 'Task 1'], base = [1, 2.5], x = [0.5, 1], orientation = 'h' ) fig = go.Figure(data=[trace1]) iplot(fig) base positions the start of each bar and x is the length of each bar However, this only seems to work for decimal numbers. Ideally, I would like the x-axis to be a time axis and say "1:00, 2:00... 24:00" instead of 1, 1.5, etc. However, when I try this, the results are a little bizarre. trace0 = go.Bar( y = ['Task 1', 'Task 1'], base = [datetime.datetime(2018, 7, 23, 1, 0), datetime.datetime(2018, 7, 23, 2, 30)], x = [datetime.time(0, 30), datetime.time(1, 0)], orientation = 'h' ) fig = go.Figure(data=[trace0]) iplot(fig) It's not clear to me how plotly is handling the datetime and time objects, I would like there to be two bars that start at 1 am and 2:30 am respectively, with a length of 30 min and 1 hour respectively. How can I achieve this?
answer count: 0
downvote count: 0
tagged with: plotly
score: 1
type: Question
tagged with: visualization
upvote count: 1
has title: Python plotly "gantt" chart with times on x-axis, using datetime with plotly
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51508733
upvote count: 9
has comment: http://stackoverflow.com/comment/100661861
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/130443217
accepted answer of: http://stackoverflow.com/q/51508682
has body: This assumes indexes are sorted: IIUC, x=np.array([ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]) x[(x[:,0] &gt;= 5) &amp; (x[:,0] &lt;= 9) ] So you would have 100 and 200 instead of 5 and 9. For a more general solution, check Wen`s answer
type: Answer
has comment: http://stackoverflow.com/comment/89987441
answers question: http://stackoverflow.com/q/51508682
score: 9

http://stackoverflow.com/q/51552706
tagged with: docker
type: Question
has comment: http://stackoverflow.com/comment/90072450
has comment: http://stackoverflow.com/comment/90072659
has answer: http://stackoverflow.com/a/51563802
favorite count: 0
tagged with: security
has body: I am about to decide on programming language for the project. The requirements are that some of customers want to run application on isolated servers without external internet access. To do that I need to distribute application to them and cannot use SaaS approach running on, for example, my cloud (what I'd prefer to do...). The problem is that if I decide to use Python for developing this, I would need to provide customer with easy readable code which is not really what I'd like to do (of course, I know about all that "do you really need to protect your source code" kind of questions but it's out of scope for now). One of my colleagues told me about Docker. I can find dozen of answers about Docker container security. Problem is all that is about protecting (isolating) host from code running in container. What I need is to know if the Python source code in the Docker Image and running in Docker Container is secured from access - can user in some way (doesn't need to be easy) access that Python code? I know I can't protect everything, I know it is possible to decompile/crack everything. I just want to know the answer just to decide whether the way to access my code inside Docker is hard enough that I can take the risk.
tagged with: python
has comment: http://stackoverflow.com/comment/90073558
has answer: http://stackoverflow.com/a/51553497
upvote count: 16
answer count: 4
has answer: http://stackoverflow.com/a/56034690
possible better answer: http://stackoverflow.com/a/51553497
accepted answer: http://stackoverflow.com/a/51563802
score: 11
has comment: http://stackoverflow.com/comment/90073675
type: AnsweredQuestion
downvote count: 5
tagged with: source-code-protection
has answer: http://stackoverflow.com/a/69979887
has title: Is distributing python source code in Docker secure?

http://stackoverflow.com/a/51571128
answers question: http://stackoverflow.com/q/51571112
has comment: http://stackoverflow.com/comment/90108327
score: 0
has comment: http://stackoverflow.com/comment/90108324
type: AcceptedAnswer
has body: python is tab sensitive so after def the code needs to be with tab try this: import requests def inka(ntfid): url = "http://zzzz:80/xxx/yyy?WSDL" headers = yyy body = "xxx"" response = requests.post(url, data=body, headers=headers) return response.text print(inka(122727))
accepted answer of: http://stackoverflow.com/q/51571112
has comment: http://stackoverflow.com/comment/90108358
type: Answer

http://stackoverflow.com/comment/90167761
comment on: http://stackoverflow.com/a/51600488
score: 0
type: AnswerComment
has text: I misspoke about my target output. Any date format is fine for me, I just want to truncate the time. Thank you all for your help
type: Comment

http://stackoverflow.com/q/51627518
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/51627944
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90220518
score: -4
type: Question
has comment: http://stackoverflow.com/comment/90220258
has body: So let's say I have a few HTML files like header.html, body1.html, body2.html, somethingsomething.html, footer.html. One text file and a few images that are supposed to be glued inside those HTML. Before I start writing my own python script just wanted to ask if you guys know any program that does that or framework that could help me.
has comment: http://stackoverflow.com/comment/90220131
downvote count: 5
upvote count: 1
has comment: http://stackoverflow.com/comment/90220178
has comment: http://stackoverflow.com/comment/90220338
answer count: 1
accepted answer: http://stackoverflow.com/a/51627944
favorite count: 0
has title: Program to glue together html files, text and imgs
has comment: http://stackoverflow.com/comment/90219962

http://stackoverflow.com/comment/120030069
has text: The original sample data has the mean(-0.005542) and std (0.06089), but the original data points were ranging between (-0.1208 to 0.14069). But after generating the new data with the desired mean (-0.005542) and std (0.06089), newly generated data points were ranges between (-26.847, 27.9262). is there any way to restrict the new data points to deviate a maximum of 1 std from the original data range?
comment on: http://stackoverflow.com/a/51515765
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51532283
accepted answer: http://stackoverflow.com/a/51536988
type: Question
answer count: 2
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/90032450
score: 0
has body: I'm using Django rest framework, I have a contact us table.. in views, I use class based view i want to send email when user post data .. this's my function def post(self, request): return self.create(request) return send_email(request) def send_email(request): if request.method == 'POST': subject = request.POST.get('subject', '') message = request.POST.get('message', '') from_email = request.POST.get('email', '') send_mail(subject, message, from_email, ['haguwanax@l0real.net'], fail_silently=False) return Response (status=status.HTTP_200_OK) it saves the data but there's nothing being sent. this's my settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_PORT = 587 EMAIL_HOST_USER = '*****@gmail.com' EMAIL_HOST_PASSWORD = '*******' EMAIL_USE_TLS = True
has answer: http://stackoverflow.com/a/51536988
has title: Django restframe work send email from posted data
has comment: http://stackoverflow.com/comment/90033229
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51533460
has comment: http://stackoverflow.com/comment/90032761
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90032180
possible better answer: http://stackoverflow.com/a/51533460

http://stackoverflow.com/comment/90116127
has text: Thank you! Although, I didn't intend to get the average of each point in each frame. I wanted to make a list of the average location of each point across multiple frames.
comment on: http://stackoverflow.com/a/51558427
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51497937
has comment: http://stackoverflow.com/comment/89963789
has answer: http://stackoverflow.com/a/51497991
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/89963894
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89963744
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/51498160
has body: Let's assume that I get number as string or hex or int and I want to convert to integer. I'm looking for a more generic form. for example, if I write: int('0x10',16) then int('0x10') will throw exception. if I write: int('10') then int('10',16) will throw exception. Do I need to check type with instanceof ?
score: -1
type: Question
has title: Let's assume that I get number as string or hex or int and I want to convert to integer. I'm looking for a more generic form
answer count: 2
upvote count: 0
favorite count: 0

http://stackoverflow.com/q/51603888
tagged with: heroku
tagged with: anaconda
score: 1
has comment: http://stackoverflow.com/comment/90173687
downvote count: 0
has body: I am trying to deploy my first Django application to Heroku. I'm using anaconda for python, and following Deploying Python from Heroku, and the recommendation is to use django_heroku package. I cannot find this package and get the following message when using: conda install django_heroku. Does anyone know where this package is? Is this necessary, or is there another way? PackagesNotFoundError: The following packages are not available from current channels: - django_heroku Current channels: - https://repo.anaconda.com/pkgs/main/win-64 - https://repo.anaconda.com/pkgs/main/noarch - https://repo.anaconda.com/pkgs/free/win-64 - https://repo.anaconda.com/pkgs/free/noarch - https://repo.anaconda.com/pkgs/r/win-64 - https://repo.anaconda.com/pkgs/r/noarch - https://repo.anaconda.com/pkgs/pro/win-64 - https://repo.anaconda.com/pkgs/pro/noarch - https://repo.anaconda.com/pkgs/msys2/win-64 - https://repo.anaconda.com/pkgs/msys2/noarch - https://conda.anaconda.org/conda-forge/win-64 - https://conda.anaconda.org/conda-forge/noarch To search for alternate channels that may provide the conda package you're looking for, navigate to https://anaconda.org and use the search bar at the top of the page.
has title: How to deploy Django (via Anaconda) to Heroku with django_heroku
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
type: Question

http://stackoverflow.com/comment/90049518
comment on: http://stackoverflow.com/a/51540613
has text: @harvpan *I count the zero and non zeros values*
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51517700
type: Question
type: AnsweredQuestion
has title: Changing Language in Python SpeechRecognition
has answer: http://stackoverflow.com/a/61038064
tagged with: python-2.7
answer count: 2
possible better answer: http://stackoverflow.com/a/51517863
has answer: http://stackoverflow.com/a/51517863
downvote count: 0
tagged with: speech-recognition
favorite count: 0
has body: I am using SpeechRecognition in my Python application. However, it can only recognise English. I want it to recognise other languages too. I know it is possible somehow. Can anyone please help me with the syntax to change the language of speechrecognition in Python2.7 Please help! Thanks in advance. Here is my code so far : import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: try: audio = r.listen(source) text = r.recognize_google(audio) except: pass
tagged with: python
accepted answer: http://stackoverflow.com/a/61038064
score: 2
upvote count: 2
tagged with: google-speech-api

http://stackoverflow.com/comment/89955370
comment on: http://stackoverflow.com/a/51489605
score: 0
type: Comment
has text: It would really help if you posted your models and your templates haha. Im working on so little here hahaha. I can't really state whether your references to objects need to be different because idk what kind of fields they are.
type: AnswerComment

http://stackoverflow.com/q/51534312
has comment: http://stackoverflow.com/comment/90036295
has answer: http://stackoverflow.com/a/51534418
type: Question
upvote count: 6
favorite count: 0
has comment: http://stackoverflow.com/comment/90036718
has answer: http://stackoverflow.com/a/51534669
tagged with: regex
has comment: http://stackoverflow.com/comment/90036351
has comment: http://stackoverflow.com/comment/90037000
answer count: 4
possible better answer: http://stackoverflow.com/a/51534418
has title: Splitting a string based on a pattern in Python
downvote count: 0
score: 6
tagged with: python
has body: I have long strings such as "123 - Footwear, 5678 - Apparel, Accessories &amp; Luxury Goods, 9876 - Leisure Products" and "321 - Apparel &amp; Accessories, 4321 - Apparel &amp; Accessories &gt; Handbags, Wallets &amp; Cases, 187 - Apparel &amp; Accessories &gt; Shoes" I want to split them based on the pattern "a number, a space, a dash, a space, some string until the next number, a space, a dash, a space or end of string". Notice that the string may contain commas, ampersands, '>' and other special characters, so splitting on them will not work. I think there is a way in Python to split based on regular expressions but I have trouble forming that. I have a very introductory knowledge of regular expressions. I can form a regex for numbers, as well as for alphanumeric strings, but I don't know how to specify "take everything until the next number starts". Update: Expected output: first case: ["123 - Footwear", "5678 - Apparel, Accessories &amp; Luxury Goods", "9876 - Leisure Products"] second case: ["321 - Apparel &amp; Accessories", "4321 - Apparel &amp; Accessories &gt; Handbags, Wallets &amp; Cases", "187 - Apparel &amp; Accessories &gt; Shoes"]
has answer: http://stackoverflow.com/a/51534547
accepted answer: http://stackoverflow.com/a/51534547
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51534811

http://stackoverflow.com/comment/89973180
score: 0
has text: Danni, for your second problem, when you call `break` in `adding_report`, you are transported back to the main loop. Add another `break` under `adding_report(report)` on line 26.
comment on: http://stackoverflow.com/q/51502090
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51485570
tagged with: lldb
type: UnansweredQuestion
type: Question
has title: How to reinstall or fix Python interpreter for XCode lldb?
has answer: http://stackoverflow.com/a/51529521
has body: I got this message at XCode after deleting some system files. (lldb) script Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'run_python_interpreter' is not defined P.S. Had to reinstall XCode, but I've got same message at debugger after reinstalling IDE Terminal output $ lldb Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy.py", line 52, in &lt;module&gt; import weakref File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/weakref.py", line 14, in &lt;module&gt; from _weakref import ( ImportError: cannot import name _remove_dead_weakref
answer count: 1
has comment: http://stackoverflow.com/comment/90010543
score: 0
has comment: http://stackoverflow.com/comment/90036006
tagged with: xcode
tagged with: python
tagged with: macos

http://stackoverflow.com/comment/90028730
score: 1
has text: Try `df.dropna(how='all', inplace=True)`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51530311

http://stackoverflow.com/q/51553166
tagged with: amazon-web-services
score: 0
has title: AWS X-Ray Python: MissingEndTime error
accepted answer: http://stackoverflow.com/a/51649591
answer count: 1
has body: I want to trace calls to the Python AWS SDK (boto3) by using the X-Ray SDK. According to the X-Ray docs, I have to patch boto3. Then X-Ray will automatically create sub-segments, so I only have to surround the AWS SDK calls inside a segment. Here is my code: import boto3 from aws_xray_sdk.core import xray_recorder, patch_all patch_all() codecommit = boto3.client("codecommit") # begin a segment xray_recorder.begin_segment("Main") # create a CodeCommit repository named "myrepo1" codecommit.create_repository(repositoryName="myrepo1") # end a segment xray_recorder.end_segment("Main") First I start the X-Ray daemon, then I run the script. However, the daemon returns the following error: 2018-07-27T15:33:01+08:00 [Info] Successfully sent batch of 1 segments (0.146 seconds) 2018-07-27T15:33:01+08:00 [Error] Unprocessed segment: { ErrorCode: "MissingEndTime", Id: "74d23cdcc7b60c3f", Message: "Invalid segment. ErrorCode: MissingEndTime" } 2018-07-27T15:33:01+08:00 [Warn] Batch that contains unprocessed segments 2018-07-27T15:33:01+08:00 [Warn] {"aws": {"xray": {"sdk": "X-Ray for Python", "sdk_version": "1.1.2"}}, "end_time": "MainSegment", "id": "74d23cdcc7b60c3f", "in_progress": false, "name": "MainSegment", "service": {"runtime": "CPython", "runtime_version": "3.6.5"}, "start_time": 1532676780.5897238, "subsegments": [{"aws": {"operation": "CreateRepository", "region": "ap-southeast-1", "request_id": "4a82bf29-916f-11e8-a631-85af1e9bc33f"}, "end_time": 1532676781.4089937, "http": {"response": {"status": 200}}, "id": "8ec94650265cf358", "in_progress": false, "name": "codecommit", "namespace": "aws", "parent_id": "74d23cdcc7b60c3f", "start_time": 1532676780.617356, "subsegments": [{"end_time": 1532676781.0933495, "http": {"request": {"method": "POST", "url": "https://codecommit.ap-southeast-1.amazonaws.com/"}}, "id": "77c7d8a0f67f8e13", "in_progress": false, "name": "https://codecommit.ap-southeast-1.amazonaws.com/", "namespace": "remote", "parent_id": "8ec94650265cf358", "s…
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: aws-xray
has answer: http://stackoverflow.com/a/51649591

http://stackoverflow.com/comment/90198498
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51546255
has text: I got it to build with `include_dirs=['build/temp.linux-x86_64-2.7'])` what error do you have now?
score: 0

class-variables
tag name: class-variables
type: Tag
tags question: http://stackoverflow.com/q/51600523
tags question: http://stackoverflow.com/q/51517548

http://stackoverflow.com/comment/89938413
type: QuestionComment
has text: @m69's link just obviated most of the answer I was posting. Nice work! Once you have a "saturated" matrix (every row & col sums to 2), you get the other solutions by flipping '1' entries. I recommend using some dynamic programming to avoid duplicating effort on unsaturated matrices. You still need a filter to avoid the symmetries you want to exclude.
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51484410

http://stackoverflow.com/comment/90057855
score: 1
has text: apply that after your aggregation function, not to the grouped object, as indicated in the second comment.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51544775

http://stackoverflow.com/a/51560259
type: Answer
accepted answer of: http://stackoverflow.com/q/51559978
score: 8
has body: Above from params import serial insert: import sys [sys.path.append(i) for i in ['.', '..']] This will add your current working directory and its parent directory to the list of locations from which you can import. Handling imports when running script from a parent directory of proj If you want to be able to import params into cars/honda.py when running your script from directories that are parents of project, you can use the following: import sys import os from functools import reduce # allow imports when running script from within project dir [sys.path.append(i) for i in ['.', '..']] # allow imports when running script from project dir parent dirs l = [] script_path = os.path.split(sys.argv[0]) for i in range(len(script_path)): sys.path.append( reduce(os.path.join, script_path[:i+1]) )
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/90097094
has comment: http://stackoverflow.com/comment/119390510
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90119078
has comment: http://stackoverflow.com/comment/90452414
has comment: http://stackoverflow.com/comment/90089022
has comment: http://stackoverflow.com/comment/90234836
answers question: http://stackoverflow.com/q/51559978
has comment: http://stackoverflow.com/comment/90235617

http://stackoverflow.com/comment/90064711
comment on: http://stackoverflow.com/q/51498024
has text: Yes, but you can still use the original method to roll the file, then you gzip it. or go to the site-packages/logging/handlers.py, copy-paste the code of RotatingFileHandler.doRollover() into your class and add the gzipping functionality.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51527594
type: Question
has comment: http://stackoverflow.com/comment/90024185
has comment: http://stackoverflow.com/comment/90024671
downvote count: 0
linked to: http://stackoverflow.com/q/41113663
tagged with: pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/90024079
tagged with: python-3.x
has body: I would like to create a utility function that filters variables in my current environment and prints them (ie print all variables that have type pd.core.frame.DataFrame) and then put this function in my utils module. I used (Pandas Get a List Of All Data Frames loaded into memory): import pandas as pd def list_my_frames(): f = [var for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)] return f I would like to be able to pass my current environment to dir() so that I can use it outside of my utils module. How can I get a handle to my current environment in python?
type: UnansweredQuestion
tagged with: python
has title: list variables in memory using function in python
answer count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/52078645
downvote count: 0
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51544666
has body: This seems to be a bug in Keras. I had a similar issue with a model using dropout in the first layer. Removing the dropout functionality from the input layer fixed this issue for me. In your case, I suggest using a dense input layer specifying the input dimensions of your data first. Thus, adding the line model.add(Dense(numberOfNeurons, activation='yourActivationFunction', input_dim=inputDimension)) should do the trick.

http://stackoverflow.com/q/51526464
tagged with: canoe
has title: How to create a com object for a specific version of application using python comtypes.client?
tagged with: com
upvote count: 1
answer count: 1
has body: I am trying to automate canoe application. I am trying to create a com object. But I have 2 different Canoe versions 7.6 and 8.2. By default it opens 7.6 version of Canoe. How do I make sure it opens 8.2 Version by default? import comtypes.client CANOE_COM_APPLICATION = "CANoe.Application" app = comtypes.client.CreateObject(CANOE_COM_APPLICATION)
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51527917
type: Question

http://stackoverflow.com/a/51639259
downvote count: 0
has comment: http://stackoverflow.com/comment/90243049
answers question: http://stackoverflow.com/q/51639219
type: Answer
has body: You're missing colons after your if statements. if int(Select) == 1: and if int(Select) == 2:
has comment: http://stackoverflow.com/comment/90243267
score: 1
upvote count: 1

http://stackoverflow.com/q/51527353
has body: This is both mathematics, modeling and biology. Using flux balance analysis we are modeling systems. I have a reaction with steps in our CobraPY model that is in essence this: A + B --> C C + D --> E E + F --> G The problem is that D is a protein that is impossible to model the creation of. Are there any workarounds for groups and flux balance analysis that allow the brief introduction of a protein or other metabolite then remove it from the system? I assume it would create infinite mass or a loop of some kind.
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Modeling of Systems Using Flux Balance Analysis - Metabolites Can't Introduced to System (CobraPY)
score: 1
upvote count: 1
type: Question
tagged with: modeling
has answer: http://stackoverflow.com/a/67271437

http://stackoverflow.com/q/51546913
tagged with: python
tagged with: module
tagged with: installation
upvote count: 2
tagged with: package
tagged with: pip
has answer: http://stackoverflow.com/a/51547059
answer count: 1
score: 2
type: AnsweredQuestion
has body: I wanted to install a package for python, but it told me my pip was not up to date and I should update it. I tried to do so and this is the result. Can someone explain this to me and tell me how to fix the problem?
downvote count: 0
accepted answer: http://stackoverflow.com/a/51547059
favorite count: 0
has title: I have an issue updating pip for installing python packages
type: Question

http://stackoverflow.com/comment/92182389
type: AnswerComment
type: Comment
has text: @Jacopofar I think you can't because `Graph disconnected` is raised on `Model(...)`, so that you don't have a reference to the model for `plot_model`
comment on: http://stackoverflow.com/a/51523029
score: 21

http://stackoverflow.com/q/51615790
upvote count: 3
tagged with: set
accepted answer: http://stackoverflow.com/a/51615893
type: Question
has comment: http://stackoverflow.com/comment/90197734
linked to: http://stackoverflow.com/q/4169252
has title: How to remove instance of custom object from python set?
answer count: 1
downvote count: 0
has body: I'm playing around with some basic card/deck manipulations in python. Below you can see my Card class and Deck class. Assume that I know that some cards are dead and would like to remove them from the deck. import itertools SUIT_LIST = ("h", "s", "d", "c") NUMERAL_LIST = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A") class Card: def __init__(self, numeral, suit): self.numeral = numeral self.suit = suit self.card = self.numeral, self.suit def __repr__(self): return self.numeral + self.suit class Deck(set): def __init__(self): for numeral, suit in itertools.product(NUMERAL_LIST, SUIT_LIST): self.add(Card(numeral, suit)) deck = Deck() dead_card = Card('J','s') deck.remove(dead_card) Raises the following error: Traceback (most recent call last): File "&lt;ipython-input-93-06af62ea1273&gt;", line 23, in &lt;module&gt; deck.remove(dead_card) KeyError: Js What is the proper way of removing dead cards from my deck? And why the way I do it does not work?
favorite count: 0
tagged with: python-3.x
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/51615893
type: AnsweredQuestion

http://stackoverflow.com/comment/90102631
has text: I was not tracking the previous row, col at all and as a result, the backtracking was not working. I just made row, col variable local like you said and it's working fine.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51566120

http://stackoverflow.com/q/51554659
type: AnsweredQuestion
score: -1
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/1704823
has title: How to create a multidimensional matrix in numpy
has comment: http://stackoverflow.com/comment/90076266
accepted answer: http://stackoverflow.com/a/51554935
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51554935
downvote count: 2
has body: I'm trying to create a multidimensional matrix with numpy, to describe a RGB image. Something like this does not work: numpy.full(100, 100, [0,0,0]) This fails with TypeError: data type not understood. What I'm trying to get at is a pixel matrix with rgb values at every pixel. Edit: this gets me halfway there: n = numpy.empty((3,3,3)) n[:] = [0,0,0] However, this gives a float array for every point, while a uint8 array would suffice. How would I fix that?
tagged with: python

http://stackoverflow.com/q/51492868
has comment: http://stackoverflow.com/comment/89954363
has comment: http://stackoverflow.com/comment/89954402
has title: Find odd pair in string of integers using python
answer count: 2
has comment: http://stackoverflow.com/comment/89954950
has body: How do I write a function that takes in a string and returns the same string with every pair of odd numbers separated with a dash. Assume that all characters in the string are numeric. i.e. "456793" -> "4567-9-3"
score: 2
downvote count: 0
tagged with: string
accepted answer: http://stackoverflow.com/a/51493144
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/51492929
has answer: http://stackoverflow.com/a/51492929
has comment: http://stackoverflow.com/comment/89954345
type: Question
has answer: http://stackoverflow.com/a/51493144

http://stackoverflow.com/comment/89952750
type: QuestionComment
has text: if you cc2.putText any constant fixed test string like "hello world", does it work?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51490371

http://stackoverflow.com/comment/90195188
type: Comment
comment on: http://stackoverflow.com/q/51614675
has text: `CTRL`+`R` is available on Windows via amazing https://github.com/lzybkr/PSReadLine. PSReadLine is included in Windows 10 but can be installed on older versions of system. More info here: https://serverfault.com/a/762222/100080.
score: 0
type: QuestionComment

http://stackoverflow.com/q/51559204
score: 0
has body: I am having a python dataframe names recording_rules. The Df has 9 million records with 8 columns each. When i use the info command, it gives me the following output: recording_rules.memory_usage(index=True, deep=False).sum() Out[6]: 574725072 I am trying to pickle this onto my file system using the following command. recording_rules.to_pickle('/Users/recording_rules_filtered_sentence.pkl') The command runs for almost 2 hours and still does not complete or gives any error. I also tried writing this dataframe to CSV, it generated a 4.1 GB CSV file. recording_rules.to_csv('/Users/recording_rules_filtered_sentence.csv', sep = '|') This took 30-40 minutes to complete. Providing here a sample of dataframe: start_time end_time channel user_id \ 0 2018-04-14 04:07:54 2018-04-14 04:54:38 Yle TV2 6 1 2018-04-14 12:25:00 2018-04-14 13:25:00 TLC Finland 6 2 2018-04-15 00:55:00 2018-04-15 01:55:00 TLC Finland 6 3 2018-04-15 15:25:00 2018-04-15 15:55:00 MTV3 6 4 2018-04-15 19:30:00 2018-04-15 21:00:00 MTV3 6 5 2018-04-15 19:00:00 2018-04-15 20:00:00 Sub 6 6 2018-04-16 03:55:00 2018-04-16 04:45:00 TLC Finland 6 7 2018-04-16 10:00:00 2018-04-16 11:00:00 AVA 6 8 2018-04-16 11:55:00 2018-04-16 12:50:00 TLC Finland 6 9 2018-04-16 13:25:00 2018-04-16 14:20:00 TLC Finland 6 10 2018-04-16 22:00:00 2018-04-16 23:00:00 FOX 6 11 2018-04-17 11:55:00 2018-04-17 12:25:00 TLC Finland 6 12 2018-04-17 20:00:00 2018-04-17 21:00:00 Liv 6 13 2018-04-17 21:00:00 2018-04-17 22:00:00 Sub 6 14 2018-04-17 22:00:00 2018-04-17 22:30:00 Liv 6 15 2018-04-18 11:55:00 2018-04-18 12:55:00 TLC Finland 6 16 2018-04-18 20:00:00 2018-04-18 21:00:00 AVA 6 17 2018-04-18 22:00:00 2018-04-18 23:00:00 Liv 6 18 2018-04-18 22:00:00 2018-04-18 23:00:00 Sub 6 19 2018-04-18 22:30:00 2018-04-18 23:30:00 Sub 6 20 2018-04-19 22:00:00 2018-04-19 23:00:00 Nelonen 6 21 2018-04-20 00:05:00 2018-04-20 01:10:00 TLC Finland 6 22 2018-04-20 12:30:00 2018-04-20 13:25:00 TLC Finland 6 23 2018-04-20 19:00:00 2018-04-20 20:00:00 Frii 6 24…
has comment: http://stackoverflow.com/comment/90087553
has comment: http://stackoverflow.com/comment/90085374
has title: Unable to pickle a large Pandas Dataframe
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/90087447
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90087301
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90087047
type: Question

http://stackoverflow.com/a/51589382
has body: It can be done easily with ffill method in pandas fillna. To illustrate the working consider the following sample dataframe df = pd.DataFrame() df['Vals'] = [1, 2, 3, np.nan, np.nan, 6, 7, np.nan, 8] Vals 0 1.0 1 2.0 2 3.0 3 NaN 4 5.0 5 6.0 6 7.0 7 NaN 8 8.0 To fill the missing value do this df['Vals'].fillna(method='ffill', inplace=True) Vals 0 1.0 1 2.0 2 3.0 3 3.0 4 3.0 5 6.0 6 7.0 7 7.0 8 8.0
accepted answer of: http://stackoverflow.com/q/51589210
answers question: http://stackoverflow.com/q/51589210
score: 9
upvote count: 9
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/51624790
tagged with: replace
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51624802
tagged with: string
duplicate of: http://stackoverflow.com/q/7208861
favorite count: 0
score: 0
has body: I have tried to use .replace in python to replace an empty list in a string but it is not working. Could anyone please tell me how? x = ['check-[]|man', 'check-[]|king'] for y in x: if "[]" in y: y.replace("[]", "o") print(y) The results gave me this despite using .replace: check-[]|man check-[]|king
possible better answer: http://stackoverflow.com/a/51624801
has title: Regarding replace in string using .replace
has answer: http://stackoverflow.com/a/51624802
linked to: http://stackoverflow.com/q/7208861
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/9189172
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51624801
downvote count: 1

http://stackoverflow.com/q/51486213
tagged with: tensorflow
type: Question
tagged with: tensorflow-transform
score: 1
has body: I have a sparse tensor (the tensor was generated using tf.Transform on a categorical value) which I convert it into a dense representation using the following command bow_indecies = tf.sparse_tensor_to_dense(sparse_bow_indecies, default_value=0) which results in a matrix of size batch_size x max_seq_length. The array looks like this [[ 597 1157 60 0 0 0] [ 939 1212 169 10 0 0] [ 242 719 215 520 57 6]] I would like to reverse the zero padding from trailing to leading in order to look like this [[ 0 0 0 597 1157 60] [ 0 0 939 1212 169 10] [ 242 719 215 520 57 6]] Any idea on how to do this?
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51486759
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Reverse trailing into leading pad zeros in a sequence tensor in Tensorflow
downvote count: 0

http://stackoverflow.com/comment/90221518
type: Comment
type: QuestionComment
score: 2
has text: In order to override a method of e. g. A your class C must inherit A: class C(A). An redefinition is necessary, if you want a behavior different from the one of the base class.
comment on: http://stackoverflow.com/q/51628525

http://stackoverflow.com/comment/90139273
comment on: http://stackoverflow.com/q/51583539
score: 0
type: Comment
type: QuestionComment
has text: i have data frame "df"(50000,3). user_id product_id quantity 0 1 196 10 1 1 10258 9 2 1 10326 1 3 1 12427 10 4 1 13032 3

http://stackoverflow.com/q/51606524
downvote count: 0
score: 1
tagged with: matplotlib
type: Question
has answer: http://stackoverflow.com/a/51606803
accepted answer: http://stackoverflow.com/a/51606803
has body: I would like to create a (sub)plot with two rows and two columns where the plot in the lower row occupies both axes. Since I use the plot from within pandas datetime (I think) I was not able to use this solution. fig, axes = plt.subplots(nrows=2, ncols=2) df1.set_index('Date').plot(ax=axes[0,0]) df2.set_index('Date').plot(ax=axes[0,1]) df3.set_index('Date').plot(ax=axes ??? ) How do I need to assign the axes (if at all possible) in order to get something like this:
tagged with: subplot
has title: How to make an axes occupy multiple subplots when using pandas datetime plot?
answer count: 2
possible better answer: http://stackoverflow.com/a/51620370
tagged with: pandas
upvote count: 1
linked to: http://stackoverflow.com/q/2265319
has answer: http://stackoverflow.com/a/51620370
favorite count: 0
has comment: http://stackoverflow.com/comment/90178577
tagged with: datetime
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51576756
tagged with: google-maps
tagged with: google-colaboratory
has comment: http://stackoverflow.com/comment/94054601
has answer: http://stackoverflow.com/a/55329863
has title: Display / Render an HTML file inside Jupyter Notebook on Google Colab platform
favorite count: 0
tagged with: jupyter-notebook
score: 30
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/73739652
tagged with: python
answer count: 4
downvote count: 0
has body: I am using Google Colab to work create maps with Python 3.0 and I have done so using Basemaps. I am next trying to create similar maps using Google Maps. There are two python packages that I have located namely gmaps and gmplot. It seems as if gmaps requires a google API but gmplot does not hence I am using gmplot. With gmplot, I am able to create a file 'my_map.html' which if I download to my local desktop, I can open in a browser and see the map correctly. However I would like to see the map in the notebook output cell without downloading to the local machine. The following image is a screenshot of what I have tried ... there is no error, but no display either. is there some command like %matplotlib inline that i need execute to be able to display the contents of the file in the output cell? or is there a better solution
upvote count: 30
type: Question
has answer: http://stackoverflow.com/a/59202531
has answer: http://stackoverflow.com/a/56288204

http://stackoverflow.com/q/51607079
has comment: http://stackoverflow.com/comment/90180247
score: 0
has comment: http://stackoverflow.com/comment/90180470
tagged with: pandas
has title: Why dont show the right value in column with pandas in python?
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90179649
linked to: http://stackoverflow.com/q/11707586
tagged with: bigdata
tagged with: python
duplicate of: http://stackoverflow.com/q/11707586
answer count: 0
has body: I try out some data analytics with pandas and got a problem. Input: import pandas as pd path = "/PATH/TO/FILE/" rnames = ["user_id", "movie_id", "rating", "timestamp"] ratings = pd.read_csv(path + "ratings.csv", engine="python", sep=",", header=0, names=rnames) mnames = ["movie_id", "title", "genres"] movies = pd.read_csv(path + "movies.csv", engine="python", sep=",", header=0, names=mnames) print(ratings[:5]) print(movies[:5]) print(movies.dtypes) Output: user_id movie_id rating timestamp 0 1 31 2.5 1260759144 1 1 1029 3.0 1260759179 2 1 1061 3.0 1260759182 3 1 1129 2.0 1260759185 4 1 1172 4.0 1260759205 movie_id ... genres 0 1 ... Adventure|Animation|Children|Comedy|Fantasy 1 2 ... Adventure|Children|Fantasy 2 3 ... Comedy|Romance 3 4 ... Comedy|Drama|Romance 4 5 ... Comedy [5 rows x 3 columns] movie_id int64 title object genres object dtype: object Process finished with exit code 0 The movies.csv is from Movielens and looks like this: movieId,title,genres 1,Toy Story (1995),Adventure|Animation|Children|Comedy|Fantasy 2,Jumanji (1995),Adventure|Children|Fantasy 3,Grumpier Old Men (1995),Comedy|Romance 4,Waiting to Exhale (1995),Comedy|Drama|Romance 5,Father of the Bride Part II (1995),Comedy As you can see the title won`t show correctly (... instead of the title). Can someone help me, please? :)
type: Question

http://stackoverflow.com/comment/89971404
has text: You simply want to change the decimals to two places at this point? Have you looked at https://stackoverflow.com/questions/15263597/convert-floating-point-number-to-a-certain-precision-and-then-copy-to-string?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51501469

http://stackoverflow.com/comment/90014195
has text: [`np.reshape`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.reshape.html)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51522488

http://stackoverflow.com/q/51527331
tagged with: pandas
linked to: http://stackoverflow.com/q/37352616
favorite count: 0
has answer: http://stackoverflow.com/a/51527708
tagged with: python
type: AnsweredQuestion
has title: Pandas boxplot, different y axes in subplots
has body: First, to say. I'm aware of similar questions namely pandas-boxplot-groupby-different-ylim-in-each-subplot and different-ylim-for-shared-axes-in-pandas-boxplot but I am still not able to get the desired result with my dataset. I've got a dataset of wastewater samples where columns are different pollutants and rows with "codes" for three different groups: Dataset looks like this (but bigger) data = pd.DataFrame({'Group': pd.Series(['IN', 'IN', 'IN', 'OUT', 'OUT', 'OUT']), 'COD' : pd.Series([800, 900, 100, 400, 450, 500]), 'BOD' : pd.Series([40, 50, 60, 20, 25, 30])}) and my code for boxplot (in jupyter with matplotlib inline) fig, ax = plt.subplots(figsize=(10, 5)) data.boxplot(['COD','BOD'], 'Group', ax) and the output is like this It's obvious that the y-axis can't be the same for all the data, but I was not able to recreate the output in such way to change the axis for individual subplots even with help of the links above. I would really a appreciate any help on this.
tagged with: matplotlib
linked to: http://stackoverflow.com/q/40148830
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/51527708
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51533672
score: 4
has answer: http://stackoverflow.com/a/51533672

http://stackoverflow.com/q/51556820
has comment: http://stackoverflow.com/comment/90096275
tagged with: python
has comment: http://stackoverflow.com/comment/90084399
type: AnsweredQuestion
tagged with: tkinter
downvote count: 1
has answer: http://stackoverflow.com/a/51556905
type: Question
has answer: http://stackoverflow.com/a/51557029
has comment: http://stackoverflow.com/comment/90094916
possible better answer: http://stackoverflow.com/a/51557047
score: -1
has comment: http://stackoverflow.com/comment/90096330
has answer: http://stackoverflow.com/a/51557047
has body: I have to make function draw(file_name),that read file with numbers: 100 50 150 100 50 100 100 150 something like this.one line is one coordinate x,y And draw line in tkiner: 1st line=1st point to 2nd line=2nd point,2nd line=2nd point to 3 line=3point import tkinter canvas = tkinter.Canvas() canvas.pack() def draw(file): file=open(file,"r") line=file.readline() i=line.find(" ") x, y = int(line[:i]), int(line[i:]) while line != "": line = file.readline() i = line.find(" ") x2, y2 = int(line[:i]), int(line[i:]) canvas.create_rectangle(x, y, x2, y2) x,y=x2,y2 file.close() draw("file.txt") canvas.mainloop() this is my code but it doesn't work
accepted answer: http://stackoverflow.com/a/51557029
answer count: 3
tagged with: canvas
has title: Python function that reads the file and write lines in tkinter
upvote count: 0
favorite count: 0

http://stackoverflow.com/a/51533198
has body: openpyxl never evaluates formulae. The tokenizer is solely used for unpacking and reassigning shared formulae. Other libraries do exist for evaluating formulae but you are generally better off passing the file to an application such as MS Excel or OpenOffice or LibreOffice for evaluation as these contain optimisations for the calculation, including parallelisation.
has comment: http://stackoverflow.com/comment/90072889
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/90059454
answers question: http://stackoverflow.com/q/51528009
downvote count: 0

http://stackoverflow.com/a/51576901
answers question: http://stackoverflow.com/q/51576862
has comment: http://stackoverflow.com/comment/90119408
type: Answer
has body: Seems like you're not adding 3 different instances of your class to the list, but the same instance, and then when you modify it 3 times, you get "New Hapmshire" added to this same instance 3 times. Try to replace: for station in stations: station.connecting_stations.append("New Hampshire") with stations[0].connecting_stations.append("New Hampshire") and print your list again to see =)
has comment: http://stackoverflow.com/comment/90119280
score: 0

http://stackoverflow.com/q/51627355
favorite count: 0
has title: how to understand re.sub("", "-", "abxc") in python
has body: recently, I study python regex, i can't understand some expression # but i think it should be : a-b---c sub_1 = re.sub("x*", "-", "abxc") # result is : -a-b-c- # but i think it should be : a-b-x-c sub_2 = re.sub("", "-", "abxc") # result is : -a-b-x-c- # but i think it should be : ['a', ''] find_all_1 = re.findall("a*", "ab") # result is : ['a', '', ''] # but i think it should be : ['', '', ''] find_all_2 = re.findall("", "abc") # result is : ['', '', '', '']
tagged with: python
tagged with: regex
answer count: 0
has comment: http://stackoverflow.com/comment/90219362
upvote count: 3
type: UnansweredQuestion
downvote count: 3
linked to: http://stackoverflow.com/q/30160040
type: Question
duplicate of: http://stackoverflow.com/q/30160040
score: 0
has comment: http://stackoverflow.com/comment/90219174

http://stackoverflow.com/comment/90187619
type: Comment
has text: Thank you, that's really helpful. It seems strange that python would allow you to alter the original list even when using the [:] and copy() methods to 'try' to create separate objects. Is that a useful feature in some cases?
comment on: http://stackoverflow.com/a/51611383
score: 0
type: AnswerComment

http://stackoverflow.com/comment/89958668
type: Comment
has text: This will throw an error – DictWriter needs the argument fieldnames, such as: wr = csv.DictWriter(outputFile, fieldnames=['user', 'valid', 'firstname', 'password'], dialect='excel')
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/51494464

http://stackoverflow.com/q/51495132
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89958440
downvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/45395630
has comment: http://stackoverflow.com/comment/89958411
has answer: http://stackoverflow.com/a/51495624
type: Question
has comment: http://stackoverflow.com/comment/89959040
has body: How can I call a method which is in another class in another fie under same package, from my python file?
has comment: http://stackoverflow.com/comment/89958482
answer count: 1
favorite count: 0
score: 0
has title: How can I call a method which is in another class under another file in python?
upvote count: 2

http://stackoverflow.com/comment/90098996
type: Comment
type: QuestionComment
has text: Use [`pandas.date_range`](http://pandas.pydata.org/pandas-docs/stable/timeseries.html#time-series-date-functionality) to construct the lists.
comment on: http://stackoverflow.com/q/51566014
score: 0

http://stackoverflow.com/q/51572555
duplicate of: http://stackoverflow.com/q/2612802
type: Question
has comment: http://stackoverflow.com/comment/90111159
upvote count: 1
tagged with: python
downvote count: 1
has title: why does this happen to my 2d list in python
has comment: http://stackoverflow.com/comment/90111057
score: 0
has comment: http://stackoverflow.com/comment/90111262
has body: i want to make a code that takes in the x and y coordinates as inputs and a 2d list as an output to match the x and y coordinates. This is my code: def d2_coordinate(size,x,y): d2_plane = [] d2_row = [] for i in range(size * 2 + 1): d2_row.append(0) for i in range(size * 2 + 1): d2_plane.append(d2_row) d2_plane[size - y][size + x] = 1 return d2_plane size = int(input("")) x_coordinate = int(input("")) y_coordinate = int(input("")) print(d2_coordinate(size,x_coordinate,y_coordinate)) so lets say i put in numbers like size = 2, x = 0, y = 0, i expect the outcome of [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] instead, i get [0,0,1,0,0] [0,0,1,0,0] [0,0,1,0,0] [0,0,1,0,0] [0,0,1,0,0] i dont understand what i did wrong here. Please help me out!
linked to: http://stackoverflow.com/q/2612802
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90111183
favorite count: 0

http://stackoverflow.com/comment/90072526
type: AnswerComment
score: 0
has text: Not sure what's going on then, may have to see your code to be able to help any further. As far as I know, this is the way to do it.
type: Comment
comment on: http://stackoverflow.com/a/51518400

http://stackoverflow.com/q/51615027
accepted answer: http://stackoverflow.com/a/55212489
upvote count: 1
linked to: http://stackoverflow.com/q/50369959
tagged with: tensorflow
type: Question
type: AnsweredQuestion
answer count: 1
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/55212489
tagged with: tensorflow-datasets
tagged with: python
has title: "SystemError: error return without exception set" when using tf.data.Dataset.from_generator
favorite count: 0
tagged with: pycharm
has body: I am hitting a strange runtime error when using tf.data.Dataset.from_generator. import tensorflow as tf def gen(): while True: yield 0, 0 batch = ( tf.data.Dataset.from_generator( gen, output_types=(tf.int32, tf.int32)) .batch(8) .repeat() .make_one_shot_iterator() .get_next() ) sess = tf.InteractiveSession() sess.run(batch) would print messages like this Exception ignored in: &lt;generator object _yield_value at 0x000001FD9ED6A7D8&gt; Traceback (most recent call last): File "C:\Users\user209974\AppData\Local\Continuum\miniconda3\envs\tf\lib\site-packages\tensorflow\python\data\util\nest.py", line 100, in _yield_value yield value SystemError: error return without exception set The error is thrown at runtime when calling Session.run, apparently each time the generator is called. What's weird though is that the returned values seems to be correct despite this error being thrown. So what is causing this error and how to make it away? (For some reason, removing batching or returning a single value in gen makes the error go away). EDIT I realized that those errors show up when running on Debug mode under PyCharm. If I run the code in the python console, as a script, or in PyCharm but not in Debug mode, those messages are not printed.

http://stackoverflow.com/q/51578424
has answer: http://stackoverflow.com/a/51594025
tagged with: python
tagged with: selenium-webdriver
tagged with: xpath
has comment: http://stackoverflow.com/comment/90122147
tagged with: selenium
type: Question
score: 0
answer count: 2
has body: I'm using Selenium with Firefox (I've tried chrome but the success ratio on this one was significantly lower). I'm trying to locate an element (upload button) and the success ratio is nowhere near an acceptable percentage. Now I know that I could try to use just selenium to the input but it wont locate it as well no matter what I do. So I used AutoIt for the uploading part. frdriver.get('') time.sleep(11) try: # el = WebDriverWait(frdriver, 15).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/header/div[2]/div[2]/div/div/form/i[2]'))) el = frdriver.find_element_by_xpath('/html/body/div[1]/header/div[2]/div[2]/div/div/form/i[2]') try: el.click() print(el) #ActionChains(frdriver).move_to_element(el).click().perform() try: #element = WebDriverWait(frdriver, 15).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/header/div[2]/div[2]/div/div/form/div[2]/div[3]/div[1]/div/div/div[1]'))) element = frdriver.find_element_by_xpath('/html/body/div[1]/header/div[2]/div[2]/div/div/form/div[2]/div[3]/div[1]/div/div/div[1]') time.sleep(4) try: element.click() #ActionChains(frdriver).move_to_element(element).click().perform() autoit.run("/image.exe") r = 100 except: print('Firefox retries upload') r += 1 except: print('Firefox retries upload') r += 1 except: print('Firefox retries upload') r += 1 except: print('Firefox retries upload') r += 1 As you can see I've tried many ways, each one had almost the same success. I'm using a remote windows machine for the job and it really might be my idea, but when it isn't minimized it works a lot better. Also there is something else, for some reason there are times that even if it hasn't successfully clicked a button it bypasses the try/except and proceeds. Edit html of the page Upload Image Max 2MB per Image Loading...
tagged with: css-selectors
has title: How to locate the upload button related to the text Upload Image as per the HTML?
has comment: http://stackoverflow.com/comment/90124620
has answer: http://stackoverflow.com/a/51579500
type: UnansweredQuestion

http://stackoverflow.com/comment/90050804
has text: Thanks, it works! However, I could not really understand the difference between `UserDict ` and `Dict`, even with the Manual page link you provide. Wouldn't it be possible to do it with a normal `Dict`?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51541098

mayavi
tags question: http://stackoverflow.com/q/51542231
tags question: http://stackoverflow.com/q/51493785
type: Tag
tags question: http://stackoverflow.com/q/51627244
tag name: mayavi
tags question: http://stackoverflow.com/q/51517407

http://stackoverflow.com/a/58443754
has body: You can create your own alembic config, script directory, and environment context. Critically this should have an already-created connection passed to it, which you have the ability to roll back after you're completed the dry-run. engine = sa.create_engine(url) session = Session(bind=engine) try: alembic_config = AlembicConfig(config_args={...}) alembic_config.attributes.update({"connection": session.connection()}) script_directory = ScriptDirectory.from_config(alembic_config) env_context = EnvironmentContext( alembic_config, script_directory, fn=lambda rev, context: script_directory._upgrade_revs("head", rev), as_sql=False, ) env_context.configure(connection=session.connection()) env_context.run_migrations() finally: session.rollback() session.close()
answers question: http://stackoverflow.com/q/51556996
score: 0
has comment: http://stackoverflow.com/comment/105561082
type: Answer

http://stackoverflow.com/q/51482990
type: Question
downvote count: 0
has body: I have a python module arranged in a directory. Call it foo. Here is the file layout: caller.py foo/__init__.py foo/bar.py foo/test/bar_test.py That is, the module is called foo and the code in foo/__init__.py gets imported when the import foo statement in caller.py gets run. Within foo/__init__.py, I wish to access the contents of bar.py. This is done with import foo.bar. My problem arises when writing the code that runs in foo/test/bar_test.py. If this file was simply foo/bar_test.py, then it could also use import foo.bar to import the contents of foo.bar.py. Unfortunately, we have a coding standard that says that unit tests go in a subdirectory called tests. Given that coding standard, how do we import bar.py? This doesn't work: # foo/test/bar_test.py import foo.bar def test_return5(): assert bar.return5() == 5 It gives me: $ py.test ================================================== test session starts ================================================== platform linux -- Python 3.6.3, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 rootdir: /home/hadoop/xxx/foo, inifile: collected 0 items / 1 errors ======================================================== ERRORS ========================================================= ___________________________________________ ERROR collecting test/bar_test.py ___________________________________________ ImportError while importing test module '/home/hadoop/xxx/foo/test/bar_test.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: test/bar_test.py:3: in &lt;module&gt; import foo.bar E ModuleNotFoundError: No module named 'foo' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ================================================ 1 error in 0.10 seconds ================================================ This works, but it's gross: # foo/test/bar_test.py import os import sys sys.path.append( os.path.join(os.path.dirname(__file__), "../..")) impor…
has title: Within the py.test test directory for a python module, import a file for the module
answer count: 1
tagged with: python-module
has answer: http://stackoverflow.com/a/51483333
favorite count: 0
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/12172791
type: AnsweredQuestion
tagged with: pytest
score: 1
accepted answer: http://stackoverflow.com/a/51483333

http://stackoverflow.com/a/51639653
accepted answer of: http://stackoverflow.com/q/51638082
has comment: http://stackoverflow.com/comment/90243903
has comment: http://stackoverflow.com/comment/90244143
answers question: http://stackoverflow.com/q/51638082
has comment: http://stackoverflow.com/comment/90244839
type: Answer
has comment: http://stackoverflow.com/comment/90243879
has comment: http://stackoverflow.com/comment/90244812
downvote count: 0
has comment: http://stackoverflow.com/comment/90244891
has body: You do not need to manage the loop of the tkinter instance with update() the mainloop() will do this for you. Instead lets write this where the class inherits from Tk() and then make the time print function part of the class. We can also use after() to update the print. Lastly we should set time_start to a class attribute to be used in our time function. import time import tkinter as tk class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.geometry("500x500") self.resizable(False, False) self.time_start = time.time() self.main_frame = tk.Frame(self) self.main_frame.grid(row = 0, column = 0, sticky = "news") self.main_text_box = tk.Text(self.main_frame) self.main_text_box.grid(row = 0, column = 0, sticky = "news") self.main_text_box.tag_configure("bold", font = "Helvetica 50") self.main_text_box.insert("end", "Example text", "bold") self.main_text_box.configure(state = "disabled") self.time_check() def time_check(self): print("Program running, {} seconds since start".format(round(time.time() - self.time_start, 3))) self.after(100, self.time_check) if __name__ == "__main__": my_app = App() my_app.mainloop()
score: 3
has comment: http://stackoverflow.com/comment/90244744
upvote count: 3
has comment: http://stackoverflow.com/comment/90244188
type: AcceptedAnswer

http://stackoverflow.com/a/51528497
has comment: http://stackoverflow.com/comment/90047869
has comment: http://stackoverflow.com/comment/109538324
score: 4
type: AcceptedAnswer
downvote count: 1
has body: Redefine MSSSource.frame() to: def frame(self): monitor = {'top': 0, 'left': 0, 'width': 640, 'height': 480} im = numpy.array(self.sct.grab(monitor)) im = numpy.flip(im[:, :, :3], 2) # 1 im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) # 2 return True, im MSS returns raw pixels in the BGRA form (Blue, Green, Red, Alpha). So #1 will reshape from BGRA to BGR and #2 will convert BGR to RGB.
upvote count: 5
answers question: http://stackoverflow.com/q/51488275
type: Answer
accepted answer of: http://stackoverflow.com/q/51488275

http://stackoverflow.com/q/51639252
favorite count: 0
has comment: http://stackoverflow.com/comment/90242932
has answer: http://stackoverflow.com/a/51639285
upvote count: 1
tagged with: python
answer count: 1
has body: i was practicing with for loop and i am noob here :p case 1- Fruits = ['mango','banana','orange','grapes','apple'] for fruit in Fruits: print("Current fruit:",fruit) print("Good Bye") output for this code is Current fruit: mango Current fruit: banana Current fruit: orange Current fruit: grapes Current fruit: apple Good Bye case 2- students = ['Avinash','Arush','Akshay','Raghav','Aditya'] for student in students: print("Current student are:",students) print("meet you next time") output Current student are: ['Avinash', 'Arush', 'Akshay', 'Raghav', 'Aditya'] Current student are: ['Avinash', 'Arush', 'Akshay', 'Raghav', 'Aditya'] Current student are: ['Avinash', 'Arush', 'Akshay', 'Raghav', 'Aditya'] Current student are: ['Avinash', 'Arush', 'Akshay', 'Raghav', 'Aditya'] Current student are: ['Avinash', 'Arush', 'Akshay', 'Raghav', 'Aditya'] meet you next time
has title: python for loop 2 program with different output
has comment: http://stackoverflow.com/comment/90242979
has comment: http://stackoverflow.com/comment/90242907
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/51639285
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90242953
type: Question
score: 1

http://stackoverflow.com/comment/89986346
type: QuestionComment
has text: I forgot about len
comment on: http://stackoverflow.com/q/51508514
score: 0
type: Comment

http://stackoverflow.com/comment/90014864
has text: Edited the post. That's the output I am looking for @RoryDaulton
score: 0
comment on: http://stackoverflow.com/q/51522685
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90024333
type: QuestionComment
comment on: http://stackoverflow.com/q/51526059
has text: [(n, m) for i, m in enumerate(x) for j, m in enumerate(y) if i==j]
score: 0
type: Comment

http://stackoverflow.com/comment/90073644
score: 0
has text: Or just not set a seed at all? I can't see what its purpose is in this application.
comment on: http://stackoverflow.com/a/51553324
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51598342
score: 1
has body: You are returning l3 at the first iteration of your loop, that's why you only get a line in output. from ast import literal_eval #combine both files and return a list def combiner(infile1, infile2): with open(infile1) as f1, open(infile2) as f2: f1_lists = (literal_eval(line) for line in f1) f2_lists = (literal_eval(line) for line in f2) result = [] # Store the results in a list for l1, l2 in zip(f1_lists, f2_lists): l3 = l1 + l2 result.append(l3) return result # Return the list class Compass: def __init__(self, coordx, coordy, coordz, positivity): self.coordX = coordx self.coordY = coordy self.coordZ = coordz self.posit = positivity def main(): file1 = "file1.txt" file2 = "file2.txt" all_args = combiner(file1, file2) for args in all_args: c = Compass(*args) print(c.coordX + ' ' + c.coordY + ' ' + c.coordZ + ' ' + c.posit) if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/90167385
answers question: http://stackoverflow.com/q/51598154
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90072889
type: AnswerComment
score: 0
has text: I think PyCell is the Python one but I've never used it.
type: Comment
comment on: http://stackoverflow.com/a/51533198

import
type: Tag
tags question: http://stackoverflow.com/q/51565064
tags question: http://stackoverflow.com/q/51510407
tag name: import
tags question: http://stackoverflow.com/q/51590572
tags question: http://stackoverflow.com/q/51507896
tags question: http://stackoverflow.com/q/51558828
tags question: http://stackoverflow.com/q/51543276
tags question: http://stackoverflow.com/q/51535558
tags question: http://stackoverflow.com/q/51540658
tags question: http://stackoverflow.com/q/51549170
tags question: http://stackoverflow.com/q/51517759
tags question: http://stackoverflow.com/q/51639006

http://stackoverflow.com/a/51544438
score: 0
answers question: http://stackoverflow.com/q/51544194
has body: The file have to be in your current work directory. Then it is no problem to import it. There are two ways to achieve this. Just open your python shell from the same folder your .py file is stored. The work directory is always set to the place from where you started the python shell. Just change your working directory in code. Just call: import os os.chdir("/directory/with/your/pyfile/")
type: Answer

wsgi
type: Tag
tags question: http://stackoverflow.com/q/51542208
tags question: http://stackoverflow.com/q/51571899
tag name: wsgi
tags question: http://stackoverflow.com/q/51579814

http://stackoverflow.com/comment/98610686
score: 0
has text: sorry for late reply! Thanks that did it for me
type: Comment
comment on: http://stackoverflow.com/a/51632568
type: AnswerComment

http://stackoverflow.com/comment/90210670
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51616021
has text: 2^6=64... why not testing all the possibilities? unless one optimization takes already one hour...
score: 0

http://stackoverflow.com/q/51499231
has answer: http://stackoverflow.com/a/51501106
type: Question
answer count: 2
tagged with: neural-network
has title: How to expand CNN to recognize more objects?
score: 0
has comment: http://stackoverflow.com/comment/89971887
upvote count: 1
downvote count: 1
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/89966589
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/51502084
accepted answer: http://stackoverflow.com/a/51502084
possible better answer: http://stackoverflow.com/a/51501106
type: AnsweredQuestion
has body: I created a simple CNN to differentiate between 5 different categories of flowers. I want to expand the CNN to recognize more objects. For example, I want the CNN to recognize the image of a glass of beer, window, tree etc. Below is the code that I made to classify the flowers, it works pretty good. But how to expand it and make it recognise more and more objects. I don't want to use any pre-trained models. I want it to learn to classify more objects. Please help. from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Convolution2D, MaxPooling2D, Flatten, Dense classifier=Sequential() #1st Convolution Layer classifier.add(Convolution2D(32, 3, 3, input_shape=(64,64,3),activation="relu")) #Pooling classifier.add(MaxPooling2D(pool_size = (2, 2))) # Adding a second convolutional layer classifier.add(Convolution2D(32, 3, 3, activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2))) # Flattening classifier.add(Flatten()) classifier.add(Dense(output_dim = 128, activation = 'relu')) classifier.add(Dense(output_dim = 64, activation = 'relu')) classifier.add(Dense(output_dim = 5, activation = 'softmax')) classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) print(classifier.summary()) train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) training_set= train_datagen.flow_from_directory('flowers/train_set', target_size=(64,64), batch_size=32, class_mode='categorical') test_set= test_datagen.flow_from_directory('flowers/test_set', target_size=(64,64), batch_size=32, class_mode='categorical') classifier.fit_generator(training_set, samples_per_epoch = 3000, nb_epoch = 25, validation_data = test_set, nb_val_samples=1000)

http://stackoverflow.com/comment/90082519
score: 1
has text: @Zulan I also got that feeling. I figured, I'd at least document this here.
comment on: http://stackoverflow.com/a/51557136
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51589469
type: Answer
downvote count: 0
score: 1
has body: Sounds like a job for xlwings. You didn't post any test data, but modyfing below to suit your needs should be quite straight-forward. import xlwings as xw wb = xw.Book('your_excel_template.xlsx') wb.sheets['Sheet1'].range('A1').value = df[your_selected_rows] wb.save('new_file.xlsx') wb.close()
upvote count: 1
answers question: http://stackoverflow.com/q/51582786

http://stackoverflow.com/q/51497860
has comment: http://stackoverflow.com/comment/89964338
type: Question
has comment: http://stackoverflow.com/comment/89964398
has comment: http://stackoverflow.com/comment/89965393
has body: I have this TemplateView: class DamageEntry(TemplateView): template_name = "damage/damageadd.html" def get(self, request): general = General.objects.get(pk=1) form = DamageEntryForm() args = {'form': form, 'general': general, } return render(request, self.template_name, args) def post(self, request): general = General.objects.get(pk=1) form = DamageEntryForm(request.POST) form.non_field_errors() if form.is_valid(): post = form.save(commit=False) if self.request.user.is_authenticated(): post.user = request.user post.userip = get_client_ip(request) # το IP του χρήστη location = get_cocation(post.lat, post.lng) post.location = location post.formatted_address= location.formatted_address post.entry_date = datetime.datetime.now(tz=timezone.utc) post.save() form = DamageEntryForm() args = {'form': form, 'general': general } return http.HttpResponseRedirect('damage/add/') else: print('form is not valid') print(form.errors) # form = DamageEntryForm() args = {'form': form, 'general': general } return render(request, self.template_name, args) It works fine for create new record. I want to use thw same view for update, because of the extra code on Post section. I use this URL for update: # /damage/damage/list/1 url(r'damage/list/(?P<pk>[0-9]+)/$', views.DamageEntry.as_view(), name="damage-by-id"), Can I do this? How can I pass pk for create and update record?
score: 0
has comment: http://stackoverflow.com/comment/89965673
has title: Use the same TemplateView for create and update
has comment: http://stackoverflow.com/comment/89965000
has comment: http://stackoverflow.com/comment/89965028
answer count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/90174357
has text: getting this error at insert inside the LinkedList class - AttributeError: type object 'LinkedList' has no attribute 'head'... Shouldn't the __init___ cover this problem and give it this attribute?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51604233
score: 0

http://stackoverflow.com/a/51590472
has comment: http://stackoverflow.com/comment/106009091
accepted answer of: http://stackoverflow.com/q/51590357
score: 10
upvote count: 10
answers question: http://stackoverflow.com/q/51590357
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90146405
has body: How about: if string not in self.combobox1['values']: self.combobox1['values'] = (*self.combobox1['values'], string) Or alternatively: if string not in self.combobox1['values']: self.combobox1['values'] += (string,)

http://stackoverflow.com/q/51550279
tagged with: python
linked to: http://stackoverflow.com/q/7771011
tagged with: dictionary
has title: Python conditional get value from dict?
type: AnsweredQuestion
score: 4
has answer: http://stackoverflow.com/a/51550346
accepted answer: http://stackoverflow.com/a/51550307
has body: Given this json string, how can I pull out the value of id if code equals 4003? error_json = '''{ 'error': { 'meta': { 'code': 4003, 'message': 'Tracking already exists.', 'type': 'BadRequest' }, 'data': { 'tracking': { 'slug': 'fedex', 'tracking_number': '442783308929', 'id': '5b59ea69a9335baf0b5befcf', 'created_at': '2018-07-26T15:36:09+00:00' } } } }''' I can't assume that anything other than the error element exists at the beginning, so the meta and code elements may or may not be there. The data, tracking, and id may or may not be there either. The question is how to extract the value of id if the elements are all there. If any of the elements are missing, the value of id should be None
downvote count: 3
upvote count: 7
type: Question
possible better answer: http://stackoverflow.com/a/51550346
has comment: http://stackoverflow.com/comment/90068065
has comment: http://stackoverflow.com/comment/90068125
answer count: 3
has answer: http://stackoverflow.com/a/51550307
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51550388

cryptography
tag name: cryptography
tags question: http://stackoverflow.com/q/51613990
tags question: http://stackoverflow.com/q/51535968
type: Tag
tags question: http://stackoverflow.com/q/51539989

http://stackoverflow.com/comment/90121290
has text: Thank you.That worked. How can I better post questions so Idon't get downvotes? I'm new to the site. Once again thanks.
comment on: http://stackoverflow.com/a/51577942
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90217120
comment on: http://stackoverflow.com/q/51624496
score: 0
type: Comment
type: QuestionComment
has text: check before findcontour process, the image contains full object or not. With Morphological operations you may miss some part in the object.

http://stackoverflow.com/q/51526547
has answer: http://stackoverflow.com/a/51526653
accepted answer: http://stackoverflow.com/a/51526653
answer count: 1
has title: comparing values in a list to create a dictionary?
score: 0
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
type: Question
tagged with: list-comprehension
has body: I'm trying to append my list into a dictionary based on an if condition. I wrote a working function for this problem, but I want to write this program in list comprehension. The below function organizes all the tracks by month. The result will be a dictionary with the month as the key and the tracks as the value. [[j for j in lst2] for i in month if j[-2] == i] #I tried this list comprehension code for my function given below column names [Position, Track Name, Artist, Streams, Datetime.object, Region, month, day] Input : #my working code [['1','Starboy','The Weeknd','3135625',datetime.datetime(2017, 1, 1, 0, 0), 'global',1,1], ['2','Closer','The Chainsmokers','3015525',datetime.datetime(2017, 1, 1, 0, 0), 'global',1,1] ['3','Party Monster','The Weeknd','829599',datetime.datetime(2017, 2, 2, 0, 0), ' global',2,2]] def organized(lst2): month = [1,2] edict = {} for i in month: elst = [] for j in lst2: if j[-2] == i: elst.append(j) edict[i] = elst return edict output {1: [['1', 'Starboy', 'The Weeknd', '3135625', datetime.datetime(2017, 1, 1, 0, 0),'global', 1, 1], ['2', 'Closer', 'The Chainsmokers', '3015525', datetime.datetime(2017, 1, 1, 0, 0), 'global', 1, 1]] 2:‘3’, 'Party Monster', 'The Weeknd', '829599', datetime.datetime(2017, 2, 2, 0, 0), 'global', 2, 2}

http://stackoverflow.com/comment/90112441
has text: @Sedo The number of variables is the one thing that is absolutely not a problem in this code. Any modern compiler would convert the code to SSA *anyway*.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51573152

http://stackoverflow.com/comment/90128791
score: 0
type: Comment
has text: It is printing empty line
comment on: http://stackoverflow.com/a/51581669
type: AnswerComment

http://stackoverflow.com/a/51567866
accepted answer of: http://stackoverflow.com/q/51567847
has comment: http://stackoverflow.com/comment/90102341
answers question: http://stackoverflow.com/q/51567847
downvote count: 0
has comment: http://stackoverflow.com/comment/90107714
has comment: http://stackoverflow.com/comment/90102074
has comment: http://stackoverflow.com/comment/90102061
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90102093
has comment: http://stackoverflow.com/comment/90102068
has comment: http://stackoverflow.com/comment/90106516
has comment: http://stackoverflow.com/comment/90102194
has comment: http://stackoverflow.com/comment/90102076
has comment: http://stackoverflow.com/comment/90102086
has body: Firstly, you have to reorder your keywords to match the position of the elements in the source data: list1 = ["Language","Filename","Blank Lines","Comment Lines","Code Lines"] then it's as simple as: mydict = { a : b for a,b in zip( list1, mylist[0].strip().split(',')) } which gives us: {'Blank Lines': '188', 'Comment Lines': '5', 'Code Lines': '613', 'Language': 'Ruby', 'Filename': 'events_spec.rb'} and then you just have to iterate over the all elements in mylist.
type: Answer
has comment: http://stackoverflow.com/comment/90103925
score: 3
upvote count: 3

http://stackoverflow.com/q/51547551
tagged with: matplotlib
has title: Matplotlib connects end of data after animation refreshes
tagged with: python-2.7
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51548549
accepted answer: http://stackoverflow.com/a/51548549
tagged with: python
has answer: http://stackoverflow.com/a/71314298
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/90064848
possible better answer: http://stackoverflow.com/a/71314298
type: Question
linked to: http://stackoverflow.com/q/28016764
has body: I'm having an issue exactly like this post, but slightly more frustrating. I'm using matplotlib to read from a file that is being fed data from another application. For some reason, the ends of the data only connect after the animation (animation.FuncAnimation) has completed its first refresh. Here are some images: This is before the refresh: And this is after the refresh: Any ideas as to why this could be happening? Here is my code: import json import itertools import dateutil.parser import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style import scipy.signal as sig import numpy as np import pylab as plt sensors = {} data = [] lastLineReadNum = 0 class Sensor: def __init__(self, name, points = 0, lastReading = 0): self.points = points self.lastReading = lastReading self.name = name self.x = [] self.y = [] class ScanResult: def __init__(self, name, id, rssi, macs, time): self.name = name self.id = id self.rssi = rssi self.macs = macs # Is not an integer, but a datetime.datetime self.time = time def readJSONFile(filepath): with open(filepath, "r") as read_file: global lastLineReadNum # Load json results into an object that holds important info for line in itertools.islice(read_file, lastLineReadNum, None): temp = json.loads(line) # Only reads the most recent points... data.append(ScanResult(name = temp["dev_id"], id = temp["hardware_serial"], rssi = temp["payload_fields"]["rssis"], macs = temp["payload_fields"]["macs"], time = dateutil.parser.parse(temp["metadata"]["time"]))) lastLineReadNum += 1 return data style.use('fivethirtyeight') fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) def smooth(y, box_pts): box = np.ones(box_pts)/box_pts y_smooth = np.convolve(y, box, mode='same') return y_smooth def determineClosestSensor(): global sensors #sensors.append(Sensor(time = xs3, rssi = ys3)) def determineXAxisTime(scanresult): return ((scanresult.time.hour * 3600) + (scanresult.time.minute * 60) + (scanresult.time.second)) /…

http://stackoverflow.com/q/51539056
tagged with: http://stackoverflow.com/tag/json
tagged with: redisjson
score: 0
has title: Fastest and Best way to store and access complex JSON objects on Redis
answer count: 1
tagged with: hashset
tagged with: redis
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51540536
has body: I've been using ReJSON(json.set) for storing complex JSON on my redis server. For ex: {'2018-02-01' : {'cid_1':{ 'city_1: {'mid_1: {'user_data : ...},{'merchant_data': ...},{'item_data':...}...}...}...} Accessing one key at a time is blazingly fast. But accessing months of data, and adding it, takes quite an appreciable amount of time. Is there another better way to store/access these complex json structures: 1) So if I just need user_data, not having to retrieve all the other data and then filter out on the rest, like: dict_a = rj.jsonget(self.start_date, rejson.Path.rootPath()) dict_a = dict_a[self.cid][self.city][self.merchant]['User_data'] After testing on time, i see that 99% of it is spent getting and calculating the data. So based upon that, do you think my code needs more optimization ? def calculate_total(self,T): delta = self.delta() for i in range(delta): try: dict_a = rj.jsonget(self.start_date, rejson.Path.rootPath()) if T == 1: dict_a = dict_a[self.cid][self.city][self.merchant]['Merchant_data'] elif T == 2: dict_a = dict_a[self.cid][self.city][self.merchant]['User_data'] elif T == 3: dict_a = dict_a[self.cid][self.city][self.merchant]['Item_data'] break except KeyError: self.start_date = str((datetime.strptime(self.start_date, '%Y-%m-%d') + timedelta(days=i)).date()) else: return ('Error 404- No Data found for %s, in %s on %s'%(self.cid,self.city,start_date)) for i in range(delta): new_date = str((datetime.strptime(self.start_date, '%Y-%m-%d') + timedelta(days=i+1)).date()) try: dict_b = rj.jsonget(new_date, rejson.Path.rootPath()) if T == 1: dict_b = dict_b[self.cid][self.city][self.merchant]['Merchant_data'] elif T == 2: dict_b = dict_b[self.cid][self.city][self.merchant]['User_data'] elif T == 3: dict_b = dict_b[self.cid][self.city][self.merchant]['Item_data'] else: dict_b = rj.jsonget(new_date, rejson.Path.rootPath()) dict_a = merge_dict(dict_a,dict_b) except KeyError: pass return (dict_a) def merge_dict(dictA, dictB): new_dict = {} common_keys = …
type: Question

http://stackoverflow.com/a/51547752
type: Answer
score: 2
downvote count: 0
upvote count: 2
has body: Read the documentation: index returns the position of the first occurrence of the given element. Second, as soon as you find any qualifying index, you return from the function. You never stay long enough to find any more indices. Why do you "explode" the string into a list of individual characters? You can iterate a string just as easily. For your updated problem of getting the alphabetic difference, the solution is trivial: use the ord function, which returns the ordinal (ASCII code) of the character. dist = [] prev = str[0] for next in str[1:]: dist.append(abs(ord(prev) - ord(next))) prev = next return dist This returns the absolute distance between pairs of adjacent letters. Given str = "simpletext", we get the output [10, 4, 3, 4, 7, 15, 15, 19, 4]
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51547719
has comment: http://stackoverflow.com/comment/90063272
answers question: http://stackoverflow.com/q/51547719

http://stackoverflow.com/a/51565280
type: Answer
answers question: http://stackoverflow.com/q/51550950
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51550950
has body: Thanks to @Mr.T and @DavidG, I figure it out. Now the code becomes # Revised original code import matplotlib matplotlib.use("Qt5Agg") import matplotlib.pyplot as plt figA = plt.figure('aa') figB = plt.figure('bb') plt.close('aa') plt.plot([2,3],[1,1],color='green') plt.show() The culprit is the backend (default: "TkAgg"), and I set it as "Qt5Agg" now. I install the package pyqt5 by pip install pyqt5==5.10.1 Note that the pyqt5 version needs to be 5.10.1. The latest one (5.11.2) would cause another error. For details, please read the webpage.
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/90053397
type: AnswerComment
has text: @PaulHankin good point, thanks! Strictly speaking, that's only true if the Collatz conjecture is true :). We also need a special case for starting at 1, but it gives a nice speed-up
type: Comment
comment on: http://stackoverflow.com/a/51541308
score: 0

http://stackoverflow.com/q/51561265
upvote count: 1
tagged with: python
tagged with: restructuredtext
type: AnsweredQuestion
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/51566601
has title: How to find an intersphinx mapping for wx.CheckBoxState
downvote count: 0
tagged with: wxpython
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: for my project documentation I use the intersphinx mapping to the wxpython documentation. That works fine so far but I don't succeed to get a link to wx.CheckBoxState. I tried to find information about that here and in other forums, but didn't find anything. Here my code: def my_meth( self, value, aStr ): """ :param int value: This is my value :param str aStr: This is another value Description using - :py:class:`wx.CheckBoxState` - :py:class:`wx.CheckBoxState.enumeration` - :py:class:`wx.Validator` """ self.my_var = value self.my_str = aStr Running Sphinx produces As you see links to "int", "str", "wx.Validator" work fine, but both attempts to find a link to wx.CheckBoxState didn't succeed. There is still the hard coded way (a direct link to the page), but I would prefer the smart one (:py:class:...). Can anybody help? Thanks in advance Humbalan By the way: I work with sphinx 1.7.5, python 3.7 and wxpython 4.0.1
tagged with: python-sphinx
has answer: http://stackoverflow.com/a/51566601

http://stackoverflow.com/comment/90090018
type: Comment
type: QuestionComment
has text: Do you just want to find the first gap? Or can there be multiple gaps? Are the input letters guaranteed to be in order?
comment on: http://stackoverflow.com/q/51561242
score: 0

http://stackoverflow.com/comment/90161286
comment on: http://stackoverflow.com/q/51597173
has text: I was able to generate the possible pairs but you don't need `(5,6)` which is generated by my code: `lst = list(set(sorted(np.array(intervals1+intervals2).flatten())));` `output = [(lst[i], lst[i+1]) for i in range(len(lst)-1)];` `print (output)`. Perhaps one can play with these lines to reach the desired solution
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90184314
has text: Which pandas version have you installed? check [this](https://stackoverflow.com/q/36521691/7699859) @Smr
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51609726
type: Comment

http://stackoverflow.com/comment/90225823
type: Comment
has text: Thank you! What's happening is `np.bincount()` does not accept negative values, which is why you're getting the error. The `linearmodels` package should really have logic to make sure this fails gracefully with a more informative error message.
comment on: http://stackoverflow.com/q/51617740
score: 0
type: QuestionComment

http://stackoverflow.com/comment/89963707
score: 0
type: Comment
type: QuestionComment
has text: Try `$('#mydata-' + set_id).html(response);`
comment on: http://stackoverflow.com/q/51486736

http://stackoverflow.com/comment/90197128
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51615849
type: QuestionComment
has text: what about [this](https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.rolling.html)

http://stackoverflow.com/a/51628710
answers question: http://stackoverflow.com/q/51628437
has body: The image is read into from file into an numpy array. You can get the whole idea of axis and data manipulation by reading article Numpy sum axis intuition (especially the examples): The way to understand the “axis” of numpy sum is it collapses the specified axis. So when it collapses the axis 0 (row), it becomes just one row and column-wise sum. In 2-d arrays, it might be confusing, however when we talk about 3-d, 4-d, n-d, it’s the more straightforward way to define the axis.
score: 0
type: Answer

http://stackoverflow.com/q/51497129
has answer: http://stackoverflow.com/a/51497202
accepted answer: http://stackoverflow.com/a/51497202
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/22101836
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/132989499
has comment: http://stackoverflow.com/comment/89963520
upvote count: 3
linked to: http://stackoverflow.com/q/51320242
has comment: http://stackoverflow.com/comment/89964434
has body: I try to add a search box with this code's i got the error: Blank result def home(request): if 'search' in request.GET: term = request.GET['search'] name = Products.objects.filter(titulo__icontains=term) return render(request,'base.html', {'name':name}) in the model: from django.db import models class Products(models.Model): name = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.name on the views from django.shortcuts import render from .models import Products def home(request): if 'search' in request.GET: term = request.GET['search'] item = Products.objects.filter(name__icontains=term) return render(request,'base.html', {'item':item}) if i use this i got the error local variable 'name' referenced before assignment And if i add the variable name from django.shortcuts import render from .models import Products def home(request): item=none if 'search' in request.GET: term = request.GET['search'] item = Products.objects.filter(name__icontains=term) return render(request,'base.html', {'item':item}) edited the second view, with this i don't have results using {{Products.name}} on the html file i also try with: def home(request): query = request.GET.get('search',None) items = Products.objects.all() if query is not None: items = items.filter( Q(items__contains=query) ) context = {'items':items} return render(request, 'base.html', context)
type: Question
has comment: http://stackoverflow.com/comment/89962061
has title: django2 search form UnboundLocalError at /
score: 3

http://stackoverflow.com/comment/90140114
comment on: http://stackoverflow.com/a/51587328
type: Comment
has text: After I run `docker-compose up -d`, I can see many containers with `watch "docker ps"`. I notice the `mysql:5` image is restarting over and over without ever connecting and showing its `PORTS` values.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51619876
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/51618235
has comment: http://stackoverflow.com/comment/90209356
score: 2
has body: Even though you said you can do it, here's my solution: #!/usr/bin/env python3 """Context manager to limit execution time.""" import multiprocessing import time from typing import Callable def run_until(seconds: int, func: Callable, *args) -&gt; None: """Run a function until timeout in seconds reached.""" with multiprocessing.Pool(processes=2) as pool: result = pool.apply_async(func, [(*args)]) try: result.get(timeout=seconds) except multiprocessing.TimeoutError: pass if __name__ == "__main__": run_until(1, time.sleep, 20) # exits after 1 second
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51618235
has comment: http://stackoverflow.com/comment/90217130

http://stackoverflow.com/q/51614853
tagged with: importerror
linked to: http://stackoverflow.com/q/43872617
linked to: http://stackoverflow.com/q/47043407
tagged with: jupyter-notebook
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51615619
has body: I am using : Python 3.6.6 Mac OS High Sierra 10.13.6 and the following website to help me install pytrends https://pypi.org/project/pytrends/ I am following the instructions to download pytrends and installed the requirements to run pytrends "requests, lxml, & pandas". Here are the instructions Install pytrends pip install pytrends Connect pytrends to google from pytrends.request import TrendReq pytrends = TrendReq(hl=’en-US’, tz=360) but I get the following error File "<ipython-input-1-e31d93dc256d>", line 2 pytrends = TrendReq(hl=’en-US’, tz=360) ^ SyntaxError: invalid character in identifier so I researched for information to help me and found a code that worked better for me from https://github.com/GeneralMills/pytrends/blob/master/README.md from pytrends.request import TrendReqpytrends = TrendReq(hl='en-US', tz=360) but I received the following error ModuleNotFoundError Traceback (most recent call last) <ipython-input-9d1eaf7e6778a>in <module>() ----> 1 from pytrends.request import TrendReq 2 3 pytrends = TrendReq(hl='en-US', tz=360) ModuleNotFoundError: No module named 'pytrends' I ran the above mentioned code in Jupiter labs. My guess is that I have to import pytrends in Jupiter lab. I installed pytrends but through terminal not Jupyter labs. I will try !pip3 install pytrends in Jupiter lab. I got this idea by reading an issue someone has from https://github.com/GeneralMills/pytrends/issues/248 In addition to link above, I found two other relevant questions on stack overflow that might help me solve this issue : Jupyter Notebook: no module named pandas numpy & pandas 'ModuleNotFoundEror' in Jupyter notebook (Python 3)
accepted answer: http://stackoverflow.com/a/51615619
tagged with: traceback
type: Question
has title: error when connecting pytrends in Jupyter lab
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/90224689
has text: Yes, I tried that. Most of the suggestions were for using PDFMINER. But, I am not sure if pdfminer supports Python 3x. Thanks for your response.
comment on: http://stackoverflow.com/q/51629794
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51544275
type: Answer
has body: Following chepner's advice, I made some test. Signal generation is made by the following code: #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;cmath&gt; int main(int argc, char** argv) { std::ofstream of("signal.bin"); double omega = 10; double delt = 0.1; double phi = 1; int number_of_channel = 4; int nsize = 100000000; for (auto i=0; i&lt;nsize; ++i) { for (auto j=0; j&lt;number_of_channel; ++j) { double data = sin(omega*delt*i + phi*j); of.write(reinterpret_cast&lt;char*&gt;(&amp;data), sizeof(double)); } } of.close(); return 0; } The signal generated a 3GB binary file. Then I wrote python code reading data non-contiguously. import numpy as np import time import os def collect_signal_rev0(fp, channel_no, stride, dtype): byteSize = np.dtype(dtype).itemsize fp.seek(0,2) # go to the file end eof = fp.tell() # get the eof address fp.seek(0,0) # rewind fp.seek(0 + channel_no,0) # starting point per each channel signal = [] while True: start = fp.tell() sample = np.frombuffer(fp.read(byteSize), dtype=dtype) signal.append(sample[0]) if fp.tell() == eof or fp.tell() + stride &gt; eof: break; else: fp.seek(start + stride, 0) return signal def collect_signal_rev1(fp, channel_no, stride, dtype): byte_size = np.dtype(dtype).itemsize fp.seek(channel_no, 0) signal = [] sentinel = bytes() for sample in iter(lambda: fp.read(byte_size), sentinel): sample = np.frombuffer(sample, dtype=dtype) signal.append(sample[0]) # since the file pointer is pointing to the next item after reading # it should stride with subtracted by 1 byte_size fp.seek(stride-byte_size, 1) return signal def collect_signal_rev2(fp, num_channels, channel_no, stride, dtype): byte_size = np.dtype(dtype).itemsize offset = channel_no * byte_size signal = [] while True: sample = fp.read(byte_size * num_channels) if not sample: break sample = np.frombuffer(sample, dtype=dtype, count=1, offset=offset) signal.append(sample[0]) return signal def collect_signal_rev3(fp, channel_no, stride, dtype): return f…
answers question: http://stackoverflow.com/q/51531224
score: 0

http://stackoverflow.com/a/51617681
answers question: http://stackoverflow.com/q/51615993
has body: You can iterate over your entire computer automatically: import csv import os for root, dirs, files in os.walk(".\\your_directory_to_start\\"): # for each file and directory... for file in files: # for each file if file.endsswith(".csv"): # if file is csv print(os.path.join(root, file)) # show file name with location ruta_completa = os.path.join(root, file) # store in a variable the full path to file mi_archivo = open(ruta_completa) #open the file mi_csv = csv.reader(mi_archivo) # extract data from file mis_datos = list(mi_csv) # convert data from file into list mis_datos # show in screen all the data mis_datos[0] #extract the first row value mis_datos[0][0] #extract the first cell value in the first row # do whatever you want... even create a new xlsx file or csv file
score: 0
type: Answer

http://stackoverflow.com/comment/90181327
score: 0
type: QuestionComment
type: Comment
has text: @Sraw `Successfully installed cython-0.28.4` but the attribute error I mentioned above stays, still.
comment on: http://stackoverflow.com/q/51608035

http://stackoverflow.com/a/51496419
has body: This is a kind of "brute force" solution to the problem, simply tiling every value as many times as the largest number of repetitions and then picking the right elements: import tensorflow as tf # Repeats across the first dimension def tf_repeat(arr, repeats): arr = tf.expand_dims(arr, 1) max_repeats = tf.reduce_max(repeats) tile_repeats = tf.concat( [[1], [max_repeats], tf.ones([tf.rank(arr) - 2], dtype=tf.int32)], axis=0) arr_tiled = tf.tile(arr, tile_repeats) mask = tf.less(tf.range(max_repeats), tf.expand_dims(repeats, 1)) result = tf.boolean_mask(arr_tiled, mask) return result with tf.Graph().as_default(), tf.Session() as sess: print(sess.run(tf_repeat([0, 1, 2], [3, 4, 5]))) Output: [0 0 0 1 1 1 1 2 2 2 2 2]
upvote count: 4
answers question: http://stackoverflow.com/q/51490806
downvote count: 0
score: 4
type: Answer

http://stackoverflow.com/comment/90239899
comment on: http://stackoverflow.com/q/51637718
type: QuestionComment
score: 0
has text: Are you just using the default Python interpreter or some kind of IDE?
type: Comment

http://stackoverflow.com/q/51528295
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/50430086
answer count: 1
downvote count: 0
favorite count: 0
tagged with: unity-game-engine
has body: I install tensorflow 1.7.1 to use with Unity ML-Agent. I install tensorflow with the following command: pip3 install tensorflow==1.7.1 Installation goes fines but when I try to import tensorflow I got this error: C:\&gt;python Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tensorflow Traceback (most recent call last): File "C:\Python35_x64\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 14, in swig_import_helper return importlib.import_module(mname) File "C:\Python35_x64\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 666, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 577, in module_from_spec File "&lt;frozen importlib._bootstrap_external&gt;", line 903, in create_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed ImportError: DLL load failed: Une routine d\u2019initialisation d\u2019une bibliothèque de liens dynamiques (DLL) a échoué. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python35_x64\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Python35_x64\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 17, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "C:\Python35_x64\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 16, in swig_import_helper return importlib.import_module('…
has answer: http://stackoverflow.com/a/51621845
has title: Tensorflow 1.7.1 error with python 3.5
tagged with: python
accepted answer: http://stackoverflow.com/a/51621845
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90036460
has comment: http://stackoverflow.com/comment/90025470
has comment: http://stackoverflow.com/comment/90050084
tagged with: ml-agent
upvote count: 2

http://stackoverflow.com/a/51537133
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51537046
has body: Because QuerySets in Django are lazy: as long as you do not consume the result, the QuerySet is not evaluated: no querying is done, until you want to obtain non-QuerySet objects like lists, dictionaries, Model objects, etc. We can however not doe this for all ORM calls: for example Model.objects.get(..) has as type a Model object, we can not postpone that fetch (well of course we could wrap it in a function, and call it later, but then the "type" is a function, not a Model instance). The same with a .aggregate(..) since then the result is a dictionary, that maps the keys to the corresponding result of the aggregation. But your first query does not need to be evaluated. By writing a slicing, you only have added a LIMIT statement at the end of the query, but no need to evaluate it immediately: the type of this is still a QuerySet. If you would however call list(qs) on a QuerySet (qs), then this means the QuerySet has to be evaluated, and Django will make the query. The laziness of QuerySets also makes these chainings possible. Imagine that you write: Model.objects.filter(foo=42).filter(bar=1425) If the QuerySet of Model.objects.filter(foo=42) would be evaluated immediately, then this could result in a huge amount of Model instances, but by postponing this, we now filter on bar=1425 as well (we constructed a new QuerySet that takes both .filter(..)s into account). This can result in a query that can be evaluated more efficiently, and for example, can result in less data that has to be transferred from the database to the Django server.
has comment: http://stackoverflow.com/comment/90041977
has comment: http://stackoverflow.com/comment/90041929
score: 3
answers question: http://stackoverflow.com/q/51537046
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/89978636
comment on: http://stackoverflow.com/q/51498510
score: 0
type: Comment
type: QuestionComment
has text: @api55 I tried everything I did.

http://stackoverflow.com/q/51533663
type: Question
has title: RuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 'mat2'
tagged with: deep-learning
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: pytorch
has body: When I'm running a pytorch code,I got this error information below: class BatchRNN(nn.Module): def __init__(self, input_size, hidden_size, rnn_type=nn.LSTM, bidirectional=False, batch_norm=True, dropout = 0.1): super(BatchRNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.bidirectional = bidirectional self.batch_norm = SequenceWise(nn.BatchNorm1d(input_size)).cuda() if batch_norm else None self.rnn = rnn_type(input_size=input_size, hidden_size=hidden_size, bidirectional=bidirectional, dropout = dropout, bias=False,batch_first=True).cuda() def forward(self, x): if self.batch_norm is not None: x = self.batch_norm(x).cuda() x, _ = self.rnn(x) self.rnn.cuda().flatten_parameters() return x class CTC_RNN(nn.Module): def __init__(self, rnn_input_size, rnn_hidden_size, rnn_layers=1, rnn_type=nn.LSTM, bidirectional=True, batch_norm=True, num_class=1232, drop_out = 0.1): super(CTC_RNN, self).__init__() self.rnn_input_size = rnn_input_size self.rnn_hidden_size = rnn_hidden_size self.rnn_layers = rnn_layers self.rnn_type = rnn_type self.num_class = num_class self.num_directions = 2 if bidirectional else 1 #cnn self.conv1_cnn=nn.Conv2d(1,256,(2,rnn_input_size)).cuda() self.conv2_cnn=nn.Conv2d(1,256,(2,256)).cuda() self.fc_cnn=nn.Linear(256,rnn_hidden_size).cuda() self.softmax_cnn=torch.nn.Softmax().cuda() rnns = [] rnn = BatchRNN(input_size=rnn_input_size, hidden_size=rnn_hidden_size, rnn_type=rnn_type, bidirectional=bidirectional, batch_norm=False).cuda() rnns.append(('0', rnn)) for i in range(rnn_layers-1): rnn = BatchRNN(input_size=self.num_directions*rnn_hidden_size, hidden_size=rnn_hidden_size, rnn_type=rnn_type, bidirectional=bidirectional, dropout = drop_out, batch_norm = batch_norm).cuda() rnns.append(('%d' % (i+1), rnn)) self.rnns = nn.Sequential(OrderedDict(rnns)).cuda() if batch_norm : fc = nn.Sequential(nn.BatchNorm1d(self.num_directions*rnn_hidden_size).cuda(), nn.Linear(self.num_directions*rnn_hidden_size, rnn_hidden_size, bias=F…
score: 1
upvote count: 1

http://stackoverflow.com/comment/90156829
type: Comment
has text: I was using the function because I could use it elsewhere without having to type that full code block before it. But your method works too.
comment on: http://stackoverflow.com/a/51577592
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90180240
type: AnswerComment
has text: The comments explain the individual statements but not why your solution should be chosen over another.
type: Comment
comment on: http://stackoverflow.com/a/51607041
score: 0

http://stackoverflow.com/comment/90194902
comment on: http://stackoverflow.com/q/51614756
score: 0
has text: Did you check if your `countries` list contains 'NaN'?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90001160
comment on: http://stackoverflow.com/q/51515165
has text: Which columns are you talking about when swapping? Input features? `explained_variance_ratio_` will be equal to the number of output components from PCA, not input.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90157726
type: Comment
has text: Refer to this: https://pandas.pydata.org/pandas-docs/stable/merging.html
comment on: http://stackoverflow.com/a/51591313
type: AnswerComment
score: 0

http://stackoverflow.com/q/51517429
tagged with: tkinter
upvote count: 2
tagged with: time
has comment: http://stackoverflow.com/comment/90003257
downvote count: 1
linked to: http://stackoverflow.com/q/5478351
tagged with: chess
type: AnsweredQuestion
score: 1
has body: Apologies if the question is a little vague, I'll edit it if necessary. I'm creating a chess game in Python with Tkinter and want to add a chess timer. When a player moves a piece the move() function is called, causing the piece to be moved to the correct square and the turn switches (from black to white and vice-versa) - turn is a list ["W", "B"] that keeps track of whose turn it is. Called when a player selects a square to move to: def move(): #code here turn.reverse() To time each move, I want to measure the time between consecutive execution of the move() function (i.e. time between turn switches). To summarise: How can I measure the time between consecutive executions of the same function? Edit From the answers I can see that my question was misunderstood, I'm sorry for not clarifying: I'm not looking to measure the time it takes to execute a function (the move() function). I am looking to measure the time between consecutive executions of a function. The answers given here assume I only want to measure the execution time of the function from start to end. You cannot assume that the move() function executes again immediately after it has finished; it is called by clicking a button so there may be a delay (thinking about the move) before the move() function is called again. Any help would be greatly appreciated.
has comment: http://stackoverflow.com/comment/90003592
has answer: http://stackoverflow.com/a/51517684
type: Question
linked to: http://stackoverflow.com/q/14452145
answer count: 1
has comment: http://stackoverflow.com/comment/90003388
favorite count: 0
has comment: http://stackoverflow.com/comment/90003322
has comment: http://stackoverflow.com/comment/90003774
accepted answer: http://stackoverflow.com/a/51517684
tagged with: python
has title: Time between consecutive executions of a single function in Python
tagged with: python-3.x

http://stackoverflow.com/a/51517624
has body: Something like this might help you: l = [('Helipad', "Transport Services"), ...] for item in l: data['CATEGORY'][(data.CATEGORY == 'Miscellaneous') &amp; (data.SUB_CAT == item[0])] = item[1]
type: Answer
has comment: http://stackoverflow.com/comment/90031422
answers question: http://stackoverflow.com/q/51517517
score: 0

http://stackoverflow.com/comment/90217150
type: QuestionComment
has text: @Humbalan I will edit it now.
comment on: http://stackoverflow.com/q/51626124
score: 0
type: Comment

http://stackoverflow.com/q/51558265
has body: I have a grouped lists where I am trying to write a query filter. Grouped list: (listname: group) [({'swtype': 1}, ['201', '203', '205']), ({'swtype': 2}, ['207', '208'])] I am trying to access 201,203,205 from the first group one by one.How can I do that ? f_list = FP.objects.filter(pk__in= group[0]) I am trying the above code without success.Should I loop over ?
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51558361
type: AnsweredQuestion
tagged with: list
score: 1
has comment: http://stackoverflow.com/comment/90083425
type: Question
has comment: http://stackoverflow.com/comment/90083889
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51558361
favorite count: 0
has comment: http://stackoverflow.com/comment/90083467
has title: django filter from grouped list

http://stackoverflow.com/q/51490175
has answer: http://stackoverflow.com/a/51490574
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49527475
accepted answer: http://stackoverflow.com/a/51490574
score: 0
has title: Can't import datastore in Google App Engine
type: Question
tagged with: python-2.7
tagged with: google-cloud-platform
tagged with: google-cloud-datastore
answer count: 1
has body: I'm trying to import datastore to my code in GAE like this way, from google.cloud import datastore unfortunately I got some error message in stackdriver like this from grpc._cython import cygrpc as _cygrpc ImportError: dynamic module does not define init function (initcygrpc) or like this from google.cloud.datastore_v1 import types ImportError: cannot import name types anyone know the reason or something? thanks in advance ==== env: standard language: python runtime: python27
tagged with: google-app-engine

http://stackoverflow.com/q/51491771
has answer: http://stackoverflow.com/a/51549097
accepted answer: http://stackoverflow.com/a/51549097
upvote count: 1
tagged with: opencv
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51505921
score: 1
has comment: http://stackoverflow.com/comment/89960296
has answer: http://stackoverflow.com/a/51509321
has body: I want to use Python and OpenCV to achieve a non-Neural Network edge detection to calibrate some very small things, such as sperms under the microscope. Unfortunately, I found that the sperms' tails are very difficult to calibrate and they're really similar with the background. I used cv2.pyrMeanShiftFiltering() to achieve noise reduction and used cv2.findContours() to find contours. The result is like that: result: This is the original picture: Here is my code: import cv2 as cv import numpy as np import os path = "/home/rafael/Desktop/2.jpg" def detection(img): gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) #ret, dst = cv.threshold(gray, 200, 255, cv.THRESH_OTSU) ret, dst = cv.threshold(gray, 188, 255, cv.THRESH_BINARY_INV) return dst image = cv.imread(path) img = cv.pyrMeanShiftFiltering(src = image, sp = 5, sr = 40) dst = detection(img) src, contours, hierarchy = cv.findContours(dst, cv.RETR_TREE, cv.CHAIN_APPROX_NONE) cv.drawContours(image, contours, -1, (0, 0, 255), 2) cv.namedWindow('img', cv.WINDOW_NORMAL) cv.imshow('img', image) cv.waitKey(0) I tried Luke's method, and the code is here: import cv2 as cv import numpy as np import os path = "/home/rafael/Desktop/2.jpg" def enhance(img): img = cv.resize(img, (0, 0), fx = 0.3, fy = 0.3) blur = cv.GaussianBlur(img, (23, 23), 0) img = cv.add(img[:, :, 1], (img[:, :, 1] - blur[:, :, 1])) return img def detection(img): ret, dst = cv.threshold(img, 190, 255, cv.THRESH_BINARY_INV) return dst image = cv.imread(path) img = enhance(image) dst = detection(img) src, contours, hierarchy = cv.findContours(dst, cv.RETR_TREE, cv.CHAIN_APPROX_NONE) cv.drawContours(img, contours, -1, (0, 0, 255), 2) cv.namedWindow('img', cv.WINDOW_NORMAL) cv.imshow('img', img) cv.waitKey(0) This is the result: The latest picture Although I used a very big threshold(190), even appeared plenty of noises，the code still couldn't find the tails. How can I solve the problem? So thanks a lot if anyone could teach me how to improve this simple edge detectio…
type: Question
has title: How to use Python and OpenCV to achieve a well edge detection to calibrate some very small things
downvote count: 0
has answer: http://stackoverflow.com/a/51505921
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/89991962
has comment: http://stackoverflow.com/comment/89960612
has comment: http://stackoverflow.com/comment/89956954
favorite count: 0
tagged with: edge-detection
has comment: http://stackoverflow.com/comment/89957418

http://stackoverflow.com/comment/90024290
has text: Are you asking how to capture all the output into a string *and* also have it printed in real-time?
comment on: http://stackoverflow.com/q/51527750
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/51560984
has comment: http://stackoverflow.com/comment/90089565
linked to: http://stackoverflow.com/q/2761645
answer count: 0
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/90089665
tagged with: python-imaging-library
downvote count: 0
has title: Numpy array from PIL image empty without exception
has comment: http://stackoverflow.com/comment/90088986
has body: I'm reading a bunch of RGB images, one at a time, with different size using the PIL library and then convert them to numpy array. I use the following code and with 99% of the images I use, it works well. from PIL import Image import numpy as np in_image = r'path\to\img_rgb.tif' try: in_img = Image.open(in_image) in_array = np.array(in_img) print(in_array.shape) print(in_array) except Exception as e: print(e) But some images are read by PIL, passed to numpy and the result is not an array and the shape is empty. There are no errors or exceptions raised. I've opened an issue on numpy Github but it seems that the problem comes from PIL. Here's the link to it. There is also two test files attached to the issue.
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/90089863
has comment: http://stackoverflow.com/comment/90089984
favorite count: 0
tagged with: python

http://stackoverflow.com/a/75872013
downvote count: 0
has body: This can be due to Whoosh's default use of mmap'ed segment reading. If the segment is too big for available memory, Whoosh throws a MemoryError when creating the BytesIO for the buffer. Fortunately, Whoosh includes a way to disable mmap. Quick Fix The simple solution is to replace the storage used by whoosh with one that doesn't use mmap: from whoosh.filedb.filestore import FileStorage from whoosh.index import EmptyIndexError storage = FileStorage(ix_folder, supports_mmap=False) # schema as per the schema you posted in the question. try: index = storage.open_index(schema) except EmptyIndexError: index = storage.create_index(schema) Better Fix Using mmap is faster when you can. You might want to look at the size of your index on disk and your available memory and decide on a ratio below which to disable mmap. It would be nice if Whoosh did this itself or retried MemoryErrors without mmap, but alas with v2 we have to do this ourselves. Haystack For Haystack users like me, I do this step in a custom backend.setup() method that inherits from haystack.backends.whoosh_backend.WhooshSearchBackend
answers question: http://stackoverflow.com/q/51604125
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/89983243
type: AnswerComment
has text: Consider adding some more content to your answer to explain why your solution works. This way, it will help future visitors to the site!
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51500993

http://stackoverflow.com/comment/90123884
has text: What happens if you put `plt.ioff()` in the beginning of the code? In general the more we know about where and how you run the code, which versions are is use etc the higher the probability for a solution that works for you.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51559696

http://stackoverflow.com/a/51579210
upvote count: 2
has body: Here's one way using itertools, given input list L: from itertools import chain, product, repeat col, value = zip(*(list(i) for item in L for i in product(item[1], item[2]))) cat = list(chain.from_iterable(repeat(i, len(j) * len(k)) for i, j, k in L)) df = pd.DataFrame({'Cat': cat, 'Column': col, 'Value': value}) df = df.sort_values(['Cat', 'Column', 'Value']).reset_index(drop=True) print(df) Cat Column Value 0 R1 a 20.0 1 R1 a 40.0 2 R1 a 50.0 3 R1 a 60.0 4 R1 a 750.0 5 R1 b 20.0 ... 39 R3 x 10.0 40 R3 x 12.5 41 R3 x 45.0
answers question: http://stackoverflow.com/q/51579138
type: Answer
score: 2
downvote count: 0

byte
tags question: http://stackoverflow.com/q/51608846
tag name: byte
tags question: http://stackoverflow.com/q/51541670
tags question: http://stackoverflow.com/q/51565436
type: Tag

http://stackoverflow.com/comment/90165006
type: Comment
comment on: http://stackoverflow.com/a/51599145
has text: Thank you very much luca, you were absolutely right.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51689753
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51636195
has body: Just create some middleware so you can process all requests &amp; ensure users are logged in. Docs are here; https://docs.djangoproject.com/en/2.0/topics/http/middleware/#writing-your-own-middleware You'd do something like; def process_request(self, request): if not request.user.is_authenticated(): return HttpResponseRedirect('login')

http://stackoverflow.com/a/51596720
has comment: http://stackoverflow.com/comment/90159358
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: &gt;&gt;&gt; val '[12 13 14 16 17 18]' &gt;&gt;&gt; val.strip("[]").split(" ") ['12', '13', '14', '16', '17', '18']
answers question: http://stackoverflow.com/q/51596522

http://stackoverflow.com/a/51525585
score: 0
type: Answer
has body: one way can be: emp=[] for i in range(len(df)): emp.append([x for x in all_IDs if x not in df["IDs"][i]]) df["missing"]=emp This will give you a list of all the id's that are missing in the dataframe output will be like IDs missing 0 [B, C, F] [A, D, E] 1 [A, B] [C, D, E, F]
answers question: http://stackoverflow.com/q/51525501

http://stackoverflow.com/comment/90178689
has text: How do you know it doesn't work?
comment on: http://stackoverflow.com/q/51606185
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/51546109
downvote count: 0
has body: Pass your input dataframe in the process function and it will return back the output dataframe as intended by the author. The quantile function returns both the values present under the range and plugs back to the original dataframe. And then one can run the comparator on the top. import pandas as pd import numpy as np def quantile(x): x['first']= np.percentile(x['height'], 25) x['third']= np.percentile(x['height'], 75) return x def process(input_df): grouped_df = input_df.groupby(['ID2']).apply(quantile) grouped_df.loc[(grouped_df.height &gt;= grouped_df.first) &amp; (grouped_df.height &lt;= grouped_df.third), 'result'] = 'Medium' grouped_df.loc[(grouped_df.height &lt; grouped_df.first) , 'result'] = 'Short' grouped_df.loc[ (grouped_df.height &gt; grouped_df.third),'result'] = 'Tall' return grouped_df main_df = pd.read_csv('sample.csv') print process(main_df)
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51506820
answers question: http://stackoverflow.com/q/51506820
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/90015404
type: QuestionComment
type: Comment
has text: That's exactly what I am looking for "looking at groups as defined by having their first three elements common, and then finding the maximum of each such group" @IzaakvanDongen
comment on: http://stackoverflow.com/q/51522685
score: 0

http://stackoverflow.com/comment/90159913
has text: `s = set(list_of_skip_files); [file for file in files if file not in s]`
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51596971
type: Comment

http://stackoverflow.com/q/51498308
type: Question
has answer: http://stackoverflow.com/a/51498406
linked to: http://stackoverflow.com/q/51029761
answer count: 1
downvote count: 0
has body: BigInteger class BigInteger(Integer): """A type for bigger ``int`` integers. Typically generates a ``BIGINT`` in DDL, and otherwise acts like a normal :class:`.Integer` on the Python side. """ __visit_name__ = 'big_integer' BIGINT class BIGINT(BigInteger): """The SQL BIGINT type.""" __visit_name__ = 'BIGINT' But Column(BigInteger) and Column(BIGINT) can both work, both define a bigint in postgresql. How to distinguish them?
accepted answer: http://stackoverflow.com/a/51498406
favorite count: 0
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89968593
has title: What's the difference between BIGINT and BigInteger in SQLAlchemy?
tagged with: sqlalchemy

http://stackoverflow.com/comment/90026053
type: AnswerComment
has text: This is an excellent response, and thank you for providing multiple options and examples. Minor side question, how did you get the download link from Gohlke's site? Trying to copy link path doesn't seem to work for me (I get `;`)
type: Comment
comment on: http://stackoverflow.com/a/51528588
score: 0

http://stackoverflow.com/comment/90236905
type: QuestionComment
comment on: http://stackoverflow.com/q/51635881
has text: @MadPhysicist If I use the itertools code it works not as I need it. As I mentioned I need the paranthesis around the intermediate products which is not the case while using `join`
score: 0
type: Comment

http://stackoverflow.com/comment/89975240
type: QuestionComment
has text: I *strongly* urge you to consider upgrading to Python 3, at which point the standard library offers you the [`@singledispatch` decorator function](https://docs.python.org/3/library/functools.html#functools.singledispatch) to take care of type-based dispatching.
score: 4
comment on: http://stackoverflow.com/q/51503202
type: Comment

http://stackoverflow.com/comment/90008354
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/51499441
has text: @Matthew I added a couple other edits to the class. Apparently, I was getting a `'function' object has no attribute '_input_kwargs'` error when trying the transformer out, and I also added backwards compatibility for python 2.7 with the `super(Parent, self).__init__()` initializer. Interestingly, the solution is very hacky now because it's not only inheriting from `VectorAssembler`, but it's also wrapping an instance of the class.
type: Comment

http://stackoverflow.com/comment/90081180
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51556833
type: Comment
has text: This sounds like a question much better suited to https://scicomp.stackexchange.com Especially asking which programming language to use is clearly off-topic here. It is quite broad as well, ask here about concrete and focused problems to solve, not for possible tricks.

http://stackoverflow.com/comment/98024844
type: AnswerComment
has text: this command doesn't work on windows and even if you compile files one by one with batch files, you still will be getting the error
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51627810

http://stackoverflow.com/q/51516588
has answer: http://stackoverflow.com/a/51516802
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
has title: KeyError while executing SQL with parameters
has body: I am getting KeyError while running below code. I am trying to pass parameters using separate parameters variable. Code: import teradata host,username,password = 'hostname','uname', 'pwd' udaExec = teradata.UdaExec (appName="APtest", version="1.0", logConsole=False) connect = udaExec.connect(method="odbc",system=host, username=username, password=password, dsn="dsnname") val1='NULL' val2='NULL' parameters={'param1':val1, 'param2': val2} qry=""" SELECT number FROM table WHERE number = %(param1)s AND col=%(param2)s """ connect.execute(qry, parameters) Error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/tmp/lib/python2.7/site-packages/teradata/udaexec.py", line 675, in execute self.internalCursor.execute(query, params, **kwargs) File "/tmp/lib/python2.7/site-packages/teradata/udaexec.py", line 745, in execute self._execute(self.cursor.execute, query, params, **kwargs) File "/tmp/lib/python2.7/site-packages/teradata/udaexec.py", line 787, in _execute logParamCharLimit) File "/tmp/lib/python2.7/site-packages/teradata/udaexec.py", line 875, in _getParamsString if isinstance(params[0], (list, tuple)): KeyError: 0 If i write the query in below manner then it works but i have very long list of parameters therefore need it in separate parameter variable. This works: qry=""" SELECT number FROM table WHERE number = '%s' AND col='%s' """ % (val1, val2)
answer count: 1
favorite count: 0
score: 0
tagged with: teradata
tagged with: python

http://stackoverflow.com/q/51531109
accepted answer: http://stackoverflow.com/a/51547749
has comment: http://stackoverflow.com/comment/90042898
has comment: http://stackoverflow.com/comment/90030009
type: Question
linked to: http://stackoverflow.com/q/37326206
has answer: http://stackoverflow.com/a/51547749
score: -2
has title: Passing kwargs to a custom field in django
downvote count: 2
answer count: 1
has body: I used this question as a base for creating a custom field: Django File upload size limit When I try to makemigrations I get an error stating that 'content_types' isn't in the kwargs. I've debugged through the code and it almost seems like my custom field init is being called twice. Once from within the model where I have this field (with the kwargs) and once without the kwargs included. I referenced this post: How to pass additional keyword arguments in a custom Field in Django Rest Framework? However I am already doing whatever the solution says. class MediaField(FileField): def __init__(self, *args, **kwargs): self.content_types = kwargs.pop('content_types') self.max_upload_size = kwargs.pop('max_upload_size') super(MediaField, self).__init__(*args, **kwargs) The field in action in the model: media = MediaField(upload_to='media', # this will create a folder in MEDIA_ROOT content_types=['jpeg', 'jpg', 'png'], max_upload_size=5242880) the error: KeyError: 'content_types' the stacktrace: (efs-cP0vQdei) user@right:~/Documents/websites/efs$ ./manage.py makemigrations Traceback (most recent call last): File "./manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/user/.local/share/virtualenvs/efs-cP0vQdei/lib/python3.6/sit…
favorite count: 0
linked to: http://stackoverflow.com/q/2472422
tagged with: field
has comment: http://stackoverflow.com/comment/90030028
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90035995
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/90042882

http://stackoverflow.com/comment/90184319
type: QuestionComment
has text: `sorted(map(int, set(B) - set(A)))`
type: Comment
comment on: http://stackoverflow.com/q/51609791
score: 0

http://stackoverflow.com/a/51599623
has comment: http://stackoverflow.com/comment/90166183
type: Answer
has body: Use numpy.column_stack: Stack 1-D arrays as columns into a 2-D array np.column_stack((A, B)) array([[1, 4], [2, 6], [5, 7], [8, 9]])
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90166083
has comment: http://stackoverflow.com/comment/90166143
answers question: http://stackoverflow.com/q/51599596
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51599596
has comment: http://stackoverflow.com/comment/90166059

http://stackoverflow.com/comment/90198425
score: 0
type: Comment
type: QuestionComment
has text: It's a [RTFM](https://docs.python.org/2/library/subprocess.html#subprocess.Popen)-kind of answer ... you must call Popen with a list containing the "executable" and every single parameter something like`p = subprocess.Popen([filepath,os.path.abspath('.\\file.txt')], stdout=subprocess.PIPE, stdin=subprocess.PIPE)`. You can use `communicate` if the called "program" reads from `stdin`.
comment on: http://stackoverflow.com/q/51616422

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/51555312
tags question: http://stackoverflow.com/q/51548652
tags question: http://stackoverflow.com/q/51503386
tags question: http://stackoverflow.com/q/51495003
tags question: http://stackoverflow.com/q/51585445
tags question: http://stackoverflow.com/q/51507820
type: Tag
tags question: http://stackoverflow.com/q/51544389
tags question: http://stackoverflow.com/q/51637504
tags question: http://stackoverflow.com/q/51596853
tags question: http://stackoverflow.com/q/51605406
tags question: http://stackoverflow.com/q/51521453
tags question: http://stackoverflow.com/q/51518500
tags question: http://stackoverflow.com/q/51559363
tags question: http://stackoverflow.com/q/51544257
tags question: http://stackoverflow.com/q/51566274
tags question: http://stackoverflow.com/q/51613290
tag name: xml
tags question: http://stackoverflow.com/q/51544765
tags question: http://stackoverflow.com/q/51497714
tags question: http://stackoverflow.com/q/51512938
tags question: http://stackoverflow.com/q/51490944
tags question: http://stackoverflow.com/q/51546336
tags question: http://stackoverflow.com/q/51524863
tags question: http://stackoverflow.com/q/51563548
tags question: http://stackoverflow.com/q/51536757
tags question: http://stackoverflow.com/q/51555209
tags question: http://stackoverflow.com/q/51531741
tags question: http://stackoverflow.com/q/51612811
tags question: http://stackoverflow.com/q/51621579

http://stackoverflow.com/a/51599468
answers question: http://stackoverflow.com/q/51599289
score: 0
type: AcceptedAnswer
has body: Create a helper function to handle replacements: def helper(mtch): return df.loc[df.match.eq(mtch.group().lower()), 'use'].values[0] Then use a list comprehension with re.sub: [ re.sub(r'|'.join(df.match.values), lambda x: helper(x), i, flags=re.I) for i in m ] # ['1st Officer', 'Executive Officer'] If you really want the originals too: set(m + [re.sub(r'|'.join(df.match.values), lambda x: helper(x), i, flags=re.I) for i in m]) # {'1st Officer', 'Executive Officer', 'First Officer'} Personally, I think it would be easier to accomplish this by using a dictionary instead of a dataframe, which allows for much easier lookup: dct = dict(df.values) # {'and': '&amp;', 'first': '1st'} [ re.sub(r'|'.join(dct.keys()), lambda x: dct[x.group().lower()], i, flags=re.I) for i in m ] # ['1st Officer', 'Executive Officer']
type: Answer
accepted answer of: http://stackoverflow.com/q/51599289

http://stackoverflow.com/comment/89938904
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51484937
has text: @BrenBarn. That's kind of the way I've solved it now. I have made the class "castable" to `tuple` and used `.to_dict()` for creating dictionaries.

http://stackoverflow.com/q/51525416
tagged with: tkinter
score: 0
has answer: http://stackoverflow.com/a/51547336
type: Question
has comment: http://stackoverflow.com/comment/90019737
has body: My goal is for my nascent custom GUI application, which subclasses tkinter.Frame, to expand in both directions independently when its parent window is resized. This worked when I first built it in a script using native tkinter classes only (see bottom of post for that code), but ever since I restructured it as a subclass (see first block of code below), it insists on keeping its original proportions when resizing. That is, if I maximize the parent window, the main GUI frame expands diagonally only until it hits the bottom of the screen. Then the rest of the window to the right is left as empty gray space. My question is: What am I doing wrong in the class implementation that's causing this issue? Here is a screenshot of the problem, and below is the code used to generate the GUI in the picture (excuse the ugly color scheme, it was just to help keep my frames straight when designing/debugging it): [EDITED TO REMOVE UNNECESSARY CODE (in this part, more of it turned out to be necessary to generate the frame I was seeing than originally thought, so I couldn't cut that much):] from tkinter import * from tkinter import ttk class CharDbGui(Frame): # Mage character database object def __init__(self, root, database=None, *args, **kwargs): Frame.__init__(self, root, *args, **kwargs) self.root = root ### Broad layout into color-coded frames first ### self.rowweight(range(1, 5), [10, 40, 40, 10]) self.colweight(range(1, 4), [25, 75, 25]) top_toolbar = Frame(self, bg="green", height=50, width=1) top_toolbar.grid(row=1, column=1, columnspan=4, sticky=E+W+N+S) leftbox = Frame(self, height=1, width=1) leftbox.grid(row=2, column=1, rowspan=2, sticky=N+S+E+W) midbox = Frame(self, bg="white", height=1, width=1) midbox.grid(row=2, column=2, rowspan=2, sticky=N+S+E+W) righttopbox = Frame(self, bg="black", height=1, width=1) righttopbox.grid(row=2, column=3, sticky=N+S+E+W) rightbottombox = Frame(self, bg="purple", height=1, width=1) rightbottombox.grid(row=3, column=3, sticky=N+S+E+W) b…
tagged with: subclassing
has comment: http://stackoverflow.com/comment/90020906
tagged with: user-interface
has comment: http://stackoverflow.com/comment/90062344
answer count: 1
has title: Troubleshooting frame expansion with tkinter
tagged with: expand
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90021378
has comment: http://stackoverflow.com/comment/90019892

nexus
type: Tag
tags question: http://stackoverflow.com/q/51540884
tags question: http://stackoverflow.com/q/51525435
tag name: nexus

http://stackoverflow.com/q/51567519
has body: Myself and a group of people "bet" on which teams will win on different football matches results (no money involved). There are 3 possibilities of points being awarded to the player. points = [0, 3, 4] So, if I say team A will win 1-0. If team A loses, I get no points. If team A wins, I get 3 points. If team A wins 1-0, I get an additional point, for a total of 4 points. So, for that specific bet I can get 0, 3, or 4 points. So does everybody else who participated in the bet. So I was trying to get all possible combinations of results. For two players, I want to be able to obtain this kind of output (example for two players): "Player 1" 0 0 0 3 3 3 4 4 4 "Player 2" 0 3 4 0 3 4 0 3 4 I used to have an Excel file that used VBA to calculate these possible results, but the number of players was fixed, so the code did not adapt to adding or removing players. I'm trying to create a function that can calculate and output some data structure with all possible combinations of results, for different (and a dynamic) number of players. I have read several questions (10+) about combinations in python but none of those cover this specific scenario. They usually cover using itertools for permutations (not the case because we can all have the same result), for multiple combinations (won't work if the number of combinations exceed the values of the possible results (3). I did manage to get something similar to what i need by using: string_points = str(points[0])+str(points[1])+str(points[2]) for p in itertools.product(string_points, repeat=3): print(p) The result is a sequence of tuples with string values of the possible results: ('0', '0') ('0', '3') ('0', '4') ('3', '0') ('3', '3') ('3', '4') ('4', '0') ('4', '3') ('4', '4') But being strings, I can't perform any operations on them or calculate statistics... Is there any way to make this work using itertools? Would anyone suggest a different approach altogether? I am open to any kind of solution. Is there any kind of data structur…
type: Question
score: 0
has title: Combinations : How to calculate all possible combinations of points awarded for match results guesses game
has answer: http://stackoverflow.com/a/51567535
answer count: 1
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51567535

http://stackoverflow.com/comment/90040640
score: 0
comment on: http://stackoverflow.com/q/51533696
type: Comment
type: QuestionComment
has text: Thanks, sometimes in real it is different ;) So you need filter first row of `DataFrame` or need filter out first True value of boolean mask?

http://stackoverflow.com/comment/90024535
has text: the issue with your solution is that if `items.py`, in which `class Person` and `class Pet` are declared, executes before the Spider even begins crawling, then the fields are created before i would even know how many pets a person might have
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51527494

http://stackoverflow.com/comment/90034203
score: 0
type: Comment
has text: I try connect= create_engine('mysql+mysqldb://root:PW@localhost:3306/test') but error in "ModuleNotFoundError: No module named 'MySQLdb'". so I install mysqldb but Could not find a version...how can I fixed?
comment on: http://stackoverflow.com/a/51530272
type: AnswerComment

http://stackoverflow.com/comment/90123349
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51578978
has text: @WillemVanOnsem no in my `views.py`, I have defined a `logout_view` as a function for logging out users.Nowhere else in `views.py` file, I have defined any function called `logout`.

http://stackoverflow.com/a/51484818
answers question: http://stackoverflow.com/q/51484712
downvote count: 0
upvote count: 6
has body: You must pass the result of the recursive call up the stack: if isinstance(v, dict): return find_location(v) # note the 'return' Without the return, the line is just a statement that calls the function but doesn't return its result (or ends the surrounding function). And without a return statement, a function implicitly returns None.
score: 6
type: Answer

http://stackoverflow.com/q/51585600
tagged with: variables
has comment: http://stackoverflow.com/comment/90136723
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/17873384
answer count: 0
has comment: http://stackoverflow.com/comment/90136681
has title: How to prevent rewriting input variable in a function?
has body: I'm trying to write a function that takes a list as an input and returns a modified version of that list such that the function does not change the input list. The input variable T is a list of lists. I have tried def function(T): Tree = copy.copy(T) Do stuff with Tree return Tree only to discover that T has been changed by the function. I have also tried Tree = T[:] but that also doesn't work. Any suggestions?
duplicate of: http://stackoverflow.com/q/17873384
type: Question
tagged with: local
score: 0

amazon-ecs
type: Tag
tag name: amazon-ecs
tags question: http://stackoverflow.com/q/51517996

http://stackoverflow.com/comment/89982938
type: AnswerComment
score: 0
has text: Thanks. How can I modify your code for printing into a text file?
type: Comment
comment on: http://stackoverflow.com/a/51500728

http://stackoverflow.com/a/51570818
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51570764
accepted answer of: http://stackoverflow.com/q/51570764
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90107671
upvote count: 1
downvote count: 0
has body: The pd.DataFrame constructor accepts a list of dictionaries directly. This will be more efficient than appending repeatedly to an existing dataframe. Here's a demo: d1 = {'name': 'Demetrius', 'number': '0001', 'style': 'D', 'text': 'Demetrius an der...', 'year': '1797'} d2 = {'name': 'ABC', 'number': '0002', 'style': 'E', 'text': 'Some text', 'year': '1850'} L = [d1, d2] df = pd.DataFrame(L) print(df) name number style text year 0 Demetrius 0001 D Demetrius an der... 1797 1 ABC 0002 E Some text 1850

http://stackoverflow.com/comment/90019835
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51524463
has text: Does it work if you add a break before the `delete = ` line and letting it load first then let your code continue?
type: Comment

http://stackoverflow.com/a/51512461
has comment: http://stackoverflow.com/comment/89993324
has comment: http://stackoverflow.com/comment/90030527
accepted answer of: http://stackoverflow.com/q/51512416
has comment: http://stackoverflow.com/comment/90003063
answers question: http://stackoverflow.com/q/51512416
type: AcceptedAnswer
score: 4
has body: You can connvert column to_datetime and then find indices by max and min values by idxmax and idxmin: a = pd.to_datetime(df['yrmnt'], format='%Y %m') print (a) 0 2015-03-01 1 2015-03-01 2 2013-08-01 3 2015-08-01 4 2014-09-01 5 2015-10-01 6 2016-02-01 7 2015-11-01 8 2015-11-01 9 2015-11-01 10 2017-02-01 Name: yrmnt, dtype: datetime64[ns] print (df.loc[a.idxmax(), 'yrmnt']) 2017 02 print (df.loc[a.idxmin(), 'yrmnt']) 2013 08 Difference in months: b = a.dt.to_period('M') d = b.max() - b.min() print (d) 42 Another solution working only with month period created by Series.dt.to_period: b = pd.to_datetime(df['yrmnt'], format='%Y %m').dt.to_period('M') print (b) 0 2015-03 1 2015-03 2 2013-08 3 2015-08 4 2014-09 5 2015-10 6 2016-02 7 2015-11 8 2015-11 9 2015-11 10 2017-02 Name: yrmnt, dtype: object Then convert to custom format by Period.strftime minimal and maximal values: min_d = b.min().strftime('%Y %m') print (min_d) 2013 08 max_d = b.max().strftime('%Y %m') print (max_d) 2017 02 And subtract for difference: d = b.max() - b.min() print (d) 42
has comment: http://stackoverflow.com/comment/89993333
type: Answer
has comment: http://stackoverflow.com/comment/90030610
has comment: http://stackoverflow.com/comment/90030563
upvote count: 4
has comment: http://stackoverflow.com/comment/90003642
downvote count: 0
has comment: http://stackoverflow.com/comment/90030550
has comment: http://stackoverflow.com/comment/90030548
has comment: http://stackoverflow.com/comment/90003253
has comment: http://stackoverflow.com/comment/90030355
has comment: http://stackoverflow.com/comment/90003918
has comment: http://stackoverflow.com/comment/90030326

http://stackoverflow.com/comment/89965393
score: 0
type: QuestionComment
has text: I use a ModelForm as form. How can I solve my problem with model form?
type: Comment
comment on: http://stackoverflow.com/q/51497860

http://stackoverflow.com/comment/90062114
type: AnswerComment
type: Comment
has text: @A.Torres: Yes. So say you call `myfunc(val1, val2, val3)`, then the `MM_ITERS` variable would have `MM_ITERS_default` and `SPHERIZE` would have `SPHERIZE_default`. On the other hand if you called `myfunc(val1, val2, val3, val4)`, then `MM_ITERS` would have `val4` while `SPHERIZE` would have `SPHERIZE_default`. And `myfunc(val1, val2, val3, val4, val5)`, has `val4` for `MM_ITERS` and `val5` for `SPHERIZE`. You could also do, for example, `myfunc(val1, val2, val3, SPHERIZE=val5)`, in which case `MM_ITERS` variable would have `MM_ITERS_default` and `SPHERIZE` would have `val5`.
comment on: http://stackoverflow.com/a/51546746
score: 1

http://stackoverflow.com/a/51567928
type: Answer
answers question: http://stackoverflow.com/q/51567427
score: 0
has body: You can also use sets: with open("kalimat.txt",'r') as f: text = f.read() search_words = set(["makan","Rina","mahal"]) for sentence in text.split("."): words_in_sentence = set(sentence.split()) if words_in_sentence.intersection(search_words): print(sentence)

http://stackoverflow.com/q/51492827
linked to: http://stackoverflow.com/q/26473681
has comment: http://stackoverflow.com/comment/89955217
has body: When i am trying to install astroscrappy in my Linux Mint 19 system with command pip install astroscrappy, giving error that below Collecting astroscrappy Using cached https://files.pythonhosted.org/packages/80/12/899e09a3dee9055fb1428c22a42ca65e24242c4491a30de982af38cea792/astroscrappy-1.0.5.tar.gz Complete output from command python setup.py egg_info: OpenMP was not found. astroscrappy will be compiled without OpenMP. (Use the "-v" option of setup.py for more details.) Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/tmp/pip-build-5apIDa/astroscrappy/setup.py", line 77, in &lt;module&gt; package_info = get_package_info() File "/tmp/pip-build-5apIDa/astroscrappy/astropy_helpers/astropy_helpers/setup_helpers.py", line 396, in get_package_info ext_modules.extend(setuppkg.get_extensions()) File "astroscrappy/utils/setup_package.py", line 104, in get_extensions '(End of OpenMP info)').format(*outputs)) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 71: ordinal not in range(128) ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-5apIDa/astroscrappy/ What should i do?
answer count: 0
tagged with: installation
duplicate of: http://stackoverflow.com/q/26473681
type: Question
has title: Pip install for Astroscrappy. Command "python setup.py egg_info" failed with error code 1
score: 0
has comment: http://stackoverflow.com/comment/89954322
type: UnansweredQuestion
tagged with: pip
has comment: http://stackoverflow.com/comment/89967944
tagged with: python
has comment: http://stackoverflow.com/comment/89955892

http://stackoverflow.com/comment/90146790
comment on: http://stackoverflow.com/q/51590156
has text: The code is very long and it works outside of docker. I don't think that it brings anything to the table... see the following link to have an example of how the method "self._send_to_timeseries(msg)" works: https://github.com/PredixDev/predix-volcano-app/blob/master/setup/ingest_data.py
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90043278
score: 0
comment on: http://stackoverflow.com/a/51537530
type: Comment
has text: thanks, I dont want to Join the list items into two lists, I would like to keep the original list items as they are but nest them in an parent list
type: AnswerComment

http://stackoverflow.com/q/51560655
accepted answer: http://stackoverflow.com/a/51564903
has comment: http://stackoverflow.com/comment/90088385
type: Question
tagged with: ctypes
has body: .7 file contains MRS data from GE scanner. I want to read its header, change some of its fields values like scan date, etc., and save a new .7 file with modified header and rest of the data should be same. Code: from ctypes import * import ge_util as utilge class PfileHeaderLittle(LittleEndianStructure): """ Contains the ctypes Structure for a GE P-file rdb header. Dynamically allocate the ctypes _fields_ list later depending on revision """ _pack_ = 1 _fields_ = utilge.get_pfile_hdr_fields(20.0) hdr = PfileHeaderLittle() fname = r"P16896.7" filelike = open(fname, 'rb') filelike.seek(0) filelike.readinto(hdr) print("hdr: ", hdr) print("hdr: ", type(hdr.rhe_patname)) print("hdr: ", hdr.rhe_patname) hdr.rhe_patname = b"CHANGE_IT" print("hdr: ", hdr.rhe_patname) with open("my_file.7", 'wb') as file: file.write(hdr) Output: hdr: &lt;__main__.PfileHeaderLittle object at 0x0000025F75D09F48&gt; hdr: &lt;class 'bytes'&gt; hdr: b'MRS TEST1' hdr: b'CHANGE_IT' This code reads the header, modify one field and save it back. But, rest of the data is not saved. I read the saved file again and confirmed that the header is modified, but rest of the data is not present in the new file. How can I save modified header and save a new file with rest of the data? Here is ge_util: https://scion.duhs.duke.edu/vespa/project/export/3828/trunk/common/ge_util.py P16896.7 file: https://drive.google.com/open?id=1zqQbOUwlIa1_rv9OAVA0sQfEEaOFsne0
score: 0
has answer: http://stackoverflow.com/a/51564903
answer count: 1
has comment: http://stackoverflow.com/comment/90088455
has comment: http://stackoverflow.com/comment/90088514
has comment: http://stackoverflow.com/comment/90088206
tagged with: python
has comment: http://stackoverflow.com/comment/90088263
type: AnsweredQuestion
has title: How to read, modify header and save .7 file with rest of its data?

http://stackoverflow.com/a/51590093
type: AcceptedAnswer
has body: The problem stems from defining __abstract__ == True on User. From the docs: __abstract__ causes declarative to skip the production of a table or mapper for the class entirely. A class can be added within a hierarchy in the same way as mixin (see Mixin and Custom Base Classes), allowing subclasses to extend just from the special class If you make User abstract, to get mapped, it needs to be subclassed by another model, e.g. this works: class User(Base): __tablename__ = 'User' __abstract__ = True id = Column('id', INTEGER(display_width=11), primary_key=True, nullable=False) email = Column('email', VARCHAR(charset='utf8mb4', collation='utf8mb4_0900_ai_ci', length=100), unique=True) password = Column('password', VARCHAR(charset='utf8mb4', collation='utf8mb4_0900_ai_ci', length=45)) name = Column('name', VARCHAR(charset='utf8mb4', collation='utf8mb4_0900_ai_ci', length=100)) class AUser(User): pass if __name__ == '__main__': Base.metadata.create_all(bind=engine) add_user = AUser(email = "testing@testing.com", password = 'testing', name = 'testing') session.add(add_user) session.commit()
has comment: http://stackoverflow.com/comment/90147861
has comment: http://stackoverflow.com/comment/90150374
has comment: http://stackoverflow.com/comment/90147930
type: Answer
has comment: http://stackoverflow.com/comment/90147981
answers question: http://stackoverflow.com/q/51589930
score: 3
has comment: http://stackoverflow.com/comment/90149653
downvote count: 1
upvote count: 4
accepted answer of: http://stackoverflow.com/q/51589930

http://stackoverflow.com/a/51531736
upvote count: 6
has body: Use: df = (df.set_index('colum2')['colum1'] .str.split(',', expand=True) .stack() .reset_index(name='column3') .groupby('column3', as_index=False)['colum2'] .sum() .rename(columns={'colum2':'column4'}) ) print (df) column3 column4 0 a 80 1 b 70 2 c 70 3 f 40 4 g 50 5 z 50 Explanation: First set_index by column colum2 Create DataFrame by split Reshape by stack Create index by columns by reset_index groupby and aggregate sum Last rename column if necessary Another solution: from itertools import chain a = df['colum1'].str.split(',') lens = a.str.len() df = pd.DataFrame({ 'column3' : list(chain.from_iterable(a)), 'column4' : df['colum2'].repeat(lens) }).groupby('column3', as_index=False)['column4'].sum() print (df) column3 column4 0 a 80 1 b 70 2 c 70 3 f 40 4 g 50 5 z 50 Explanation: Create lists by split Get lengths of lsits by len Last repeat columns and flatten colum1 groupby and aggregate sum
score: 6
has comment: http://stackoverflow.com/comment/90067547
answers question: http://stackoverflow.com/q/51531697
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51531697
type: Answer
has comment: http://stackoverflow.com/comment/90044452

flask-cache
type: Tag
tags question: http://stackoverflow.com/q/51552789
tag name: flask-cache

http://stackoverflow.com/comment/90065928
comment on: http://stackoverflow.com/q/51549124
score: 0
type: Comment
type: QuestionComment
has text: ok, I can see your error from the title. But you 'd better put it to content box.

http://stackoverflow.com/comment/90016670
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51502808
type: Comment
has text: @MapMan - Do you have an xmlns in your XML? If so, let me know what it is and I will update my answer.

http://stackoverflow.com/comment/90100755
type: QuestionComment
comment on: http://stackoverflow.com/q/51567059
score: 0
has text: @Jacob just added it!
type: Comment

http://stackoverflow.com/a/51547542
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51546742
accepted answer of: http://stackoverflow.com/q/51546742
type: Answer
score: 3
downvote count: 0
has body: First, the author's solution is an optimized version of Counter(str1) == Counter(str2) (it returns False faster and creates a single instance of a Counter). It is, indeed, O(n) because hash table (Counter) access is O(1). Next, your solution is quadratic (O(n^2)) because each in is O(n) - it has to traverse the whole string. It is also wrong on strings with repetitions. Third, sorted(str1) == sorted(str2) is, indeed, linearithmic (O(n*log(n))) and thus is worse than the original linear solution. Note, however, that for small strings the constants may make a difference and the linearithmic (sorted) solution may turn out to be faster than the linear (Counter) one. Finally, beware that Python is usually implemented using an interpreter, so the actual performance may depend on whether you are using features implemented in C or in Python. E.g., if Counter is implemented in C, then Counter(str1) == Counter(str2) will probably outperform the author's solution hands down, even though algorithmically the author's solution is better.
upvote count: 3

http://stackoverflow.com/a/51569796
accepted answer of: http://stackoverflow.com/q/51569716
upvote count: 1
has comment: http://stackoverflow.com/comment/90105828
has body: Pandas expects each record to be a tuple, not a dict. Here's one way to make it work: items = [next(iter(d.items())) for d in json] pd.DataFrame.from_items(items, orient='index', columns=['Summary']) Then you get: Summary 1981121 Tasa 1981123 This fox only jumps on the top
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51569716
score: 1

http://stackoverflow.com/q/51548652
has comment: http://stackoverflow.com/comment/90065988
has comment: http://stackoverflow.com/comment/90065407
has comment: http://stackoverflow.com/comment/90065048
has comment: http://stackoverflow.com/comment/90065359
type: Question
has comment: http://stackoverflow.com/comment/90065206
has title: Accessing the zip file and folder in S3 from EC2 instance using boto3 package in Python
tagged with: amazon-web-services
has body: I got an issue, i want to look inside a zip File that i will drop on my bucket, it has this structure: main.zip ==>main/folder1/subfolder/file.xml ==>main/dolfer2/file.xml Using a lambda function i need to swim on the zip file capturate del path from xmls files then parse them with xml.dom.minidom I am doing this: key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) bucket = urllib.unquote_plus(event['Records'][0]['s3']['bucket']['name'].encode('utf8')) try: obj = s3.get_object(Bucket=bucket, Key=key) with io.BytesIO(obj["Body"].read()) as tf: # rewind the file tf.seek(0) # Read the file as a zipfile and process the members with zipfile.ZipFile(tf, mode='r') as zipf: for file in zipf.infolist(): fileName = file.filename putFile = s3.put_object(Bucket=bucket, Key='Open/'+fileName, Body=zipf.read(file)) print(putFile) how can i go over all the zip and capturate the path/object of the xmls file on the zip(even if they are inside any folder on the zip) to parse the xml with xml.dom.minidom? I got to go over en folder and got de xml file on it with: from xml.dom.minidom import parse, parseString import os import boto3 def lambda_handler(event, context): # TODO implement s3= boto3.client('s3') datos = [] if event: print('event:',event) file_obj = event['Records'][0] filename = str(file_obj['s3']['object']['key']) print('filename',filename) fileobj = s3.get_object(Bucket='mi-informacion-audit',Key=filename) file_content = fileobj[y]['Body'].read().decode('utf-8') #print(file_content) datos.append(file_content.replace('\n','')) for x in range(len(datos)): print(datos[x]) doc = parseString(datos[x]) nodeListCom = doc.getElementsByTagName('cfdi:Comprobante') for x in range(len(nodeListCom)): pk_xmlyear = nodeListCom[x].getAttribute('Fecha')[2:4] print(pk_xmlyear) return 'Hello from Lambda' But this folder contains 10 xml file and my code only reads the first one... any help?
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/90065314
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/90065139
has comment: http://stackoverflow.com/comment/90065628

http://stackoverflow.com/comment/90024847
has text: `for files in folderPath:` isn't doing what you think. You want `for file in os.listdir(folderPath):` instead.
type: QuestionComment
score: 1
type: Comment
comment on: http://stackoverflow.com/q/51528103

http://stackoverflow.com/comment/90202692
comment on: http://stackoverflow.com/q/51618541
score: 5
has text: in the line `if cor == gue`, `cor` and `gue` are always zero so they are always equal. Changing these variables in the `ans()` and `guess()` functions only changes them inside that function. There are ways around this (such as declaring those variables nonlocal) but the best way is to return the values.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90070382
score: 0
comment on: http://stackoverflow.com/q/51551267
type: Comment
type: QuestionComment
has text: ok uninstall and reinstall fixed this

http://stackoverflow.com/q/51500889
tagged with: dataframe
answer count: 3
tagged with: pandas
has title: Python: 'ValueError: can only convert an array of size 1 to a Python scalar' when looping over rows in pd.DataFrame
has answer: http://stackoverflow.com/a/77217972
favorite count: 0
has body: I would like to loop over the rows of a DataFrame, in my case to calculate strength ratings for a number of sports teams. The DataFrame columns 'home_elo' and 'away_elo' contain the pre-match strength rating (ELO score) of the teams involved and are updated in the row of the next home / away match after the match (each team has two strength ratings at any point in time, for home and away games), with what update_elo(a,b,c) returns. The respective code snippet looks as follows: for index in df.index: counter = counter + 1 # Calculation of post-match ELO scores for home and away teams if df.at[index,'updated'] == 2: # Update next match ELO scores if not yet updated but pre-match ELO scores available try: all_home_fixtures = df.date_rank[df['localteam_id'] == df.at[index,'localteam_id']] next_home_fixture = all_home_fixtures[all_home_fixtures &gt; df.at[index,'date_rank']].min() next_home_index = df[(df['date_rank'] == next_home_fixture) &amp; (df['localteam_id'] == df.at[index,'localteam_id'])].index.item() except ValueError: print('ERROR 1 at' + str(index)) df.at[index,'updated'] = 4 try: all_away_fixtures = df.date_rank[df['visitorteam_id'] == df.at[index,'visitorteam_id']] next_away_fixture = all_away_fixtures[all_away_fixtures &gt; df.at[index,'date_rank']].min() next_away_index = df[(df['date_rank'] == next_away_fixture) &amp; (df['visitorteam_id'] == df.at[index,'visitorteam_id'])].index.item() except ValueError: print('ERROR 2 at' + str(index)) df.at[index,'updated'] = 4 # print('Current: ' + str(df.at[index,'fixture_id']) + '; Followed by: ' + str(next_home_fixture)) # print('Current date rank: ' + str(df.at[index,'date']) + ' ' + str(df.at[index,'date_rank']) + '; Next home date rank: ' + str(df.at[next_home_index,'date_rank']) + '; Next away date rank: ' + str(df.at[next_away_index,'date_rank'])) df.at[next_home_index, 'home_elo'] = update_elo(df.at[index,'home_elo'],df.at[index,'away_elo'],df.at[index,'actual_score']) df.at[next_away_index, 'away_elo'] = up…
has comment: http://stackoverflow.com/comment/89970505
has comment: http://stackoverflow.com/comment/89970659
accepted answer: http://stackoverflow.com/a/51501255
score: 16
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51501255
has answer: http://stackoverflow.com/a/61071890
type: Question
possible better answer: http://stackoverflow.com/a/61071890
upvote count: 16

http://stackoverflow.com/q/51591483
tagged with: python
has answer: http://stackoverflow.com/a/51591541
has answer: http://stackoverflow.com/a/51591598
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51591598
type: Question
accepted answer: http://stackoverflow.com/a/51591541
tagged with: dataframe
score: 0
answer count: 2
tagged with: pandas
has title: How to select values on dataframe conditioned to certain string matching a repetead id?
has body: I have this dataframe: user_id event 1 registration 1 visit 1 purchase 2 registration 2 external I would like to select all values from every user_id which has at least one event of type external in order to store them in another dataframe. So, for this case, I would like to have a dataframe with the next information: user_id event 2 registration 2 external How could I do that?

http://stackoverflow.com/a/51552357
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51551868
has body: I think condition is not necessary, use str.split with select last strings by indexing: pr1 = pd.DataFrame({'식품이름':[' ~~@text','ssds','wew@efs']}) print (pr1) 식품이름 0 ~~@text 1 ssds 2 wew@efs pr1['new'] = pr1['식품이름'].str.split("@").str[-1] print (pr1) 식품이름 new 0 ~~@text text 1 ssds ssds 2 wew@efs efs
has comment: http://stackoverflow.com/comment/90071982
type: Answer
has comment: http://stackoverflow.com/comment/90071963
score: 0
has comment: http://stackoverflow.com/comment/90072040
accepted answer of: http://stackoverflow.com/q/51551868

http://stackoverflow.com/a/57569316
upvote count: 2
has body: Instead, use subprocess.check_output(). Since your command has multiple words, parse your command with split() method from shlex lib. Something like this: import subprocess import shlex cmd=shlex.split('[find][2] root_dir -name file_name') print subprocess.check_output(cmd)
downvote count: 0
answers question: http://stackoverflow.com/q/51529415
type: Answer
score: 2

http://stackoverflow.com/q/51611378
tagged with: python
has answer: http://stackoverflow.com/a/51611629
has answer: http://stackoverflow.com/a/73753834
upvote count: 13
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90187432
has body: I have a dataframe that looks like this: level_0 level_1 Repo Averages for 27 Jul 2018 0 Business Date Instrument Ccy 1 27/07/2018 GC_AUSTRIA_SUB_10YR EUR 2 27/07/2018 R_RAGB_1.15_10/18 EUR 3 27/07/2018 R_RAGB_4.35_03/19 EUR 4 27/07/2018 R_RAGB_1.95_06/19 EUR I am trying to get rid of the top row and only keep Business Date Instrument Ccy 0 27/07/2018 GC_AUSTRIA_SUB_10YR EUR 1 27/07/2018 R_RAGB_1.15_10/18 EUR 2 27/07/2018 R_RAGB_4.35_03/19 EUR 3 27/07/2018 R_RAGB_1.95_06/19 EUR I tried df.columns.droplevel(0) but not successful any help is more than welcome
score: 13
has answer: http://stackoverflow.com/a/63309369
tagged with: drop
has answer: http://stackoverflow.com/a/62596960
type: Question
has title: Remove top row from a dataframe
possible better answer: http://stackoverflow.com/a/63031195
has answer: http://stackoverflow.com/a/63031195
has comment: http://stackoverflow.com/comment/90187534
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90187663
accepted answer: http://stackoverflow.com/a/63309369
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90187440
tagged with: pandas
answer count: 5

http://stackoverflow.com/a/51498930
upvote count: 5
accepted answer of: http://stackoverflow.com/q/51482740
has body: It is behaving just the way it should. It's just that how you print the query. from sqlalchemy.dialects import postgresql query = statement.compile(dialect=postgresql.dialect(),compile_kwargs={"literal_binds": True}) print(query) # will print the compiled query statement againt the dialect.
answers question: http://stackoverflow.com/q/51482740
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/89967631
type: Answer

http://stackoverflow.com/comment/90117812
has text: The signature of this method is `add_parser(self, name, **kwargs)`. So there's not a lot for PyCharm to use (compare that with the `__init__` of `ArgumentParser` class). `add_parser` then creates the parser with `self._parser_class(**kwargs)`.
comment on: http://stackoverflow.com/q/51574640
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51572352
tagged with: mnist
tagged with: python-2.7
score: 0
has body: I am following a tutorial in TensorFlow and MNIST. I do not understand the error message or how to fix it. I am using Jupyter Notebook, Python 2.7. Is this a python version issue and if so how can I fix this? The code and error follow: import tensorflow as tf X = tf.placeholder(tf.float32, [None, 28, 28, 1]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) init = tf.initialize_all_variables() # Model! Y = tf.nn.softmax(tf.matmul(tf.reshape(X, [-1, 784]), W), + b) TypeError Traceback (most recent call last) &lt;ipython-input-17-00f12701ef74&gt; in &lt;module&gt;() 1 # Model! ----&gt; 2 Y = tf.nn.softmax(tf.matmul(tf.reshape(X, [-1, 784]), W), + b) TypeError: bad operand type for unary +: 'Variable'
answer count: 1
has answer: http://stackoverflow.com/a/51572470
tagged with: jupyter-notebook
type: UnansweredQuestion
tagged with: python
tagged with: tensorflow
type: Question
has title: TypeError: bad operand type for unary +: 'Variable' Tensorflow MNIST

http://stackoverflow.com/q/51484601
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/89938385
tagged with: dataframe
type: Question
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51484666
downvote count: 0
favorite count: 0
tagged with: iteration
has body: I am new to python and struggling with a pretty basic concept, so bear with me. Please accept my apologies. Objetive: I have an existing dataframe I want to take the existing dataframe and create two separate versions (variables "df_1" and "df_2") based on it. They will be the same except they will have different country_ids. See Desired Output for dataframe 1 ("df_1") name occupation country_id mike plumber 123 mary plumber 123 joe plumber 123 See Desired Output for dataframe 2 ("df_2") name occupation country_id mike plumber 456 mary plumber 456 joe plumber 456 My Code country_id_1 = 123 country_id_2 = 456 df_0 = name occupation mike plumber mary plumber joe plumber df_1 = df_0 df_2 = df_0 df_1['country_id'] = df_1.shape[0]*[country_id_1] df_2['country_id'] = df_2.shape[0]*[country_id_2] When I Print I Get This Result print(df_1['country_id'] = df_1.shape[0]*[country_id_1]) print(df_2['country_id'] = df_2.shape[0]*[country_id_2]) name occupation country_id mike plumber 456 mary plumber 456 joe plumber 456 name occupation country_id mike plumber 456 mary plumber 456 joe plumber 456 It's obviously referring to the last variable I used (country_Id_2). I'm sure a loop/iteration would solve this but I do need two variables at the end of the day. Any help would be appreciated.
has answer: http://stackoverflow.com/a/51484790
tagged with: python
has title: Create Two Dataframes From One By Adding Distinct Data in One Column

http://stackoverflow.com/q/51577938
has body: I have two list of dictionaries as follows: x=[{'id':1, 'var1':2}, {'id':1, 'var1':2}, {'id':2, 'var1':2}] y=[{'var2':1, 'var3':2}, {'var2':3, 'var3':3}, {'var2':4, 'var3':4}] I want to merge each dict into each other dict, so the output is as follows: z=[{'id':1, 'var1':2, 'var2':1, 'var3':2}, {'id':1, 'var1':2, 'var2':3, 'var3':3}, {'id':2, 'var1':2, 'var2':4, 'var3':4}] However, when I use the following merge function: def merge_x_and_y(x_data, y_data): for x_entry, y_entry in zip(x_data, y_data): x_entry.update(y_entry ) return x_data I instead end up with: z=[{'id':1, 'var1':2, 'var2':1, 'var3':2}, {'id':1, 'var1':2, 'var2':1, 'var3':2}, {'id':2, 'var1':2, 'var2':2, 'var3':3}] So if a dict in x is a duplicate, it duplicates the dict from y, which I don't want. I want each x dict to be merged with a different y dict (even if the x dict is a duplicate). Is there a way to merge each x dict with a y dict ignoring duplicates? Edit: The reprex above works, but I still don't get the right outcome in my actual code. I think it might be to do with Lenik's suggestion, that the same elements may be referenced twice. Prior to the merge, I've tried to expand the data using: def expand_x(x): processed_x_data = [] [processed_x_data .extend([entry]*entry['count']) for entry in x] return processed_x_data After doing this step, should I reallocate a unique id to each entry to avoid double referencing?
has comment: http://stackoverflow.com/comment/90121517
tagged with: python
tagged with: merge
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90121248
has comment: http://stackoverflow.com/comment/90121334
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90121291
has answer: http://stackoverflow.com/a/51578030
possible better answer: http://stackoverflow.com/a/51578103
has answer: http://stackoverflow.com/a/51578103
has title: Merge two list of dicts in python when some dicts are duplicates
has comment: http://stackoverflow.com/comment/90121380
downvote count: 0
accepted answer: http://stackoverflow.com/a/51578030
favorite count: 0
linked to: http://stackoverflow.com/q/38987

http://stackoverflow.com/q/51632697
type: Question
has title: Prediction techniques using scikit-kearn (Polynomial regression)
upvote count: 0
tagged with: scikit-learn
score: -1
has body: I try to test a first example using sklearn: from sklearn.preprocessing import PolynomialFeatures from sklearn import linear_model X = [[0.44, 0.68], [0.99, 0.23]] vector = [109.85, 155.72] predict= [0.49, 0.18] poly = PolynomialFeatures(degree=2) X_ = poly.fit_transform(X) predict_ = poly.fit_transform(predict) clf = linear_model.LinearRegression() clf.fit(X_, vector) print clf.predict(predict_) But i have these errors: /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/__init__.py:148: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility from ._shortest_path import shortest_path, floyd_warshall, dijkstra,\ /usr/lib/python2.7/dist-packages/scipy/sparse/csgraph/_validation.py:5: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility File "hi.py", line 1, in &lt;module&gt; from sklearn.preprocessing import PolynomialFeatures ImportError: cannot import name PolynomialFeatures python -V --&gt; 2.7.6 Please, how can I deal with these errors? Bests.
has answer: http://stackoverflow.com/a/51632852
has comment: http://stackoverflow.com/comment/90229606
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/22914458
type: UnansweredQuestion
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/89948371
type: Comment
has text: Updated at the top
comment on: http://stackoverflow.com/a/51489605
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90189798
type: Comment
comment on: http://stackoverflow.com/a/51611986
has text: how to search if i have both teach, learn and learn, teach in two different rows, what should be the solution. as grepl searches for pattern. Do i have to give both patterns or is their any short cut
type: AnswerComment
score: 0

http://stackoverflow.com/q/51526229
has title: pytest- how to raise Assertion Error?
score: 1
has comment: http://stackoverflow.com/comment/90022617
has comment: http://stackoverflow.com/comment/90021408
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90023507
has body: I am writing a few test cases for a project. In my project an "Address" object MUST contain a set of 3 attributes, either a 'name','email','phone' or 'address','city','state_id'. @observes('name', 'email', 'phone', 'address', 'city', 'states_id', 'state') def validate_address_obj(self, name, email, phone, address, city, states_id, state): name_email_phone = name and email and phone address_city_state = address and city and (states_id or state) if not name_email_phone and not address_city_state: raise AssertionError( "A valid address has to have: {} AND/OR {} defined.".format( "name, email, and phone", "address, city, and state")) # fi # end def validate_address_obj This function validates that a set of attributes is present, if the required attributes are not present an 'AssertionError' should be raised. When i run my tests, no exceptions are raised. def test_validate_addresses(address_factory): """ An Address must consist of at least: a name, phone number, and email OR an address, city, and state """ # Testing name, email, and phone need to be set # when address, city, and states_id is not with pytest.raises(AssertionError): address_factory(name='', address='', city='', state=None) with pytest.raises(AssertionError): address_factory(email='', address='', city='', state=None) with pytest.raises(AssertionError): address_factory(phone='', address='', city='', state=None) # Testing address, city, and states_id need to be set # when name, email, and phone is not with pytest.raises(AssertionError): address_factory(address='', name='', email='', phone='') with pytest.raises(AssertionError): address_factory(city='', name='', email='', phone='') with pytest.raises(AssertionError): address_factory(state=None, name='', email='', phone='') # end def test_validate_addresses This is a snippet of my Test Case.
tagged with: exception
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90023918
tagged with: python
tagged with: pytest
answer count: 0
has comment: http://stackoverflow.com/comment/90023255
upvote count: 1
has comment: http://stackoverflow.com/comment/90021202
type: Question

http://stackoverflow.com/q/51618724
upvote count: 1
has answer: http://stackoverflow.com/a/51619072
tagged with: dataframe
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51618881
has answer: http://stackoverflow.com/a/51618957
has body: I have data samples from a database which I want to reshape from vertical to horizontal in python for further data analysis. The dataframe looks like this: ID measured_at weight aa 2017-11-04 78.1 bb 2018-04-08 74.2 bb 2018-04-16 73.2 bb 2018-04-28 72.1 cc 2018-03-02 90.2 cc 2018-03-20 88.9 I want it to look like this: id date1 weight1 date2 weight2 date3 weight3 aa 2017-11-04 78.1 NA NA NA NA bb 2018-04-08 74.2 2018-04-16 73.2 2018-04-28 72.1 cc 2018-03-02 90.2 2018-03-20 88.9 NA NA Some ids have more than 3 measurements so it needs to generate new date and weight columns for every new measurement on the same id. How could this be done?
tagged with: pandas
downvote count: 0
score: 1
has title: Reshaping dataframe from vertical to horizontal in python
favorite count: 0
tagged with: data-analysis
type: Question
tagged with: python
answer count: 3

http://stackoverflow.com/comment/90197001
type: Comment
comment on: http://stackoverflow.com/q/51611102
has text: see your code, gamecount = 0 then print (gamecount," ",gamelist[gamecount]) you can't concatenate a string with an integer so you need convert everything to string like print (str(gamecount)+" "+gamelist[gamecount])
score: 0
type: QuestionComment

http://stackoverflow.com/q/51569666
score: 0
type: Question
has title: Comparison on two columns from two text files using numpy
has body: I have two files with the txt format as shown below: File 1: Delimiter ^ ID^Name^Address^Date of Join^Pin^Country 1^John^No 123. Ml^2016-06-30^123123^USA 2^Shaw^No 13. MX^2014-02-30^423123^UK 3^Donn^No 453. MR^2015-01-30^523123^UAE File 2: Delimiter | Name|ID|Address|Date of Join|Pin|Country John|1|No 123. Ml|2016-06-30|123123|USA Shaw|2|No 13. MX|2014-02-30|423123|UK Donn|3|No 453. MR|2015-01-02|523123|UAE Donn|4|No 1. XR|2012-03-10|523123|UAE I want to do comparison on two 2 columns namely ID and Date of Join. My try: I am using numpy for this. import numpy as np data1 = np.loadtxt('E:\File1.txt', delimiter='^') data2 = np.loadtxt('E:\File2.txt', delimiter='|') np.savetxt('E:\Output.txt',data2[data1[:,0]!=data2[:,1] or data1[:,3]!=data2[:,3],:]) But getting an error: ValueError: could not convert string to float: ID
tagged with: numpy
tagged with: python-2.7
answer count: 1
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51569704

http://stackoverflow.com/a/51583672
type: Answer
has comment: http://stackoverflow.com/comment/90132654
answers question: http://stackoverflow.com/q/51583639
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90132671
has body: In order to find the length, you will have to type-cast the map to list (or tuple) and then you may call len over it. For example: &gt;&gt;&gt; len(list(map(lambda a: a[0], x))) 3
upvote count: 1

http://stackoverflow.com/a/51546846
answers question: http://stackoverflow.com/q/51546819
has comment: http://stackoverflow.com/comment/90061857
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: If you just want to space out checks, the time.sleep() function should work. However, as G_M's comment says, you should look into Selenium waits. Think about this: is there an element on the page that will indicate that the result is loaded? If so, use a Selenium wait on that element to make sure your program is only pausing until the result is loaded and not wasting any time afterwards.

http://stackoverflow.com/a/51516783
answers question: http://stackoverflow.com/q/51516709
has comment: http://stackoverflow.com/comment/90002133
has body: Just use: df.loc[df['name'].isin(values)]
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90001933

http://stackoverflow.com/comment/89999490
has text: Wow, this is so cool :) Thank you. It works as I want both views for creating and changing document. I wonder if I should do the same in ``add_view`` method in Document admin.
comment on: http://stackoverflow.com/a/51515361
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/104617480
has text: Interesting. I was trying to download a bunch of files and could see the ID of all the buttons, but `browser.find_element_by_id('single-download-btn')` found nothing. I ended up copying the inner html from the inspector and working with that directly. I'll refer back to this and try again if I run into the issue.
type: Comment
comment on: http://stackoverflow.com/a/51570044
score: 0
type: AnswerComment

series
tag name: series
tags question: http://stackoverflow.com/q/51571121
tags question: http://stackoverflow.com/q/51564120
type: Tag
tags question: http://stackoverflow.com/q/51488681
tags question: http://stackoverflow.com/q/51525385
tags question: http://stackoverflow.com/q/51548902
tags question: http://stackoverflow.com/q/51553634
tags question: http://stackoverflow.com/q/51563433
tags question: http://stackoverflow.com/q/51592274

http://stackoverflow.com/comment/90238090
has text: Sure, where can I send it to you ? (sorry new to stack overflow i'm not sure if there a messaging service here)
type: Comment
comment on: http://stackoverflow.com/a/51633533
type: AnswerComment
score: 0

http://stackoverflow.com/q/51562173
has answer: http://stackoverflow.com/a/58192827
downvote count: 1
has comment: http://stackoverflow.com/comment/90100425
tagged with: jupyter
favorite count: 0
type: UnansweredQuestion
has title: Where is ipython/jupyter config file located inside virtual environment created using `python -m venv myvenv`?
tagged with: python
tagged with: jupyter-console
has body: ipython and jupyter-console have different matplotlib backends. Due to this I can't show my plots when using jupyter-console. Both run in virtual environment on Xubuntu 16.04. [edit] Where is ipython/jupyter config file located inside virtual environment created using python -m venv myvenv? I know that system-wide configuration file is something like /.ipython/profile_default/ipython_kernel_config.py, and I can create it running ipython profile create. But the ipython virtual enviroment-wide configuration file? Do I even need it, isn't changing system-wide config enough? $ ipython Python 3.5.2 (default, Nov 23 2017, 16:37:01) Type 'copyright', 'credits' or 'license' for more information IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: import matplotlib In [2]: matplotlib.get_backend() Out[2]: 'TkAgg' $ jupyter-console Jupyter console 5.2.0 Python 3.5.2 (default, Nov 23 2017, 16:37:01) Type 'copyright', 'credits' or 'license' for more information IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: import matplotlib In [2]: matplotlib.get_backend() Out[2]: 'module://ipykernel.pylab.backend_inline'
score: 1
tagged with: matplotlib
linked to: http://stackoverflow.com/q/48207687
tagged with: ipython
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51562249
has comment: http://stackoverflow.com/comment/90091260

http://stackoverflow.com/q/51523301
has title: Strange "declare -x" output in Terminal
has comment: http://stackoverflow.com/comment/90017922
has comment: http://stackoverflow.com/comment/90017691
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90017541
has comment: http://stackoverflow.com/comment/90017239
has comment: http://stackoverflow.com/comment/90016567
has comment: http://stackoverflow.com/comment/90019550
type: Question
has comment: http://stackoverflow.com/comment/90016684
tagged with: declare
tagged with: terminal
score: 0
has comment: http://stackoverflow.com/comment/90017769
has body: So, I'm a complete newbie in Python. I'm currently learning from an Udemy course and, after installing jupyter and while trying to make the ''jupyter notebook'' command work (it always returned the error: jupyter: command not found), I probably did something I shouldn't have and now every time I open my terminal I get this: declare -x Apple_PubSub_Socket_Render="/private/tmp/com.apple.launchd.tCfOClSB1p/Render" declare -x HOME="/Users/user" declare -x LANG="pt_PT.UTF-8" declare -x LOGNAME="user" declare -x OLDPWD declare -x PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" declare -x PWD="/Users/user" declare -x SHELL="/bin/bash" declare -x SHLVL="1" declare -x SSH_AUTH_SOCK="/private/tmp/com.apple.launchd.5Iz52iBbGB/Listeners" declare -x TERM="xterm-256color" declare -x TERM_PROGRAM="Apple_Terminal" declare -x TERM_PROGRAM_VERSION="404" declare -x TERM_SESSION_ID="DE54F659-7CC8-49AA-BF54-79192A35FFF5" declare -x TMPDIR="/var/folders/k5/yt8wjdnx01lb0fgcgm_01zx40000gn/T/" declare -x USER="user" declare -x XPC_FLAGS="0x0" declare -x XPC_SERVICE_NAME="0" Can someone help me? I've literally looked everywhere online and tried so many different things, but nothing seems to work (also, the only answer I found online was a bit too complex for a newbie like me to understand...) Thanks!
tagged with: python
tagged with: jupyter
has comment: http://stackoverflow.com/comment/90018275
has comment: http://stackoverflow.com/comment/90017991
has comment: http://stackoverflow.com/comment/90015493
tagged with: jupyter-notebook

http://stackoverflow.com/comment/90059233
has text: The reason I don't want to put it in a function is because I have lots of more code that runs in to trouble when I make a new function... (I'm adding GUI to a already complete program) and nevertheless, the code os.excel.... seems to distant Shell from all previous functions. It's almost like Shell is restarting clean with nothing else
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51545528
type: Comment

http://stackoverflow.com/q/51619188
has comment: http://stackoverflow.com/comment/90208728
has title: Find and Replace Operation Using Regex with Inner Function Not Working
answer count: 1
has answer: http://stackoverflow.com/a/51622263
has comment: http://stackoverflow.com/comment/90204150
has body: I'm new on Stack Overflow and I am hoping someone can please help me with the following code. I am trying to adapt a piece of code from the Ascher, Ravenscroft, and Martelli Python Cookbook. I would like to replace all words in Text containing a 'long-s' with the equivalent word spelled with a modern lowercase s using dictionary key:value pairs (all text is utf-8). I am able to build the dictionaries from existing tab-separated files without a problem (I am using a simple sample dictionary in the code for ease of editing), however I would like to complete all the changes in a single pass for speed and efficiency. I have removed the map and escape parts of the code as I don't think the 'long-s' needs escaping (I could be wrong though!). The first section works fine, however the inner function one_xlat seems not to do anything. It does not return/print Text at the end, and there is no error message. I have run the code in the command line and IDLE with the same result. I have run the code with and without using map and escape, and I have renamed the variables just to be sure, but I cannot quite make it work. Would someone please be able to help? Sorry if I'm missing something obvious and thank you very much in advance. Original Code from Ascher, Ravenscroft, and Martelli: import re def multiple_replace(text, adict): rx = re.compile('|'.join(map(re.escape, adict))) def one_xlat(match): return adict[match.group(0)] return rx.sub(one_xlat, text) The adapted version: import re adictCR = {"handſome":"handsome","ſeated":"seated","veſſels":"vessels","ſea-side":"sea-side","ſand":"sand","waſhed":"washed", "oſ":"of", "proſpect":"prospect"} text = "The caſtle, which is very extenſive, contains a ſtrong building, formerly uſed by the late emperor as his principal treaſury, and a noble terrace, which commands an extensive proſpect oſ the town of Sallee, the ocean, and all the neighbouring country." def word_replace(text, adictCR): regex_dict = re.compile('|'.join(adictCR)) print(r…
tagged with: python
tagged with: dictionary
tagged with: regex
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90207986
has comment: http://stackoverflow.com/comment/90208169
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90204095
accepted answer: http://stackoverflow.com/a/51622263
type: Question
score: 0

http://stackoverflow.com/a/51581057
accepted answer of: http://stackoverflow.com/q/51516666
score: 17
has comment: http://stackoverflow.com/comment/90150035
has body: The answer for this is essentially the same as for threading.Condition vs threading.Event; a condition without a lock is an event, not a condition(*). Conditions are used to signal that a resource is available. Whomever was waiting for the condition, can use that resource until they are done with it. To ensure that no-one else can use the resource, you need to lock the resource: resource = get_some_resource() async with resource.condition: await resource.condition.wait() # this resource is mine, no-one will touch it await resource.do_something_async() # lock released, resource is available again for the next user Note how the lock is not released after wait() resumes! Until the lock is released, no other co-routine waiting for the same condition can proceed, access to the resource is made exclusive by virtue of the lock. Note that the lock is released while waiting, so other coroutines can add themselves to the queue, but for wait() to finally return the lock must first be re-acquired. If you don't need to coordinate access to a shared resource, use an event; a condition is basically a lock and event combined into one primitive, avoiding common implementation pitfalls. Note that multiple conditions can share locks. This would let you signal specific stages, and other coroutines can wait for that specific stage to arrive. The shared lock would coordinate access to a single resource, but different conditions are signalled when each stage is initiated. For threading, the typical use-case for conditions offered is that of a single producer, and multiple consumers all waiting on items from the producer to process. The work queue is the shared resource, the producer acquires the condition lock to push an item into the queue and then call notify(), at which point the next consumer waiting on the condition is given the lock (as it returns from wait()) and can remove the item from the queue to work on. This doesn't quite translate to a coroutine-based application, as corouti…
type: AcceptedAnswer
upvote count: 17
type: Answer
answers question: http://stackoverflow.com/q/51516666
has comment: http://stackoverflow.com/comment/90142606
downvote count: 0

http://stackoverflow.com/comment/90221032
comment on: http://stackoverflow.com/a/51627351
type: AnswerComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177159/discussion-between-emu-and-howard-geng).
score: 0
type: Comment

http://stackoverflow.com/comment/90000022
has text: If I use celery can I then easily integrate it with Heroku?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51515638

http://stackoverflow.com/comment/90121387
type: QuestionComment
comment on: http://stackoverflow.com/q/51578000
score: 0
type: Comment
has text: This is a prefix. I don't want them. only suffixes between dots. given `a.b.c` a suffix must end with `c`

http://stackoverflow.com/comment/90128469
comment on: http://stackoverflow.com/q/51581598
type: Comment
has text: @DanielRoseman An android tablet and an android phone. They are on the same network. The local address is my local address as presented when using `ipconfig`, and yes, I'm certain it is the correct address. I can access the website from my local computer even using the local address and not via `localhost`. (See edit)
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90174898
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51599488
has text: How did you install Tensorflow?
score: 0

http://stackoverflow.com/comment/90051829
score: 1
comment on: http://stackoverflow.com/a/51542020
type: AnswerComment
type: Comment
has text: @akashkarothiya the worst is when you think you have an answer for a question and then the pro's show up and totally crush it. Better to wait around noon (EST) when they take a rest :)

http://stackoverflow.com/comment/113390018
comment on: http://stackoverflow.com/a/51642525
has text: @timmey spyder's profile gives you the running time of all the functions that are called from the script. If you want further insights, you can measure the execution time of each line of your code using lineprofiler https://stackoverflow.com/questions/22328183/python-line-profiler-code-example
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/89977134
has text: I do have export SPARK_HOME="/usr/local/spark-2.3.1-bin-hadoop2.7" set up, still not working
score: 0
comment on: http://stackoverflow.com/q/51504076
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51548638
has comment: http://stackoverflow.com/comment/90068931
score: 3
has title: Click on a checkbox element using python and selenium
downvote count: 0
has answer: http://stackoverflow.com/a/51551273
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90065818
upvote count: 3
tagged with: selenium
answer count: 1
has body: I am trying to automate loading and configuring a web page. On this page I am trying to check the state of the checkbox and then click on a it if its unchecked. HTML code for the page: 2.4 GHz network |Edit Network: Disabled Enabled Network is the field I am trying to click on. I am using selenium and python. I tried the following: browser.find_element_by_id("w-radio-enabled-text-24").send_keys("Enabled") browser.find_element_by_text("Network").click()
type: UnansweredQuestion
tagged with: ui-automation

http://stackoverflow.com/q/51613290
favorite count: 0
has title: Getting values from util:list using ElementTree in Python 2.7.15
has comment: http://stackoverflow.com/comment/90192312
upvote count: 2
tagged with: python-2.7
answer count: 1
has comment: http://stackoverflow.com/comment/90192451
tagged with: xml.etree
has comment: http://stackoverflow.com/comment/90192026
tagged with: python
tagged with: elementtree
tagged with: http://stackoverflow.com/tag/xml
score: 2
has body: I am using etree on python 2.7.15, and I stuck, I trying to parse XML File to get values from it.As you can see my code below: # -*- coding: utf-8 -*- import xml.etree.ElementTree as etree def XMLParse(filename): filename = filename tree = etree.parse(filename) beans = tree.findall('{http://www.speedframework.org/schema/beans}bean') for bean in beans: for property in bean: if "name" in property.attrib and "value" in property.attrib: print ("This one catches PROP1:" + property.attrib['name']) print property.attrib if "name" in property.attrib and not "value" in property.attrib: for util in property.iter(): for lists in util: for parameter in lists: if 'key' in parameter.attrib: print ("This one catches PROP3:" + parameter.attrib['key']) if 'bean' in parameter.attrib: print ("This one catches PROP4:" + parameter.attrib['bean']) if 'value' in parameter.attrib: print ("This one should catch PROP2:" + parameter.attrib['value']) print parameter.attrib filename = open('static/test1.xml') XMLParse(filename) And here's my xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.speedframework.org/schema/beans" xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:test="http://apache.org/hello_world_soap_http" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.speedframework.org/schema/util" xmlns:http="http://cxf.apache.org/transports/http/configuration" xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:context="http://www.speedframework.org/schema/context" xsi:schemaLocation=" http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://www.speedframework.org/schema/beans http://www.speedframework.org/schema/beans/speed-beans-2.0.xsd http://www.speedframework.org/schema/context http://www.speedframework.org/schema/context/speed-context-3.0.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://www.speedframework.org/schema/util http://www.speedframework.or…
has comment: http://stackoverflow.com/comment/90191882
downvote count: 0
has answer: http://stackoverflow.com/a/51613731
accepted answer: http://stackoverflow.com/a/51613731
has comment: http://stackoverflow.com/comment/90192295
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/51583270
tagged with: raster
favorite count: 0
has answer: http://stackoverflow.com/a/51597071
type: UnansweredQuestion
tagged with: python
has body: I have a raster image of shape 9000x10000 that has RGB bands. I use the below code to get the XY coordinates of all pixels in the image. But it is very slow. Is there a faster way to do it? filename='file.dat' inDs = gdal.Open(filename) outDs = gdal.Translate('{}.xyz'.format(filename), inDs, format='XYZ', creationOptions=["ADD_HEADER_LINE=YES"]) I want to save the XY coordinates and the pixel values in a dataframe.
tagged with: gis
type: Question
score: 0
tagged with: gdal
upvote count: 1
answer count: 1
downvote count: 1
has title: get pixel coordinates of all pixels in a raster image

http://stackoverflow.com/comment/90006384
type: AnswerComment
has text: @StevenG Got it! Glad I can help with that!
score: 0
comment on: http://stackoverflow.com/a/51518676
type: Comment

python-multiprocessing
tags question: http://stackoverflow.com/q/51504880
tags question: http://stackoverflow.com/q/51562221
tags question: http://stackoverflow.com/q/51526263
tags question: http://stackoverflow.com/q/51590766
tags question: http://stackoverflow.com/q/51553688
tags question: http://stackoverflow.com/q/51610295
type: Tag
tags question: http://stackoverflow.com/q/51508905
tags question: http://stackoverflow.com/q/51485212
tags question: http://stackoverflow.com/q/51550585
tag name: python-multiprocessing
tags question: http://stackoverflow.com/q/51485284

http://stackoverflow.com/q/51524381
type: UnansweredQuestion
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51524426
tagged with: python
tagged with: attributes
has title: "AttributeError" in Selenium Web Driver using Python
tagged with: selenium-webdriver
has body: I'm writing simple test for calculator on Python. I'm getting this error AttributeError: 'CalculatorTesting' object has no attribute 'driver'. I'm a newbie in python so please show me my mistake. Here is my code: def SetUp(self): self.driver = webdriver.Chrome('E:\chromedriver.exe') self.driver.get('http://qa-test.klika-tech.com/'); def test_01(self): driver = self.driver self.driver.find_element_by_xpath('/html/body/div[2]/ul[1]/li[5]').click() self.driver.find_element_by_xpath('/html/body/div[2]/ul[2]/li[5]').click() self.driver.find_element_by_xpath('/html/body/div[2]/ul[1]/li[5]').click() self.driver.find_element_by_xpath('/html/body/div[2]/ul[2]/li[7]').click() self.result = driver.find_element_by_xpath('//*[@id="display"]').text assert self.result is "10" def ShutDown(self): self.driver.quit() all xpaths are correct.

http://stackoverflow.com/comment/90238321
type: Comment
type: QuestionComment
has text: screenshot1 was wrong, I just edited it. What I get is actually "localhost didn't send any data"
score: 0
comment on: http://stackoverflow.com/q/51636721

http://stackoverflow.com/comment/90123763
type: Comment
comment on: http://stackoverflow.com/a/51573867
has text: @Oxymoronica : It's not a good practice to use xpath which is generated by FireBug/ firePath . As a beginner you might prefer that , But you should know how to write our own css selector or xpath.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90025569
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51527917
type: Comment
has text: If I try to register "C:\Program Files (x86)\Vector CANoe 8.2\Exec32\CANoe32.exe" . It says registration failed.

http://stackoverflow.com/comment/90077209
score: 0
comment on: http://stackoverflow.com/q/51544483
type: Comment
type: QuestionComment
has text: @AzatIbrakov I use dict {pattern: string} as config in my application. In some cases I have to add some patterns to initial config but if I just update config, new version will be using to the next config reload, so I want to create new variable with copy of initial config. Now I solved it with creating variable on config load step. But I'm still intersting in causes of this issue

http://stackoverflow.com/comment/90194934
has text: @MadPhysicist but ctrl-r is not available (my favourite trick of the gnu readline library)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51614675

http://stackoverflow.com/q/51614097
score: 1
upvote count: 1
has title: pyinstaller for gui that runs other python scripts
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/90194311
has comment: http://stackoverflow.com/comment/90193531
favorite count: 0
type: UnansweredQuestion
tagged with: pyinstaller
tagged with: python
has body: I created a GUI in python which runs some other python scripts (4 separate files). When I used pyinstaller for the gui to convert it to an executable, it could not run the other python scripts. I read somewhere that I must include them in the spec file but i am not sure how. Any help?
answer count: 0

http://stackoverflow.com/q/51596354
has comment: http://stackoverflow.com/comment/90158752
has answer: http://stackoverflow.com/a/55383655
has comment: http://stackoverflow.com/comment/90158703
favorite count: 0
has answer: http://stackoverflow.com/a/55141288
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90159018
tagged with: django
has comment: http://stackoverflow.com/comment/90159261
tagged with: python
has answer: http://stackoverflow.com/a/54546692
has title: KeyError in main while making project using django
has comment: http://stackoverflow.com/comment/95894103
has answer: http://stackoverflow.com/a/55576062
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/69794337
type: Question
has body: This is my code: import requests from django.shortcuts import render from .models import City def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&amp;units=imperial&amp;appid=bd5e378503939ddaee76f12ad7a97608' city = 'Jaipur' cities = City.objects.all() weather_data = [] for city in cities: r = requests.get(url.format(city)).json() city_weather = { 'city' : city.name, 'temperature' : r['main']['temp'], 'description' : r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } weather_data.append(city_weather) context = {'weather_data': city_weather} return render(request, 'weather/weather.html', context) I'm getting the error like this: KeyError at / 'main' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.6 Exception Type: KeyError Exception Value: 'main' Exception Location: C:\Users\HP\p\the_waether\weather\views.py in index, line 18 Python Executable: C:\Users\HP\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.5 What could be the problem?
has answer: http://stackoverflow.com/a/60205934
downvote count: 0
answer count: 6

http://stackoverflow.com/comment/90188122
type: QuestionComment
comment on: http://stackoverflow.com/q/51610959
has text: I tried that as well, (since I know `nan` and `infinite` are special float values). But that didn't work either.
score: 0
type: Comment

http://stackoverflow.com/q/51636061
score: 0
linked to: http://stackoverflow.com/q/6269765
has answer: http://stackoverflow.com/a/51636308
type: UnansweredQuestion
tagged with: python
has title: Python - Getting 3 random texts from a website
has comment: http://stackoverflow.com/comment/90236506
has body: I want to get 3 random texts with python from this website: http://mertatilgan.tk/dork.txt I tried this : import urllib2 for line in urllib2.urlopen("http://mertatilgan.tk/dork.txt"): print line while(True):pass It worked but it's getting an only first text from the website. But I need 3 random texts. (Sorry for my bad English.)
has answer: http://stackoverflow.com/a/51636240
has comment: http://stackoverflow.com/comment/90236655
has comment: http://stackoverflow.com/comment/90236798
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90236727

http://stackoverflow.com/comment/90206653
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51620139
has text: I find it odd you can change your PATH by can't point to Python3's version of pip lol. Alternatively, you could just point to python3's pip. By default on linux I forget where the heck it is b/c I am currently on a windows box. My Python3's pip on windows is located at `C:\Program Files\Python36\Scripts\pip.exe`

http://stackoverflow.com/comment/90170046
type: Comment
has text: Nowhere in your original data the word 'Doctor' or 'Footprint' appear, so it seems you didn't provide the data you are actually using. Please ensure your example is self-contained and reproduces the problematic behavior.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51601803

http://stackoverflow.com/comment/90051652
comment on: http://stackoverflow.com/q/51540486
score: 0
type: Comment
has text: Multiple calls of what? Parent constructors? Yes, but it's often uglier than explicitly calling each constructor individually. It depends on the classes you're inheriting from. You may find [this answer](https://stackoverflow.com/a/50465583/1222951) I wrote useful.
type: QuestionComment

http://stackoverflow.com/comment/90195415
score: 0
has text: @Daphne glad to be of help! I made it into an answer, so your question can be officially answered ;)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51520031

http://stackoverflow.com/comment/90097173
type: Comment
comment on: http://stackoverflow.com/q/51562377
type: QuestionComment
score: 1
has text: No, just run the line from the terminal, then try installing `awsebcli` again.

http://stackoverflow.com/q/51616225
answer count: 1
favorite count: 0
score: 0
upvote count: 1
has title: How to use __getitem__ to return objects in an object tree?
downvote count: 1
has body: I have a named tuple that I loaded from a json with open(self._json_path) as data_file: self._dom = json.load(data_file, object_hook=lambda d: namedtuple('X', d.keys())(*d.values())) I access content of this object tree by referring self._dom.my_var.A If, however, optional attributes in the JSON are not set, I run into an exception trying to access them. So self._dom.my_var.B would not work in case B is not defined in the JSON file. For that I would like offer a save way to access nullable objects with __getitem__. If they are not defined, I return None. This piece of code does not work as it seems that self.dom.key looks up an attribute literally named "key" and will not run in an attribute error even there is a object within the object tree defined. def __getitem__(self, key): try: return self.dom.key except AttributeError: return None
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51665471
has comment: http://stackoverflow.com/comment/90198019
has comment: http://stackoverflow.com/comment/90200971
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51665471
type: Question
has comment: http://stackoverflow.com/comment/90198068

http://stackoverflow.com/q/51615972
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90227083
has comment: http://stackoverflow.com/comment/90227027
tagged with: tensorflow-serving
has answer: http://stackoverflow.com/a/51669577
type: Question
has comment: http://stackoverflow.com/comment/90225598
has title: Exported Keras classification model served by TF Server gives: Expects arg[0] to be float but string is provided
tagged with: keras
linked to: http://stackoverflow.com/q/51608408
has body: I have trained a classification model in Keras (latest version of Keras and TF as per this writing) which is similar in input and output as CIFAR10. To serve this model I export it to a classification model (see the type) using the following code: def keras_model_to_tf_serve(saved_keras_model, local_version_dir, type='classification', save_model_version=1): sess = tf.Session() K.set_session(sess) K.set_learning_phase(0) old_model = load_model(saved_keras_model) config = old_model.get_config() weights = old_model.get_weights() new_model = Sequential.from_config(config) new_model.set_weights(weights) classification_inputs = utils.build_tensor_info(new_model.input) classification_outputs_classes = utils.build_tensor_info(new_model.output) # The classification signature classification_signature = tf.saved_model.signature_def_utils.build_signature_def( inputs={signature_constants.CLASSIFY_INPUTS: classification_inputs}, outputs={ signature_constants.CLASSIFY_OUTPUT_CLASSES: classification_outputs_classes }, method_name=signature_constants.CLASSIFY_METHOD_NAME) #print(classification_signature) # The prediction signature tensor_info_x = utils.build_tensor_info(new_model.input) tensor_info_y = utils.build_tensor_info(new_model.output) prediction_signature = tf.saved_model.signature_def_utils.build_signature_def( inputs={'inputs': tensor_info_x}, outputs={'outputs': tensor_info_y}, method_name=signature_constants.PREDICT_METHOD_NAME) legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op') print(prediction_signature) save_model_dir = os.path.join(local_version_dir,str(save_model_version)) if os.path.exists(save_model_dir) and os.path.isdir(save_model_dir): shutil.rmtree(save_model_dir) builder = saved_model_builder.SavedModelBuilder(save_model_dir) with K.get_session() as sess: if type == 'classification': builder.add_meta_graph_and_variables( sess, [tag_constants.SERVING], signature_def_map={ signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: classifica…
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90300693
tagged with: python
accepted answer: http://stackoverflow.com/a/51669577

http://stackoverflow.com/q/51526076
has answer: http://stackoverflow.com/a/51527113
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has body: I currently have a Python Dictionary that looks something like this: OrderedDict([('2017-07-24', 149.7619), ('2017-07-25', 150.4019), ('2017-07-26', 151.1109), ... that I am converting to JSON like so: one_yr = json.dumps(priceDict) Currently I am adding values to the dictionary from an SQL query by looping through it like so: for i in query: date = i[0] close = i[1] priceDict[date] = close The problem is that this returns a JSON object, that i then have to convert to a JSON array. I am wondering if I can just convert my Python Dictionary to a JSON array directly? Thanks.
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51526200
has comment: http://stackoverflow.com/comment/90020901
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51526127
has title: Converting Python Dictionary to JSON Array
favorite count: 0

http://stackoverflow.com/q/51558901
has body: I'm working with Matplotlib in Python to plot two elements (one is a scatter and the other is an image made from a matrix) that corresponds to the reading of a text file with n lines. Each line contains 4 columns,the first three columns are coordinates of (x,y,z) points, and the fourth column is a binary variable not necessary for this plotting. At each 20 lines read, a skeleton is read, this skeleton being a group of 20 (x,y,z) points or joints, each joint made by the first three columns of each line. The text file contains hundreds of lines, and therefore, many skeletons. Then, the text file is made of a certain number of skeletons (number_of_lines/20 = total of skeletons), that generates a movement. Therefore, the text file represents a movement. An example of the text file content: 1.3200000e+002 8.0000000e+001 6.8100000e+002 1.0000000e+000 1.6900000e+002 8.1000000e+001 6.6500000e+002 1.0000000e+000 1.4800000e+002 7.5000000e+001 6.5000000e+002 0.0000000e+000 1.5100000e+002 9.8000000e+001 6.9800000e+002 0.0000000e+000 1.3200000e+002 1.2000000e+002 6.7400000e+002 1.0000000e+000 1.6100000e+002 1.2200000e+002 6.6200000e+002 8.1730800e-001 At each skeleton plotted, a distance matrix from each joint to all the other 19 joints is generated, and imgshow is used to transform the matrix in an image. Also, in the plotting of the skeletons, only two coordinates are taken, (x,y) to generate a 2D skeleton, so the third coordinate is ignored. I had to use scatter to plot the skeleton, since the joints are plotted first, and then the lines connecting the joints are plotted, in the second for loop of the code. The problem: I'm using grispdec to plot each skeleton, and imgshow to transform the distance matrix in an image. Those plots are inside a for loop, and I've adjusted their position separately, to "force" them to be shown side by side in the same canvas. As I've explained, there are many skeletons/matrix's image pairs in each text file, and I must associate a key press even…
tagged with: plot
type: Question
score: 1
tagged with: matplotlib
tagged with: canvas
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90085039
has comment: http://stackoverflow.com/comment/90166222
favorite count: 0
has title: Matplotlib and Python: connect Gridspect and Subplot elements to canvas
tagged with: python
accepted answer: http://stackoverflow.com/a/51559554
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51559554
upvote count: 1

http://stackoverflow.com/comment/90119379
score: 1
has text: `L = L.next` changes the local variable `L`, which is then discarded because you never do anything with it. Did you mean to `return L`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51576932

http://stackoverflow.com/comment/90263462
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51618251
has text: Thanks for your hint. Not yet. But as soon as I successfully create tensorboard results or try to implement some methods to overcome gradient vanishing, I'll inform you.
score: 0

http://stackoverflow.com/comment/89986675
type: QuestionComment
has text: What is the problem? The blog code does what you want.
score: 0
comment on: http://stackoverflow.com/q/51505464
type: Comment

http://stackoverflow.com/comment/90005540
comment on: http://stackoverflow.com/q/51497681
score: 0
type: Comment
type: QuestionComment
has text: For print(len(dataset.columns)), my result is 1 (I have 60,000 rows in my dataset). I edited my comment showing a part of my dataset (there are no white lines, I just don't know how to edit a dataset here). Thanks!

http://stackoverflow.com/comment/90228217
type: Comment
has text: @jezrael If I'm not wrong, that implies that whenever both columns belong to the same bin, it's always in the 0-30 range, which is true.
comment on: http://stackoverflow.com/a/51631883
type: AnswerComment
score: 0

http://stackoverflow.com/a/51605314
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90291907
has body: Create a list whose initial value is 1000 and has the rate and the Final Order: b = [1000]+list(zip(df.Adj_Price.shift(-1)/df.Adj_Price,df.Final_Order)) df['BACK']=list(itertools.accumulate(b,lambda x,y: round(y[0]*x) if y[1]=="Buy" else x))[:-1] df Time Adj_Price Final_Order Backtest BACK 0 0 7 NaN 1000 1000 1 1 6 NaN 1000 1000 2 2 5 Buy 1000 1000 3 3 7 Buy 1400 1400 4 4 8 Sell 1600 1600 5 5 6 Sell 1600 1600 6 6 4 Buy 1600 1600 7 7 5 Buy 2000 2000 8 8 7 Buy 2800 2800 9 9 9 Sell 3600 3600 10 10 7 Sell 3600 3600 11 11 7 Sell 3600 3600 12 12 6 Sell 3600 3600 Comparing the column created to the one already present, They are identical
score: 1
accepted answer of: http://stackoverflow.com/q/51604809
has comment: http://stackoverflow.com/comment/90291881
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51604809
downvote count: 0

http://stackoverflow.com/comment/90225622
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51630493
has text: Have you read through the python docs on different data structures? https://docs.python.org/3/library/stdtypes.html You would be better off using a more complex but flexible data structure, for example a list of dictionaries where each dictionary contains the buyer and price information.
score: 0

http://stackoverflow.com/a/51531681
downvote count: 0
answers question: http://stackoverflow.com/q/51530785
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/51530785
has body: I think need preprocessing first: path_csv = 'file.csv' with open(path_csv) as f: lines = f.readlines() #get list of all possible lins starting by beerId num = [i for i, l in enumerate(lines) if l.startswith("beerId" )] #if not found value return 0 else get first value of list subtracted by 1 num = 0 if len(num) == 0 else num[0] - 1 print (num) 8 df = pd.read_csv(path_csv, header=num) print (df) beerId Book 0 341027 Northern Light
type: AcceptedAnswer

http://stackoverflow.com/q/51543865
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90056777
accepted answer: http://stackoverflow.com/a/51575863
downvote count: 2
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90057694
score: -2
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90055892
type: Question
has body: I have my custom function in python3 as follows: myFunction(A, x) """ Args: A (list) x (float) Returns: Y: numpy array of floats [y1,y2,...,y(len(A))] """ return Y What I want to do is to make a plot for some chosen constant list A, where the X axis is the input argument x (ranging between some values, say 0,10) and on the Y axis are the floats in the output array (so multiple curves, in different colors) I was thinking of doing something like this import matplotlib.pyplot as plt A = [5,10,15,20] x = numpy.linspace(0,10,1000) #1000 numbers between 0 and 10 plt.plot(x,myFunction(A, x)) But I'm getting the error TypeError: only size-1 arrays can be converted to Python scalars Thanks
upvote count: 0
has title: Plotting a custom function that returns an array of floats
answer count: 1
has comment: http://stackoverflow.com/comment/90055664
has comment: http://stackoverflow.com/comment/90056770
has answer: http://stackoverflow.com/a/51575863
has comment: http://stackoverflow.com/comment/90061266

http://stackoverflow.com/q/51566109
accepted answer: http://stackoverflow.com/a/51687823
score: 1
type: Question
downvote count: 0
favorite count: 0
tagged with: pandas
has title: Pandas - how to change cell according to next 10 cell's average
answer count: 1
has body: I have a dataset that I am trying to clean up. The data is all numeric. Basically, if there is a cell that is below 0 or above 100 i want to set it to NaN. I solved this with this code: for col in df: df.loc[df[col] &lt; 0, col] = numpy.NaN df.loc[df[col] &gt; 100, col] = numpy.NaN For values above 0 but below 20 i need to check the 10 cells above and below it. If the value is more than 20 different than the average of either the 10 cells in the same column above or below then it should also be set to numpy.NaN. I am not sure how to go about this one quite yet, after reading the documentation i know that i can simply pass in a function into the df.loc[] that returns a boolean list. However, I am not sure how to access the the passed in value's index to check for the 10 values above and below. I think it could look like something like this, but i am not even sure if this would properly produce a boolean list the way pd.df.loc[] wants it. def myFunc(value): #access index and create avgs for both tenBefore and tenAfter if abs(tenBeforeAvg - value) &gt; 20 or abs(tenAfterAvg - value) &gt; 20: return False else: return True for col in df: df.loc[df[col] &lt; 0, col] = numpy.NaN df.loc[df[col] &gt; 100, col] = numpy.NaN df.loc[myFunc(df[col]), col] = numpy.NaN Thanks ahead.
has answer: http://stackoverflow.com/a/51687823
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51568075
linked to: http://stackoverflow.com/q/9733638
tagged with: python
has comment: http://stackoverflow.com/comment/90104454
duplicate of: http://stackoverflow.com/q/9733638
has comment: http://stackoverflow.com/comment/90102653
type: UnansweredQuestion
tagged with: python-requests
has title: Request POST JSON data in Python
has body: I want to make POST data with requests in Python. This is the data, actually, I grab from Burp Suite (intercept HTTP request). sessionid=xxxsesi&amp;serverid=1&amp;partner=xxxpartner&amp;tradeoffermessage=&amp;json_tra deoffer={"newversion":true,"version":3,"me":{"assets": [{"appid":0,"contextid":"2","amount":1,"assetid":"xxxasset"}],"currency": [],"ready":false},"them":{"assets":[],"currency": [],"ready":"false"}}&amp;captcha=&amp;trade_offer_create_params= {"trade_offer_access_token":"xxxtoken"} But if I try to write in requests POST Python, it always fails. data = { "sessionid": "xxxsession", "serverid": 1, "partner":"xxxpartner", "tradeoffermessage": "", "json_tradeoffer": {"newversion":True,"version":3,"me":{"assets":[{"appid":440,"contextid":"2","amount":1,"assetid":"xxxasset"}],"currency":[],"ready":False},"them":{"assets":[],"currency":[],"ready":False}}, "captcha": "", "trade_offer_create_params": {"trade_offer_access_token":"xxxtoken"} } Can someone help me? Sorry for my bad English.
type: Question
score: 0
has answer: http://stackoverflow.com/a/51569166
answer count: 1

http://stackoverflow.com/a/51527304
upvote count: 9
answers question: http://stackoverflow.com/q/51527148
accepted answer of: http://stackoverflow.com/q/51527148
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 9
has body: PIP follows the PEP 425 Use recommendations; this stipulates how a binary distribution wheel is selected. Specifically, pip install will only consider compatible wheels. A wheel compatible with a different platform is not going to be downloaded. If there are no compatible wheels, but there is a source distribution, then that source distribution is downloaded and compiled locally. If there are no compatible wheels, and no source distribution, installation fails. Wheels can also be built for pure python projects, at which point they are no longer platform specific; these are called universal wheels. If a project uses optional binary components they can choose to produce both platform-specific wheels (including the compiled binary components specific to a Python ABI version and platform), and a universal wheel with the optional compiled components excluded. An installer can then select the universal version if no compatible binary version is available for the current platform. This is not all that common however, as a universal wheel would be preferred over a source distribution!

http://stackoverflow.com/q/51541338
tagged with: pandas
tagged with: python
upvote count: 2
has answer: http://stackoverflow.com/a/51541409
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51541367
has answer: http://stackoverflow.com/a/51541476
type: Question
downvote count: 0
possible better answer: http://stackoverflow.com/a/51541367
has title: Appending columns to a column using pandas
accepted answer: http://stackoverflow.com/a/51541409
favorite count: 0
has body: I have a dataset with the following structure, with varying sizes.: A B C D E F G H I J 1 8 7 1 3 4 7 1 5 9 8 9 1 4 7 4 5 2 1 2 8 9 7 7 4 2 9 7 1 0 What I want to do is append all columns to the first column and achieve a result like this: A 1 8 8 8 9 9 7 1 7 1 7 ... My code so far: import pandas as pd df = pd.read_csv("data.csv", header=None, delimiter=";") for column in df: df.append(column) print(df) I figured it should work by looping over all columns and using .append to append them to the first column. Any help is appreciated
answer count: 3

http://stackoverflow.com/q/51501402
type: AnsweredQuestion
upvote count: 0
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/51501437
has body: I have the following list of dictionaries: d = [{'Sport': 'MLB', 'Position': 'SP', 'Age': '25'}, {'Sport': 'NBA', 'Position': 'PG', 'Age': '28'}] I have another list that i would like to append to the above by using a for loop: c = [{'2015 Salary' : '25'}, {'2015 Salary': '35'}, {'2016 Salary' : '30'}, {'2016 Salary' : '40'}] I would like the final output to be e = [{'Sport': 'MLB', 'Position': 'SP', 'Age': '25', '2015 Salary': '25', '2016 Salary': '30'}, {'Sport': 'NBA', 'Position': 'PG', 'Age': '28', '2015 Salary': '35', '2016 Salary': '40'}}] The positions would always be the same thats why i was going to use a for loop.
duplicate of: http://stackoverflow.com/q/38987
has answer: http://stackoverflow.com/a/51501749
possible better answer: http://stackoverflow.com/a/51501437
downvote count: 3
accepted answer: http://stackoverflow.com/a/51501625
has title: use for loop to add elements to an existing dictionary in a list
tagged with: python
answer count: 4
favorite count: 0
linked to: http://stackoverflow.com/q/38987
has answer: http://stackoverflow.com/a/51501625
score: -3
has answer: http://stackoverflow.com/a/51501832

http://stackoverflow.com/q/51583236
has body: I've done simple Hangman game using PyQT4. But i have trouble with creating restart() method. I tried: class Ui_MainWindow(QtGui.QMainWindow): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(1188, 696) MainWindow.setStyleSheet(_fromUtf8("background-color: black;")) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) self.buttons = [] self.setUpKeyboard() MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1188, 25)) self.menubar.setObjectName(_fromUtf8("menubar")) MainWindow.setMenuBar(self.menubar) MainWindow.setStatusBar(self.statusbar) self.pic = QtGui.QLabel(self.mainwindow) self.pic.setPixmap(QtGui.QPixmap(os.getcwd() + "/img/s0.jpg")) self.pic.setGeometry(50, 150, 450, 280) self.pic.setObjectName(_fromUtf8("pic")) .... def restartGame(self): self.wordLabel.setText(" ") for i in range(26): self.buttons[i].setParent(None) self.counterLabel.setParent(None) self.keyWordHidden = "" self.keyWord = "" self.pic.setParent(None) self.setupUi(self.centralwidget) In other words im deleting every object created. Somehow i get output: MainWindow.setCentralWidget(self.centralwidget) AttributeError: 'QWidget' object has no attribute 'setCentralWidget' I'm running out of ideas what i need to pass as argument when i want call my setUpUi() for the second time... Got another question. My restart works almost fine. But i got another problem. The pixmap that contains graphic element (hanging device building up elements one by one - 10 jpg files like img1, img2...). For the first gameplay it works fine. After 9 mistakes the whole UI should be re-build... But then the pixmap doesn't show up... I tried to remove self.pic.setParent(None) and just again switching the "img10.jpg" for "img1.jpg". But this …
score: 0
has answer: http://stackoverflow.com/a/51583660
tagged with: restart
answer count: 1
tagged with: python
has title: Game restart PyQT4 Python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51583660
type: Question
has comment: http://stackoverflow.com/comment/90132579
tagged with: pyqt4

http://stackoverflow.com/comment/90160121
comment on: http://stackoverflow.com/a/51595426
type: AnswerComment
score: 0
type: Comment
has text: Thanks for the response. Now I know to keep searching. Do you have any suggestions on how to connect these calls back to their source within my application code? The generic nature of the stack traces leaves me in a guess-and-check debugging state.

http://stackoverflow.com/comment/90061456
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51546742
score: 0
has text: You could make a `O(nlogn)` solution easily if you sorted both strings then checked for equality at each index

http://stackoverflow.com/q/51516684
answer count: 3
has answer: http://stackoverflow.com/a/51516843
downvote count: 1
tagged with: python
has body: I have written following code: def contalpha(n): num = 65 for i in range(0, n): for j in range(0, i+1): ch = chr(num) print(ch, end=" ") num = num +1 print("\r") n = 7 contalpha(n) The output is: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ but what I want is: A B C D E A B C D A B C A B A How can I make it?
type: UnansweredQuestion
has title: print reverse pattern of alphabets using functions in python
has answer: http://stackoverflow.com/a/51516856
has answer: http://stackoverflow.com/a/51516845
type: Question
upvote count: 1
favorite count: 0
score: 0

merge
tags question: http://stackoverflow.com/q/51587670
tags question: http://stackoverflow.com/q/51483322
tags question: http://stackoverflow.com/q/51499723
tags question: http://stackoverflow.com/q/51588610
tags question: http://stackoverflow.com/q/51504078
tags question: http://stackoverflow.com/q/51483473
tags question: http://stackoverflow.com/q/51577938
tags question: http://stackoverflow.com/q/51625105
type: Tag
tags question: http://stackoverflow.com/q/51587685
tags question: http://stackoverflow.com/q/51549631
tags question: http://stackoverflow.com/q/51510818
tags question: http://stackoverflow.com/q/51520775
tag name: merge
tags question: http://stackoverflow.com/q/51550255
tags question: http://stackoverflow.com/q/51511881
tags question: http://stackoverflow.com/q/51581671
tags question: http://stackoverflow.com/q/51558432
tags question: http://stackoverflow.com/q/51507975

http://stackoverflow.com/comment/90209691
comment on: http://stackoverflow.com/q/51621955
type: Comment
type: QuestionComment
has text: disk full/failure maybe ? try another disk?
score: 0

http://stackoverflow.com/comment/89973559
has text: See [this](http://www.mathwords.com/p/permutation_formula.htm)
score: 0
comment on: http://stackoverflow.com/q/51502511
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51561937
tagged with: python
has comment: http://stackoverflow.com/comment/90091863
has comment: http://stackoverflow.com/comment/90091142
has comment: http://stackoverflow.com/comment/90090830
has comment: http://stackoverflow.com/comment/90091648
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/90090921
has comment: http://stackoverflow.com/comment/90090767
has comment: http://stackoverflow.com/comment/90090737
type: Question
score: -2
has title: Iteratively increase column by percent in other column in pandas
upvote count: 0
has body: I have a DataFrame like the one below. I want to iteratively increase val by pct_change for the appropriate group. For example, for group==1, var would first remain 1.2, then be 1.2+0.1*1.2=1.32, then 1.32+0.2*1.32=1.584. How can I do this without a loop? import pandas as pd df = pd.DataFrame({ 'var': [1.2, 1.2, 1.2, 1.2, 1.2, 1.2], 'group': [1, 2, 1, 2, 1, 2], 'pct_change': [0.15, 0.21, 0.1, 0.2, 0.2, 0.1] }) df group pct_change var 0 1 0.15 1 1 2 0.21 1 2 1 0.10 1 3 2 0.20 1 4 1 0.20 1 5 2 0.05 1 What I want to obtain: group pct_change var 0 1 0.15 1.200 1 2 0.21 1.200 2 1 0.10 1.320 3 2 0.20 1.440 4 1 0.20 1.584 5 2 0.05 1.512 UPDATE: The suggested solution by @Wen doesn't produce the correct answer: df.assign(pct_change=(df['pct_change']+df['var'])).groupby(['group'])['pct_change'].apply(lambda x : x.cumprod()/x.iloc[0]) 0 1.00000 1 1.00000 2 1.42000 3 1.64000 4 2.53328 5 2.56168
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90091876
has answer: http://stackoverflow.com/a/51562807
tagged with: pandas

http://stackoverflow.com/comment/89939700
type: Comment
type: QuestionComment
has text: What is `type(p)`? Also, please include the full traceback of the `AttributeError` so that we can identify the problem.
comment on: http://stackoverflow.com/q/51485024
score: 0

http://stackoverflow.com/q/51510635
tagged with: interpolation
has title: scipy ND Interpolating over NaNs
upvote count: 2
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51526380
score: 1
downvote count: 1
tagged with: scipy
has body: I have been trouble working out how to use the scipy.interpolate functions (either LinearNDInterpolator, griddata or Preferably NearestNDInterpolator) There are some tutorials online but i am confused what form my data needs to be in. The online documentation for nearestND is terrible. The function asks for: x : (Npoints, Ndims) ndarray of floats Data point coordinates. y : (Npoints,) ndarray of float or complex Data point values. I have data in the form: lat,long,data,time held within an xarray dataset. There are some gaps in the data I would like to fill in. I don't understand how to tell the function my x points. i have tried (lat,long) as a tuple and np.meshgrid(lat,long) but can't seem to get it going. Any help on how i can pass my lat,long coordinates into the function? Bonus points for time coordinates as well to make the estimates more robust through the third dimension. Thanks!
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/51526380
has answer: http://stackoverflow.com/a/51511081
tagged with: python-xarray
answer count: 2
has comment: http://stackoverflow.com/comment/89990501
has comment: http://stackoverflow.com/comment/89990516
possible better answer: http://stackoverflow.com/a/51511081
favorite count: 0

http://stackoverflow.com/q/51543298
has comment: http://stackoverflow.com/comment/90054542
has body: So, here is what I'd like to do. Here is my code: def weapon(): '''A list of the available weapon''' print("Here is your weapon choices for today: ") print("1. Flail:\n Damage: 1,6 \n Heal: 1, 3") print("2. Dagger:\n Damage: 2, 4 \n Heal: 2, 3") print("3. Sword:\n Damage: 1, 7 \n Heal: 1, 2") print("4. Crossbow:\n Damage: 0, 10 \n Heal: 0, 0") print("5. Mace:\n Damage: 1, 8 \n Heal: 0, 0") print("6. Quarterstaff:\n Damage 3,10 \n Heal 0,5") # Covert to integer to select weapon: WEAPON = int(input("Choose your weapon: \n 1: Flail \n 2: Dagger," "\n 3: Sword," "\n 4: Crossbow, \n 5: Mace," "\n 6: Quarterstaff \n" "Press the corresponding number for your weapon:\n ")) I want to change the function to a dictionary or maybe a class so that this string format can work: print('You choice a,' '{WEAPON} with {DAMAGE} and' '{HEAL} capabilties'.format(WEAPON=weapon, DAMAGE=Damage, HEAL=Heal)) I'd also add a confirmation message and allow the user to choose another weapon. Edit Here is the full code from random import randint NAMES = ["Ryu", "Bruce Lee", "Jet Li", "Steven Segal", "Batman", "The Flash", "Chuck Norris", "Frieza", "Cell", "Wonder Woman", "Goku", "Vegeta"] NAMEINT = randint(0, 11) if NAMEINT == 0: FIGHTERNAME = NAMES[0] elif NAMEINT == 1: FIGHTERNAME = NAMES[1] elif NAMEINT == 2: FIGHTERNAME = NAMES[2] elif NAMEINT == 3: FIGHTERNAME = NAMES[3] elif NAMEINT == 4: FIGHTERNAME = NAMES[4] elif NAMEINT == 5: FIGHTERNAME = NAMES[5] elif NAMEINT == 6: FIGHTERNAME = NAMES[6] elif NAMEINT == 7: FIGHTERNAME = NAMES[7] elif NAMEINT == 8: FIGHTERNAME = NAMES[8] elif NAMEINT == 9: FIGHTERNAME = NAMES[9] elif NAMEINT == 10: FIGHTERNAME = NAMES[10] elif NAMEINT == 11: FIGHTERNAME = NAMES[11] # Intro Text NAME = input("Hello what is your name?\n") print("Hello", NAME, "Today you will be fighter", FIGHTERNAME) # Starting Health PLAYERHP = 10 ENEMYHP = 10 # Weapon Inventory def weapon(): '''A list of the available weapon''' print("Here is your weapon choices for today: ") print("1. …
accepted answer: http://stackoverflow.com/a/51552297
score: 0
has comment: http://stackoverflow.com/comment/90058763
has comment: http://stackoverflow.com/comment/90056263
answer count: 1
has comment: http://stackoverflow.com/comment/90060038
has comment: http://stackoverflow.com/comment/90056156
tagged with: python
has comment: http://stackoverflow.com/comment/90061430
tagged with: text-based
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90055846
has answer: http://stackoverflow.com/a/51552297
has title: I'm creating a text based fighter program with Python 3.6 (32-bit) and changing a function to a dictionary
type: Question

http://stackoverflow.com/comment/90337300
score: 0
type: AnswerComment
type: Comment
has text: What? That's not what you are doing. You are using two capturing groups and not just one.
comment on: http://stackoverflow.com/a/51636746

http://stackoverflow.com/comment/90164351
type: AnswerComment
comment on: http://stackoverflow.com/a/51599145
type: Comment
has text: @EnzoRomano Yes, instead of using `r.text`, use `r.json()` to automatically parse the JSON into a Python dictionary.
score: 0

http://stackoverflow.com/q/51627149
tagged with: javascript
has comment: http://stackoverflow.com/comment/90219134
has comment: http://stackoverflow.com/comment/90218739
has answer: http://stackoverflow.com/a/51627458
upvote count: 4
has title: Uncaught SyntaxError: Unexpected token & in javascript django app
answer count: 3
score: 3
accepted answer: http://stackoverflow.com/a/51627458
favorite count: 0
has answer: http://stackoverflow.com/a/63313714
has comment: http://stackoverflow.com/comment/90219068
tagged with: django
has answer: http://stackoverflow.com/a/51627298
has comment: http://stackoverflow.com/comment/90218773
tagged with: python
has comment: http://stackoverflow.com/comment/90218986
linked to: http://stackoverflow.com/q/18812317
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/63313714
has body: This is my function: function convert_strings() { var chart_labels = {{ chartlabels }}; var array_length = chart_labels.length; for (var i = 0; i &lt; array_length; i++) { chart_labels[i] = chart_labels[i].replace(/&amp;#039;/g, "'") } return chart_labels } This is my error: "Uncaught SyntaxError: Unexpected token &amp;" function convert_strings() { var chart_labels = [&amp;#39;CHENNAI LPG RO&amp;#39;, &amp;#39;KOCHI LPG RO&amp;#39;, &amp;#39;BANGALORE LPG RO&amp;#39;, &amp;#39;HUBLI LPG RO&amp;#39;, &amp;#39;MADURAI LPG RO&amp;#39;, &amp;#39;MANGLORE LPG RO&amp;#39;]; var array_length = chart_labels.length; for (var i = 0; i &lt; array_length; i++) { chart_labels[i] = chart_labels[i].replace(/&amp;#039;/g, "'") } return chart_labels } Please advice what to do :)
has comment: http://stackoverflow.com/comment/90218875
downvote count: 1
type: Question

http://stackoverflow.com/comment/90141090
type: Comment
type: QuestionComment
has text: Ah, I get you. No, the only way for a trigger to communicate with the outside directly is via `NEW`. Of course it can have side effects and store stuff in the database, like a temporary table. The question is who is the recipient of the information, since the environment for a trigger is a DML statement.
score: 1
comment on: http://stackoverflow.com/q/51568436

http://stackoverflow.com/comment/90156204
comment on: http://stackoverflow.com/q/51594977
score: 0
has text: "_I can't show any of the real data or most of the code for sensitivity reasons._" - the best approach is to produce a simplified scenario that produces the same error. You may even figure out what's going wrong while doing so.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/89954387
type: QuestionComment
has text: Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful.
comment on: http://stackoverflow.com/q/51492897
score: 0
type: Comment

http://stackoverflow.com/a/51510882
type: Answer
has comment: http://stackoverflow.com/comment/90010268
answers question: http://stackoverflow.com/q/51510081
has comment: http://stackoverflow.com/comment/90009177
has comment: http://stackoverflow.com/comment/90008824
accepted answer of: http://stackoverflow.com/q/51510081
score: 0
type: AcceptedAnswer
has body: If you're setting your defaultdict to int, you can only store an integer for each key in the dictionary. I'm not sure if you want to sum RT and LT, or generate separate counts for each. To combine RT and LT as a single value: sumarized = defaultdict(int) for Type,RT,LT,NAID,RecT in rows: sumarized[NAID, RecT] += RT + LT print(sumarized) output (formatted for easier reading): defaultdict(&lt;class 'int'&gt;, { ('NZ45', '2018-05-30 16:59:00'): 674, ('CR98', '2018-05-30 16:59:00'): 570, ('RU992', '2018-05-30 16:58:00'): 260 }) To keep the values separate, you'll need to add something to the keys to distinguish between the two: for T,RT,LT,NAID,RecT in data: sumarized[NAID, RecT, 'RT'] += RT sumarized[NAID, RecT, 'LT'] += LT print(sumarized) output (formatted for easier reading): defaultdict(&lt;class 'int'&gt;, { ('NZ45', '2018-05-30 16:59:00', 'RT'): 71, ('NZ45', '2018-05-30 16:59:00', 'LT'): 603, ('CR98', '2018-05-30 16:59:00', 'RT'): 90, ('CR98', '2018-05-30 16:59:00', 'LT'): 480, ('RU992', '2018-05-30 16:58:00', 'RT'): 80, ('RU992', '2018-05-30 16:58:00', 'LT'): 180 }) If you want some other type of data arrangement you can alter your defaultdict keys/value/set up accordingly.

http://stackoverflow.com/comment/90152891
has text: Hi, no problem. I tried a bit of numerical experiments, and it worked with "not too large" f(x). But when it comes to 10^5 etc, the integrand becomes like a delta function, which may be problematic for numerical quadrature (because of the too narrow width)... But anyway, some (pre)scaling of the problem may be helpful. (Otherwise, I guess a more neat approach (specific to the problem) may be necessary like the paper shown in the comments.)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51591986
type: AnswerComment

http://stackoverflow.com/comment/90089984
has text: Thanks for your input. Yes, I'd like to avoid to see all my 500 huge images to trap those that are not PIL compatible. But what's bothering me the most is that I tried to read the same image with GDAL and it works great, and I could convert each band to a numpy array...
score: 0
comment on: http://stackoverflow.com/q/51560984
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90346997
has text: @Programmer120 If that's the case just use a constant to save it, like `limit = jsondata["limit"]`. And then at the last, create a dictionary urself, put them inside by `mydatadict["result"] = datarALL`. Thats it. No magic method.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51628451
type: AnswerComment

http://stackoverflow.com/q/51543478
upvote count: 1
has title: Autocomplete filename in python script
type: Question
has comment: http://stackoverflow.com/comment/90056007
tagged with: autocomplete
score: 1
has comment: http://stackoverflow.com/comment/90054874
linked to: http://stackoverflow.com/q/5637124
has body: I have made a python script that asks the user to enter 2 or 3 filenames, which should be analysed. The filename insertion is done in the script (it is not passed as argument to argparse, because there are other choices that user has to make before that). Due to the company naming convention these filenames can be quite long and thus cumbersome to type. To help the user I am printing the contents of directory. For now I am using something like this: fname = raw_input("Insert phase 1 filename: ") (than I check the if file exists etc...) Is there a way to implement autocomplete for filenames inside the python script by writing custom input() function? Note that the script must run on different machines / OS and I can not ask users to install some non-standard python libraries. If there is no clean way to do it I might use less fancy solution of just printing a number before the filenames in the directory and than ask the user to insert just the number.
answer count: 1
downvote count: 0
tagged with: python-2.x
favorite count: 0
duplicate of: http://stackoverflow.com/q/5637124
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51543648
has comment: http://stackoverflow.com/comment/90055867
has comment: http://stackoverflow.com/comment/90055968

http://stackoverflow.com/comment/90137578
comment on: http://stackoverflow.com/a/51580556
score: 0
type: AnswerComment
has text: Thanks for your answer it helped a lot, although I am having trouble changing the background image. When I tried to implement your code into my own source it would only show me the background image and wouldn't show the buttons.
type: Comment

http://stackoverflow.com/comment/90263478
score: 0
has text: Okay @sid8491, implemented exactly and changed the details, getting one error saying "Invalid Syntax" `return 'Document data: {}'.format(doc.to_dict())` On that line, pointing towards the return statement. The bottom `if intentName` statement is still highlighting as "return out of function" for some reason. Strange, Thank you for your help so far.
type: Comment
comment on: http://stackoverflow.com/a/51627228
type: AnswerComment

http://stackoverflow.com/a/51632393
answers question: http://stackoverflow.com/q/51631866
has comment: http://stackoverflow.com/comment/90229307
score: 0
has body: Let's do this recursively ;) Base case 1: when the text is an empty string, return an empty string Base case 2: when the first letter of the text is a caret, search for the closing tag and return call to function with remaining text after closing tag. def remove_tags(text, tags=[]): if text == '': return text if text[0] == '<': closing_caret_pos = text.find('>') tag = text[0:closing_caret_pos+1] is_open_tag = '/' not in tag is_close_tag = not is_open_tag is_valid_tag = tag[1:-1].isalpha() or tag[2:-1].isalpha() if is_valid_tag and is_open_tag: tags.append(tag) return remove_tags(text[1:], tags) if is_valid_tag and is_close_tag: tags.pop() return remove_tags(text[len(tag):], tags) if len(tags) != 0: # when an open tag exists keeping looking return remove_tags(text[1:], tags) return text[0] + remove_tags(text[1:], tags) Test runs: text = "I am happy with This is a Heading This is a paragraph. 3333 This is a Heading This is a paragraph. your code" print(remove_tags(text)) > I am happy with 3333 your code text = "x<=1 cookies " print(remove_tags(text)) > x<=1 text = "I am <a happy with lal" print(remove_tags(text)) > I am <a happy with lal
type: Answer
has comment: http://stackoverflow.com/comment/90229040
has comment: http://stackoverflow.com/comment/90229197

http://stackoverflow.com/comment/90145416
comment on: http://stackoverflow.com/q/51554811
score: 0
has text: No that's an error , I am asking about alert screen shot
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51569080
score: 0
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51569384
accepted answer: http://stackoverflow.com/a/51569384
has comment: http://stackoverflow.com/comment/90104520
downvote count: 1
possible better answer: http://stackoverflow.com/a/51569209
favorite count: 0
tagged with: input
tagged with: python
tagged with: dictionary
tagged with: indexing
type: AnsweredQuestion
has title: how to pass the specific column of dictionary as input of other function in python
type: Question
has body: Im using a function to parse an excel in python without using libraries but importing an individual script accessing the excel data. my program can read the excel data and with following structure gets the values. I need to access specific columns of the listExcelvalues as follow and pay it to the input of other function : actual code ive converted the list into the dict but the problem is I dont want to pass all the dictionary as input of other function but instead specific columns. Any ideas how to do so ?
has answer: http://stackoverflow.com/a/51569209

visual-studio-code
tags question: http://stackoverflow.com/q/51592682
tags question: http://stackoverflow.com/q/51573941
tags question: http://stackoverflow.com/q/51629696
tags question: http://stackoverflow.com/q/51619195
tags question: http://stackoverflow.com/q/51529973
tags question: http://stackoverflow.com/q/51602100
tags question: http://stackoverflow.com/q/51583346
tags question: http://stackoverflow.com/q/51578239
tag name: visual-studio-code
tags question: http://stackoverflow.com/q/51619868
type: Tag
tags question: http://stackoverflow.com/q/51591245
tags question: http://stackoverflow.com/q/51534758
tags question: http://stackoverflow.com/q/51550260
tags question: http://stackoverflow.com/q/51540391

http://stackoverflow.com/comment/90215532
comment on: http://stackoverflow.com/a/51625356
type: AnswerComment
score: 0
type: Comment
has text: I did that. But had to terminate the session and switch it bak again to see the changes. Thanks a lot.

http://stackoverflow.com/comment/89951845
type: Comment
score: 3
type: QuestionComment
comment on: http://stackoverflow.com/q/51491617
has text: How are you defining "similar"? Are these references similar? If not, can you give examples that are, and explain why they count as similar?

ode
tags question: http://stackoverflow.com/q/51575544
type: Tag
tag name: ode

scatter
tags question: http://stackoverflow.com/q/51529879
tag name: scatter
type: Tag

http://stackoverflow.com/comment/90107988
comment on: http://stackoverflow.com/a/51558391
type: AnswerComment
score: 0
type: Comment
has text: @Jack you may use `abs(a+b)/2.0 * 0.10` for 10% or `abs(a+b)/2.0 * 0.54` for 54% if that's simpler.

http://stackoverflow.com/comment/90051382
type: Comment
has text: Any advice for modifying the library directories used for linking in the later stages of the setup? I'm running into a similar issue where it's ensuring `/usr/lib` under the `x86_64-sdk` path is being added (since that's where `python3` is located), even when that path is not being specified in the `--library-dirs` argument.
comment on: http://stackoverflow.com/a/51526536
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90152093
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51592397
has text: @PaulNovac - see the edit. Anyway, it is usually a better practice to save the file under a new name when it changed.
type: AnswerComment

http://stackoverflow.com/comment/90154373
has text: It doesn't work. Do I have to format fdate and tdate in YYYY-mm-dd format?
type: Comment
comment on: http://stackoverflow.com/a/51594126
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90104871
has text: It looks like you already have 3 suspects that may be breaking your program. Have you tried removing all of them? Did it still break? Then there's something else to be looked into. If it works, try adding those three options one by one and see when it starts breaking again. That way, you will either understand the problem and fix it yourself or at least be able to edit our some irrelevant code from your question
score: 1
comment on: http://stackoverflow.com/q/51569131
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90242371
comment on: http://stackoverflow.com/a/51638749
type: AnswerComment
score: 0
has text: Used that command. There was a version sitting in something like Python > 3.6 > Site-Packages. I'm ripping everything out (that didn't come with Mac) and reinstalling everything that's required for this project. This is ridiculous. I've never had this issue with Flask, Python, passlib, or whatever before.
type: Comment

http://stackoverflow.com/comment/90030214
comment on: http://stackoverflow.com/a/51530848
type: Comment
score: 1
type: AnswerComment
has text: @pianoman102 Probably you should read more about packages and modules in python. Check this article as start: https://realpython.com/python-modules-packages/

http://stackoverflow.com/a/51638338
accepted answer of: http://stackoverflow.com/q/51613990
answers question: http://stackoverflow.com/q/51613990
type: AcceptedAnswer
has body: This would work: const crypto = require('crypto') function validatePassword(secret, format) { let parts = format.split('$') return parts[4] == crypto.pbkdf2Sync(secret, Buffer.from(parts[3].replace(/\./g, '+') + '='.repeat(parts[3].length % 3), 'base64'), +parts[2], 32, parts[1].split('-')[1]).toString('base64').replace(/=/g, '').replace(/\+/g, '.') }
has comment: http://stackoverflow.com/comment/139523362
type: Answer
score: 3
downvote count: 1
upvote count: 4

http://stackoverflow.com/a/51507634
upvote count: 1
has body: It's reading F etc. as variable names. To fix this: Rewrite them as "F" etc. Fix your comparisons; or is used for multiple comparisons and can't be used how you're using it. Consider using user_input.casefold() == "f" instead.
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51507592

http://stackoverflow.com/comment/90143505
comment on: http://stackoverflow.com/a/51587327
has text: @nicosalto The title is what is used to filter questions, and in your case screams Threads, on the other hand I change the tags, you can see it in the edition. :)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/51576728
has comment: http://stackoverflow.com/comment/90120362
answers question: http://stackoverflow.com/q/51570072
has body: Your problem is that on your Hotel model you have hotel_main_img and it's defined to be models.FileField(upload_to='hotel_images/'). So not only is it not anImageField, it's aFileField`...but also it's not a list of images...it's a single file upload that is being rendered for your form and the same for the automatic form handling You are going to need to create a formset containing inline forms for your related Hotel_image object. Then you can allow multiple images to be uploaded.
has comment: http://stackoverflow.com/comment/90120285
has comment: http://stackoverflow.com/comment/90120637
score: 0
has comment: http://stackoverflow.com/comment/90120346
type: Answer

http://stackoverflow.com/a/51639358
type: AcceptedAnswer
score: 79
has comment: http://stackoverflow.com/comment/109060714
type: Answer
accepted answer of: http://stackoverflow.com/q/51639332
answers question: http://stackoverflow.com/q/51639332
has comment: http://stackoverflow.com/comment/109057430
has body: You are looking at an annotation for a variable. The hint is moved to the __annotations__ mapping: &gt;&gt;&gt; char: str &gt;&gt;&gt; __annotations__ {'char': &lt;class 'str'&gt;} Variable annotations are there to support third-party tooling, such as type checkers; the syntax is new in Python 3.6. See PEP 526 -- Syntax for Variable Annotations, and What's new in Python 3.6: Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in the __annotations__ attribute of a class or module.
upvote count: 79
downvote count: 0
has comment: http://stackoverflow.com/comment/90243233
has comment: http://stackoverflow.com/comment/90243185

http://stackoverflow.com/q/51510870
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/89990554
upvote count: 4
has comment: http://stackoverflow.com/comment/89990558
has body: Python 3.6 I have a simple Python web server that, when it receives a POST request, spawns a netcat process to listen on a port. Seems to work OK except that a zombie is left following the spawn. (Server code below) I send a POST request to the server like so: curl -X POST -H "Content-Type: text/plain" --data "example data" localhost:8000 After that I do a ps ax to see the processes running and the netcat process is there, the web server is there, AND a zombie is there. 6873 pts/0 S+ 0:00 python3 nc_server.py 6876 ? Zs 0:00 [python3] &lt;defunct&gt; 6877 ? S 0:00 nc -l 54927 Why? How can I avoid the zombie? from http.server import HTTPServer, BaseHTTPRequestHandler import socket import os import io host = '0.0.0.0' port = 8000 def find_free_port(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(('', 0)) return s.getsockname()[1] def spawn_netcat(port): command = "/bin/nc" params = f"nc -l {port}" spawnDaemon(command, params.split()) def spawnDaemon(path_to_executable, params): # Do first fork pid = os.fork() if (pid != 0): return # Decouple from parent environment os.chdir("/opt") os.setsid() os.umask(0) # Do second fork pid = os.fork() if (pid != 0): os._exit(0) # exec this process into netcat..... os.execv(path_to_executable, params) class Server(BaseHTTPRequestHandler): def do_POST(self): netcat_listen_port = find_free_port() spawn_netcat(netcat_listen_port) self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() response = io.BytesIO() response.write(str(netcat_listen_port).encode()) self.wfile.write(response.getvalue()) if __name__ == "__main__": httpd = HTTPServer((host, port), Server) httpd.serve_forever()
has comment: http://stackoverflow.com/comment/89990570
has comment: http://stackoverflow.com/comment/89990359
type: AnsweredQuestion
downvote count: 0
has title: How to double fork from a Python web server without leaving a zombie process?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51517165
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/51517165
has comment: http://stackoverflow.com/comment/89990537
has comment: http://stackoverflow.com/comment/89990578
answer count: 1
has comment: http://stackoverflow.com/comment/89990331
has comment: http://stackoverflow.com/comment/112478419
has comment: http://stackoverflow.com/comment/89991371

http://stackoverflow.com/comment/90095159
has text: Got it. That means your frame is still RGB, not grayscale (for a grayscale 1080p image the shape should be (1080, 1920)). Can you try `frame = skimage.color.rgb2gray(frame)` before the convolution? The OP (`frame = color.rgb2gray`) suggests you might be doing this step incorrectly.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51562341

http://stackoverflow.com/comment/90152561
type: Comment
type: AnswerComment
has text: thank you for your attempt to answer my question, the code is now updated.
comment on: http://stackoverflow.com/a/51591328
score: 0

http://stackoverflow.com/comment/90217429
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51626358
type: Comment
has text: @NityeshAgarwal - I think not.

http://stackoverflow.com/comment/90048722
comment on: http://stackoverflow.com/q/51540399
score: 0
has text: Not really, I need a list of unique names I have to use further down in my pipeline.
type: Comment
type: QuestionComment

cors
type: Tag
tag name: cors
tags question: http://stackoverflow.com/q/51575155

http://stackoverflow.com/q/51562500
tagged with: sharepoint
upvote count: 2
has body: I have a Python script that will upload a file to Sharepoint using Microsoft Graph but it gives me a 500 status code error when I try to upload the same file twice. Here is the code for the function that uploads the file: def upload_file(session,filename,driveid,folder): """Upload a file to Sharepoint. """ fname_only = os.path.basename(filename) # create the Graph endpoint to be used endpoint = f'drives/{driveid}/root:/{folder}/{fname_only}:/createUploadSession' start_response = session.put(api_endpoint(endpoint)) json_response = start_response.json() upload_url = json_response["uploadUrl"] # upload in chunks filesize = os.path.getsize(filename) with open(filename, 'rb') as fhandle: start_byte = 0 while True: file_content = fhandle.read(10*1024*1024) data_length = len(file_content) if data_length &lt;= 0: break end_byte = start_byte + data_length - 1 crange = "bytes "+str(start_byte)+"-"+str(end_byte)+"/"+str(filesize) print(crange) chunk_response = session.put(upload_url, headers={"Content-Length": str(data_length),"Content-Range": crange}, data=file_content) if not chunk_response.ok: print(f'&lt;Response [{chunk_response.status_code}]&gt;') pprint.pprint(chunk_response.json()) # show error message break start_byte = end_byte + 1 return chunk_response Here is the output for the first run: bytes 0-10485759/102815295 bytes 10485760-20971519/102815295 bytes 20971520-31457279/102815295 bytes 31457280-41943039/102815295 bytes 41943040-52428799/102815295 bytes 52428800-62914559/102815295 bytes 62914560-73400319/102815295 bytes 73400320-83886079/102815295 bytes 83886080-94371839/102815295 bytes 94371840-102815294/102815295 Here is the output for the second run: bytes 0-10485759/102815295 bytes 10485760-20971519/102815295 bytes 20971520-31457279/102815295 bytes 31457280-41943039/102815295 bytes 41943040-52428799/102815295 bytes 52428800-62914559/102815295 bytes 62914560-73400319/102815295 bytes 73400320-83886079/102815295 bytes 83886080-94371839/102815295 bytes 94371840-10…
has comment: http://stackoverflow.com/comment/90195539
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/57620236
type: UnansweredQuestion
tagged with: python
has title: How to overwrite a file uploading to SharePoint with Microsoft Graph
score: 2
downvote count: 0
tagged with: onedrive
tagged with: microsoft-graph-api
type: Question

http://stackoverflow.com/q/51570953
tagged with: string
tagged with: return-type
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90107947
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51571025
type: Question
has body: def token(t): running_cost = [] total_cost = 0 for y in t: running_cost.append(y) for k in range(len(running_cost)): total_cost += float(running_cost[k]) total_cost = '{:,.2f}' .format(total_cost) return total_cost When I run my code through the tester, this is what I get: Expected: 1.17 Actual: 1.17 Incorrect! (wrong value and/or wrong return type) I suppose the code does not want a string return type but the reason I have to string it is because the code requires that I return all my values with a floating point number to 2 decimal places whether it is a 0 or not.
score: 0
has title: Incorrect! (wrong value and/or wrong return type)
answer count: 1

http://stackoverflow.com/q/51577733
has comment: http://stackoverflow.com/comment/90121523
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51578166
upvote count: 0
answer count: 1
favorite count: 0
has title: How to edit the line appended into list multiple times?
tagged with: python
has comment: http://stackoverflow.com/comment/90121191
type: UnansweredQuestion
has body: Have a scenario where, a. Previously the list was having one value only, so it was a straight away adding the line like given below. s_array.append(' %s [%d:0] %s;'%(str(s_ud_in_cfg_array[i][1]), int(s_ud_l_var_temp[0]), str(s_ud_in_cfg_array[i][0]), )) b. Have a scenario where a list has multiple values like s_ud_l_var_tmp = ['32', '64', '16'] c. I wanted to add a line with the values from the array as given below into a list. s_array.append(' %s [%d:0][%d:0][%d:0] %s;'%(str(s_ud_in_cfg_array[i][1]), int(s_ud_l_var_temp[0]), int(s_ud_l_var_temp[1]), int(s_ud_l_var_temp[2]), str(s_ud_in_cfg_array[i][0]), )) c. But the catch here is the value in the s_ud_l_var_tmp can be keep varying and it won't be three all the times. UPDATE: a. Finally i got to two arrays as given below value of le_temp_list ['%s', '[%s-1:0]', '[%d:0]', '%s'] value of le_temp_list_val ['logic', '`ADR_WTH', 31, 'green'] Where array le_temp_list has the list of %d's and %s's for which to be replaced values are in le_temp_list_val. I wanted something like as given below, so that I can append the output of the below execution into an array. '%s [%s-1:0] [%d:0] %s'%(logic, `ADR_WTH, 31, green) So the final output should be like, logic [`ADR_WTH-1:0] [31:0] green i.e. expressions in le_temp_list is replaced by values in le_temp_list_val and represent the output.
downvote count: 2
type: Question
score: -2

http://stackoverflow.com/q/51628992
has comment: http://stackoverflow.com/comment/90222819
has title: Selecting range of rows based on whether they contain certain value for a specific number of rows
tagged with: pandas
tagged with: python
has body: I have a pandas dataframe where one of the column contain just 2 different values (around 20,000 rows): 0 and 100. They occur in continuous series. For example, if there is a 0, there will be at least 50 more zeroes after that, before changing to 100. I want to create a new column where it will output a 1 if the range of 0's in the above mentioned column is above a certain threshold (lets say 100). So if there are 100 0's continously occuring in the column, it will output a 1, else it will output a 0. How do I go about doing that? I tried pandas.rolling but that didn't work Sample: Input Output 0 1 0 1 0 1 0 1 0 1 In the above table, if there are 100 continuous 0, the output will be 1.
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90222610
has comment: http://stackoverflow.com/comment/90222753
downvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/90222304
type: Question
upvote count: 2
favorite count: 0

http://stackoverflow.com/comment/89963902
type: AnswerComment
comment on: http://stackoverflow.com/a/51497933
type: Comment
has text: @running.t - Yes, but it depends of version of pandas, answer was edited.
score: 0

http://stackoverflow.com/comment/90145157
type: Comment
type: QuestionComment
has text: Yes that would be enough.
comment on: http://stackoverflow.com/q/51587643
score: 0

http://stackoverflow.com/comment/90271621
has text: Could you please specify, what should I look exactly? Thanks.
type: Comment
comment on: http://stackoverflow.com/a/51652319
score: 0
type: AnswerComment

http://stackoverflow.com/q/51542543
has answer: http://stackoverflow.com/a/51542637
has body: I have a DF that has the following information: id email org senha server email_comp 1 jj @gmail.com 123 imap.gmail.com jj@gmail.com 2 bb @gmail.com 325 imap.gmail.com bb@gmail.com I need to read those records one by one to do the validation in the email, but I can not think of a way to do this loop for all information. At the moment I achieved the following: for nextServer in enumerate (imaplib.IMAP4_SSL(df['server'])): But it continues giving error, if it were to do with HardCode the process would be as follows: while go: mail = imaplib.IMAP4_SSL(server) mail.login(email_comp, senha)
type: Question
tagged with: for-loop
possible better answer: http://stackoverflow.com/a/51542637
accepted answer: http://stackoverflow.com/a/52101324
tagged with: imap
score: 0
answer count: 2
tagged with: validation
has answer: http://stackoverflow.com/a/52101324
tagged with: python
type: AnsweredQuestion
has title: access validation - Python

http://stackoverflow.com/a/56924316
upvote count: 6
score: 6
answers question: http://stackoverflow.com/q/51562067
has body: This problem happened to me and as the error was intermittent, I initially believed that it was some firewall or antivirus problem, but it was much simpler. I had a form that was being submitted twice when the SEND button was clicked. The button was set to type="submit" and a javascript code submitted this form when this button was clicked. I changed the button to type="button" and the problem was solved.
downvote count: 0
type: Answer

http://stackoverflow.com/q/51529840
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51530120
accepted answer: http://stackoverflow.com/a/51530115
tagged with: python
type: AnsweredQuestion
has body: I'm having problems (sort of) with combining duplicate columns. It seems to work on older versions of Pandas/Python (not sure what the culprit is here), but not on the latest version. I basically have a dataframe of mixed values with duplicate column names after a concat. The values are either going to be a int, string, or nan. All non-nan values are going to be the same for each duplicate column name, so in theory max() should do the trick. Say I have the Dataframe: col1 col1 col2 col2 col3 0 Foo nan nan Bar Baz 1 nan nan Bar Bar nan 2 0 nan 1 nan 1 My goal is to get col1 col2 col3 0 Foo Bar Baz 1 nan Bar nan 2 0 1 1 Doing this df.groupby(df.columns,axis=1).max() Does exactly what I want it to do on a older version of Pandas/Python, but does not work for the latest. This is what I'm getting on the latest version: col1 col2 col3 0 nan nan Baz 1 nan nan nan 2 0 1 1 Any ideas?
possible better answer: http://stackoverflow.com/a/51530120
score: 1
has comment: http://stackoverflow.com/comment/90028031
has title: Pandas combine duplicate columns that contain strings
upvote count: 1
has comment: http://stackoverflow.com/comment/90028023
type: Question
has comment: http://stackoverflow.com/comment/90027941
has answer: http://stackoverflow.com/a/51530050
has answer: http://stackoverflow.com/a/51530115

http://stackoverflow.com/comment/90025975
type: AnswerComment
score: 0
type: Comment
has text: @Tuft Yes, you should be able to run hundreds of programs (or the same program run hundreds of times in parallel) that all call `socket.create_connection(('localhost', 12345))`, and they'll all work (each one automatically getting a unique ports to connect from).
comment on: http://stackoverflow.com/a/51528059

http://stackoverflow.com/comment/132989499
type: Comment
comment on: http://stackoverflow.com/q/51497129
type: QuestionComment
score: 0
has text: Does this answer your question? [How can a name be "unbound" in Python? What code can cause an \`UnboundLocalError\`?](https://stackoverflow.com/questions/22101836/how-can-a-name-be-unbound-in-python-what-code-can-cause-an-unboundlocalerror)

http://stackoverflow.com/q/51579764
downvote count: 3
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90124918
has body: Please, tell me what do string 'sorted(args, key=len)[0] ? names = ['Bruce', 'Clark', 'Peter'] heroes = ['Batman', 'Superman', 'Spiderman'] def shortest_seq(*args): return range(len(sorted(args, key=len)[0])) g = ((names[i], heroes[i]) for i in shortest_seq(names, heroes)) for item in g: print(item)
has comment: http://stackoverflow.com/comment/90124838
linked to: http://stackoverflow.com/q/12791923
duplicate of: http://stackoverflow.com/q/12791923
accepted answer: http://stackoverflow.com/a/51579795
has title: What means stroke 'key = len'?
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90124840
has comment: http://stackoverflow.com/comment/90125405
tagged with: python
score: -2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90124957
has answer: http://stackoverflow.com/a/51579795

http://stackoverflow.com/comment/90115182
type: Comment
has text: That's happening because `self.right` or `self.left` is `None`.
type: QuestionComment
comment on: http://stackoverflow.com/q/51574633
score: 0

http://stackoverflow.com/comment/89970053
score: 0
type: Comment
has text: what if a name appears more than twice?
comment on: http://stackoverflow.com/a/51500856
type: AnswerComment

http://stackoverflow.com/comment/90167685
type: Comment
type: QuestionComment
has text: I'd have to look at it more, but why not just use `list(c) + s`?
comment on: http://stackoverflow.com/q/51600164
score: 0

http://stackoverflow.com/q/51566013
has answer: http://stackoverflow.com/a/51566040
tagged with: nonetype
score: 0
has answer: http://stackoverflow.com/a/51566081
accepted answer: http://stackoverflow.com/a/51566081
tagged with: python-decorators
has title: Why do I get an error message of NoneType object is not callable when I try to call this function?
tagged with: return
possible better answer: http://stackoverflow.com/a/51566040
tagged with: python
type: AnsweredQuestion
has body: def decorator_function(original_func): def wrapper_func(): print('Run this code before the function that needs docorated') original_func() print('Run this code after the function that needs decorated has been called') return wrapper_func() def function_needing_decorated(): print('I need to be decorated') decorator_test = decorator_function(function_needing_decorated) I'm guessing it has to do with a misunderstanding of return because I'm pretty sure I shouldn't have added the parenthesis. My question is WHY it won't work? WHY is it a NoneType but isn't a NoneType when I don't put the parenthesis there. The more detailed you are on this the better because I really need to understand this.
type: Question
answer count: 2

http://stackoverflow.com/a/51490042
has comment: http://stackoverflow.com/comment/89948922
has comment: http://stackoverflow.com/comment/89949043
has comment: http://stackoverflow.com/comment/89948974
has comment: http://stackoverflow.com/comment/89949328
has body: I think you need something like this population_size = 20 job_count = 10 operation_count = 10 max_sublot = [3, 5, 7, 6, 4, 2, 7, 9, 3, 5] mc_op = [6, 14, 8, 5, 6, 9, 4, 6, 7, 2] import numpy as np def gen_population(population_size, max_sublot, mc_op, job_count): return tuple({'LHS': [gen_lhs(length) for length in max_sublot], 'RHS': gen_rhs(np.dot(max_sublot, mc_op), job_count, max_sublot, 10, mc_op)} for _ in range(population_size)) def gen_lhs(length): return [round(np.random.uniform(0,1),2) for _ in range(length)] def gen_rhs(length, job_count, max_sublot, operation_count, mc_op): ret = [] for i in range(length): new = [] new.append(np.random.randint(job_count)) new.append(np.random.choice(max_sublot)) new.append(np.random.randint(operation_count)) new.append(np.random.choice(mc_op)) ret.append(new) return ret gen_population(population_size, max_sublot, mc_op, job_count)
has comment: http://stackoverflow.com/comment/89949070
has comment: http://stackoverflow.com/comment/89949184
answers question: http://stackoverflow.com/q/51489873
score: 0
has comment: http://stackoverflow.com/comment/89948949
type: Answer
has comment: http://stackoverflow.com/comment/89949170
has comment: http://stackoverflow.com/comment/89949459
has comment: http://stackoverflow.com/comment/89949300
has comment: http://stackoverflow.com/comment/89949270

http://stackoverflow.com/a/51533000
downvote count: 0
score: 1
has body: These are two totally different things. The first is simple assignment. foo = bar This assignment statement merely says that the name on the left-hand side now refers to the same object as the name on the right-hand side. These statements do not modify either object. Objects are neither created nor necessarily destroyed. If you lose the last name of an object, however, you will have lost the object. The CPython runtime uses reference counting as a memory management strategy, and will automatically reclaim objects that have a zero reference count. In Python, variables act simply like object names that you can create, destroy, and change what they reference. Think of them like name-tags. Now, a statement like: foo[:] = bar Is actually a method call. It can be translated to: foo.__setitem__(slice(None, None, None), bar) Observe: &gt;&gt;&gt; class Foo: ... def __setitem__(self, key, value): ... print("Key:", key, "Value:", value) ... &gt;&gt;&gt; class Bar: pass ... &gt;&gt;&gt; foo = Foo() &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; foo[:] = bar Key: slice(None, None, None) Value: &lt;__main__.Bar object at 0x104aa5c50&gt; So, really, the type of the objects control the ultimate effects of this statement. In the case of numpy.ndarray objects, slice-based assignment works similarly to list slice based assignment in that it mutates the array object in-place, with a few more caveats like broadcasting to throw into the mix. See the relevant docs: https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html#assigning-values-to-indexed-arrays
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51531713

http://stackoverflow.com/q/51489535
tagged with: python
tagged with: cmake
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/90051244
type: Question
tagged with: cmake-modules
has comment: http://stackoverflow.com/comment/90051378
has body: I am trying to build a C based Python extension that uses a ffmpeg libraries. Since there are a bunch of libraries I have to import. I used CMake. I followed the instructions from python doc The build with CMake goes fine without any issues. But when I import the library I get the following exception. Fatal Python error: PyThreadState_Get: no current thread I am using mac with python2.7.14 (installed using Brew). The following is my CMakeLists.txt cmake_minimum_required(VERSION 3.11) project(extractor C) set(CMAKE_C_STANDARD 99) set(EXECUTABLE_NAME "extractor") set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules) set(EXTRACTOR_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}") set(target_dir "bin") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -std=99") add_library(${EXECUTABLE_NAME} SHARED src/frame_extractor.c) # add_library(${EXECUTABLE_NAME} SHARED src/dipoza.c) # add_executable(${EXECUTABLE_NAME} main.c) include_directories(".") find_package(FFmpeg REQUIRED) if (FFMPEG_FOUND) message("Found FFMPEG/LibAV libraries ${FFMPEG_LIBRARIES}") include_directories(${FFMPEG_INCLUDE_DIR}) target_link_libraries(${EXECUTABLE_NAME} ${FFMPEG_LIBRARIES}) else (FFMPEG_FOUND) message("cant find libavcodec, libavformat or libavutil. add them manually!!") endif (FFMPEG_FOUND) target_link_libraries(${EXECUTABLE_NAME} ${FFMPEG_LIBRARIES}) target_link_libraries (${EXECUTABLE_NAME} "-lm") target_link_libraries(${EXECUTABLE_NAME} "-framework CoreServices") target_link_libraries(${EXECUTABLE_NAME} "-framework CoreFoundation") target_link_libraries(${EXECUTABLE_NAME} "-framework AudioToolbox") target_link_libraries(${EXECUTABLE_NAME} "-framework VideoToolbox") target_link_libraries(${EXECUTABLE_NAME} "-framework CoreAudio") target_link_libraries(${EXECUTABLE_NAME} "-framework CoreMedia") target_link_libraries(${EXECUTABLE_NAME} "-framework CoreVideo") target_link_libraries(${EXECUTABLE_NAME} "-framework AVFoundation") target_link_li…
upvote count: 6
has title: Python C Extension: Fatal Python error: PyThreadState_Get: no current thread
has comment: http://stackoverflow.com/comment/94661088
favorite count: 0
type: UnansweredQuestion
tagged with: cpython
score: 6
tagged with: python-extensions

http://stackoverflow.com/a/51526715
type: Answer
has body: From the docs: A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create(). And here is a list of supported actions: def list(self, request): pass def create(self, request): pass def retrieve(self, request, pk=None): pass def update(self, request, pk=None): pass def partial_update(self, request, pk=None): pass def destroy(self, request, pk=None): pass So no post is not directly supported but create is. So your end point would be v1/auth/accounts/create when using the a router instead v1/auth/accounts/post. I honestly prefer using class based or function based views when working with DRF. It resembles regular django views more closely and makes more sense to me when working with them. You woul write you views and urls pretty much like regular django urls and views.
answers question: http://stackoverflow.com/q/51526190
score: 0

http://stackoverflow.com/a/60826617
has body: While analysis, found out that 4 products in train dataset had one row with missing value, so a probable solution would be to refer test data set which contains item weight of 4 missing products.
answers question: http://stackoverflow.com/q/51626943
score: 0
type: Answer

http://stackoverflow.com/q/51597329
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90163953
has comment: http://stackoverflow.com/comment/90163104
has comment: http://stackoverflow.com/comment/90164426
type: Question
has comment: http://stackoverflow.com/comment/90160641
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/90163459
tagged with: image
score: 0
has comment: http://stackoverflow.com/comment/90164080
has title: PIL pillow open bmp image returns an inverted image
has body: I have two datsets on separate folders containing handwriting words, inspecting them by an image viewer I can see that the background is white and the script is black. After reading them, one image is inverted and the other is not. I think this is a bug in the PIL/Pillow library. Or, I am missing something here? from PIL import Image ... img = Image.open('the_image.bmp')
has comment: http://stackoverflow.com/comment/90164187
has comment: http://stackoverflow.com/comment/90162396
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90511329

http://stackoverflow.com/comment/90213159
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51623345
has text: Hello. I made it work. Thanks. However, I find that the method proposed below with [...] Filename + '-A1'[...] to be a bit more intuitive.
type: AnswerComment

http://stackoverflow.com/q/51514148
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51514434
tagged with: python
tagged with: tkinter
score: 1
upvote count: 1
has title: Tkinter button been pressed and run kodi software?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51514434
has body: I am new to this python programming. I'm try to make a code that let tkinter button launch an external software in raspberry pi 3. Unfortunately, the button GUI been pressed but the external software or program did not launch. The external program that link with button GUI is kodi software. Is it possible to launch the kodi software when GUI button is pressed? from tkinter import import os class Trying(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.button() def button(self): self.test = Button(self, text="Lauch", command="kodi") self.test.grid() def kodi(): os.startfile('/usr/share/applications/kodi.desktop') root = Tk() root.title("test kodi") root.geometry("150x85") app = Trying(root) root.mainloop()
type: Question

http://stackoverflow.com/a/51538357
has body: AWS API Gateway has a hard timeout limit of 29 seconds. So regardless of the timeout limit of your lambda, the API Gateway will return a timeout if it doesn't get a response after 29 seconds. Your lambda should carry on regardless though, this should be simple enough to verify in cloudwatch logs. I'm not sure what you want API Gateway to return in this scenario, but it may be enough to have lambda begin the job and return a response to API gateway that the job has begun. To do this I would have API Gateway call a Lambda that invoked the Lambda running the ECS task. To make this asynch, the invocation from Lambda to Lambda would need to be an 'Event' invocation type. Example: import boto3 import json def lambda_handler(event, context): response = client.invoke( FunctionName='&lt;ecs_lambda&gt;', InvocationType='Event', Payload=json.dumps(event) ) return { "result": "OK" }
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90045670
type: Answer
answers question: http://stackoverflow.com/q/51517996
score: 3
accepted answer of: http://stackoverflow.com/q/51517996
upvote count: 3
has comment: http://stackoverflow.com/comment/90073782
has comment: http://stackoverflow.com/comment/90071904
has comment: http://stackoverflow.com/comment/90072735

http://stackoverflow.com/q/51503789
tagged with: xmlsec
upvote count: 1
favorite count: 0
tagged with: soap
tagged with: python
has body: I'm getting an error when I try to encrypt the body of a SOAP XML message using https://pypi.org/project/dm.xmlsec.binding/. Traceback (most recent call last): File "./manage.py", line 14, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/romeroqj/.virtualenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/romeroqj/.virtualenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/romeroqj/.virtualenv/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/romeroqj/.virtualenv/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/romeroqj/Desktop/management/commands/encrypt.py", line 63, in handle encrypted_xml = enc_ctx.encryptXml(enc_data, doc.getroot()) File "_xmlsec.pyx", line 555, in dm.xmlsec.binding._xmlsec.EncCtx.encryptXml (src/_xmlsec.c:7336) File "_xmlsec.pyx", line 637, in dm.xmlsec.binding._xmlsec.lxml_safe_dealloc (src/_xmlsec.c:8132) File "src/lxml/public-api.pxi", line 29, in lxml.etree.elementFactory File "src/lxml/etree.pyx", line 1607, in lxml.etree._elementFactory File "src/lxml/classlookup.pxi", line 403, in lxml.etree._parser_class_lookup File "src/lxml/nsclasses.pxi", line 174, in lxml.etree._find_nselement_class File "src/lxml/classlookup.pxi", line 257, in lxml.etree._callLookupFallback File "src/lxml/classlookup.pxi", line 336, in lxml.etree._lookupDefaultElementClass AssertionError: Unknown node type: 3 The error occurs when I try to encrypt the content of the body (xmlsec.TypeEncContent), but it works when I try to encrypt the body element (xmlsec.TypeEncElement). Here's the code: import dm.xmlsec.binding as xmlsec from dm.xmlsec.binding.tmpl import EncData, fromstring key_mngr = x…
downvote count: 0
answer count: 0
has title: AssertionError: Unknown node type: 3 when encrypting SOAP body content with dm.xmlsec.binding
type: UnansweredQuestion
tagged with: encryption
tagged with: encryption-asymmetric
has comment: http://stackoverflow.com/comment/89977092
type: Question
has comment: http://stackoverflow.com/comment/135405195
has comment: http://stackoverflow.com/comment/89976915
score: 1

http://stackoverflow.com/a/51566540
downvote count: 0
answers question: http://stackoverflow.com/q/51566083
has comment: http://stackoverflow.com/comment/90100520
has comment: http://stackoverflow.com/comment/90100954
has comment: http://stackoverflow.com/comment/90100443
type: Answer
has comment: http://stackoverflow.com/comment/90100302
has body: Using merge with apply: df1['name'] = df1.merge( df2, how='inner', on='animal' )'name_x', 'name_y'.apply(','.join, 1) animal name 0 lion a,w 1 tiger b,c,x,y 2 tiger b,c,x,y 3 bear d,e,z 4 bear d,e,z If order is important, you can use a custom helper function: def helper(x): foo, bar = [x[i].split(',') for i in ['name_x', 'name_y']] return ','.join(foo[:1] + bar + foo[1:]) df1.merge(df2, how='inner', on='animal')'name_x', 'name_y'.apply(helper, 1) 0 a,w 1 b,x,y,c 2 b,x,y,c 3 d,z,e 4 d,z,e dtype: object
score: 1
upvote count: 1

http://stackoverflow.com/comment/89994043
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51512672
score: 0
has text: Are each of the coordinates within the coordinate groups on separate lines in the text file and is there a blank line that separates each of the coordinate groups?

http://stackoverflow.com/a/51614602
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51614516
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51614516
has body: You probably have a space or newline at the end of i Try: print(glob.glob("*"+ i.strip() +"*.txt"))
type: AcceptedAnswer

http://stackoverflow.com/a/51510110
upvote count: 1
has body: Your question is missing some info, so I did the best that I could in answering your question. In formulating my answer, I have taken the assumption that when you say "distances," you mean distances in reality, such as meters, feet, lightyears, etc. I have a method that works only for "flat" images (meaning, the picture is not captured from the side) but works nonetheless. It relies on the PIL and NumPy libraries – PIL for loading the image into Python, and NumPy for converting it into a relatively easy-to-use 3-dimensional array. The script uses two given points and the distance formula to calculate the distance between the two points on the image in pixels. To get the real units, divide the distance by the image's width, resulting in a number between 0 and 1, and multiply that number by the width of the image in reality – that is, the span of the rightmost and leftmost pixels of the image in real life, like 30 centimeters or 2.3 miles. Click here for a REPL so you can try it for yourself. import numpy as np from PIL import Image from math import sqrt img = Image.open("my_picture.jpg") pixels = np.array(img) width, height, channels = pixels.shape actual_width = ... actual_units = ... (x1, y1) = ... (x2, y2) = ... pixel_distance = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) actual_distance = (pixel_distance / width) * actual_width print(f"The distance between the two points is about {actual_distance:.3f} {actual_units}") Side note: the final line contains an f-string, which was only added in Python version 3.6. Please let me know if this is not what you were asking for or if there is any other way I can help.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51509808
type: Answer
has comment: http://stackoverflow.com/comment/90108950

http://stackoverflow.com/a/51601918
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90333111
answers question: http://stackoverflow.com/q/51518601
score: 0
upvote count: 1
has body: Just for fun, here is the closest approximation to a one-liner: from functools import reduce big_list = [2, 1, 2, 3, 1, 2, 4] sub_list = [1, 2] result = reduce(lambda r, x: r[:1]+([1]+r[2:-r[1]],[min(len(r[0]),r[1]+1)]+r[2:])[r[-r[1]:]!=r[0]]+[x], big_list+[0], [sub_list, 1])[2:-1] Don't trust that it works? Check it on IDEone! Of course it's far from efficient and is disgustfully cryptic, however it should help to convince the OP to accept @Mad Physicist's answer.

http://stackoverflow.com/comment/90210591
comment on: http://stackoverflow.com/q/51622278
has text: @asdfg Just added it.
score: 0
type: Comment
type: QuestionComment